diff --git a/MANIFEST.json b/MANIFEST.json index 40c4dd5667912225fdc57dbc1f10758dcf2d53a8..b53db226b9b973b86853379e4ae07d8b7c0b4f1a 100644 --- a/MANIFEST.json +++ b/MANIFEST.json @@ -1,196 +1,476 @@ { "files": { "README.md": { - "bytes": 966, - "sha256": "bd0d465f995e6e88f99a624901bbf6577b31c7230a4ff959ca48516be0339af7" + "bytes": 1033, + "sha256": "4788fd92c347b0f30ec74e278f1c8d24e91eea0e1fd6106178bb29876e0bc4bd" }, "SOURCE_LOCK.json": { - "bytes": 328, - "sha256": "df3acef0a949edac8c6ec87a15e4d7c5a87534a83d49186549699a59bdf22f98" + "bytes": 332, + "sha256": "a3f67ba6d525a1fdffbc87093b0a2b4ee12b7c482b95050dfd7b27b09d19143d" }, - "components/skillsdesk/.dockerignore": { + "components/qemedia/.dockerignore": { "bytes": 29, "sha256": "60c9bdd905fcf45ac485c680d32e9773962cf061b6f041dcddd033911558a672" }, - "components/skillsdesk/ADAPTER_NOTICE": { - "bytes": 167, - "sha256": "843b71a3a9f9de899cbb9d260d55c9bd082f3df2b7771a1c31100ce5767a0a53" + "components/qemedia/ADAPTER_NOTICE": { + "bytes": 301, + "sha256": "5991dc74fa45e42c24120d3ddf4fd39c92f908f44986c71cf658c5b12deda80b" }, - "components/skillsdesk/Dockerfile": { - "bytes": 1010, - "sha256": "4f047d60bc07987131be2c9cf0662c6e6feef91125adda81eda04d4b88882f6b" + "components/qemedia/Dockerfile": { + "bytes": 978, + "sha256": "0edae3727291af6b7ed7b3d38bf94d4aaa2c42c01c4d748d676ef9045de1c8df" }, - "components/skillsdesk/LICENSE": { - "bytes": 11358, - "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" + "components/qemedia/LICENSE": { + "bytes": 1074, + "sha256": "e0a8e97900a1184396b65bca8507d5c7b1a6df58537b61722dfe0f416990f0e2" }, - "components/skillsdesk/NOTICE": { - "bytes": 676, - "sha256": "dca813e02ab76d4bc5afdcd2a2de3480d3fc0a7a710edea24c395adf23a99883" + "components/qemedia/README.md": { + "bytes": 293, + "sha256": "1f6d860d8285f6297e5381c08925a1ece2bf88eb5b0344b10740269e222a060d" }, - "components/skillsdesk/README.md": { - "bytes": 303, - "sha256": "11775067d2cfb4c254084dd741f0b13a1a5058081c171712bdb9923d430a9cd4" + "components/qemedia/SOURCE_MANIFEST.json": { + "bytes": 11903, + "sha256": "f97c7ed6f032ebf9e6276f6156c447a2f128739858fc243143d72b86443292f3" }, - "components/skillsdesk/SOURCE_MANIFEST.json": { - "bytes": 3982, - "sha256": "789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99" + "components/qemedia/THIRD_PARTY_NOTICES": { + "bytes": 4448, + "sha256": "755b9132babde91fb34bf29a7759c3cead1299484335fcafdb057fd207f210b8" }, - "components/skillsdesk/UPSTREAM_DOCKERFILE": { - "bytes": 1899, - "sha256": "2c07033febd78777deeff04350ae6887c9bb170b152d38c26cf148efa1b75d1e" + "components/qemedia/UPSTREAM_DOCKERFILE": { + "bytes": 2415, + "sha256": "acb6b642cd8d1c4f66e8a82a2cc97c9d4643ca484422e225505c0ea2b739e146" }, - "components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt": { - "bytes": 666, - "sha256": "90e6e08d4269b5bb8308b5f2f05c61aa0cb9b71643b6abe6e47b34795828dd1e" + "components/qemedia/runtime/qemedia_compat/__init__.py": { + "bytes": 66, + "sha256": "bd90e5f33d8c325c978e826c5e7a73e4ad73ff535f367ddfed0dec3d52470ade" }, - "components/skillsdesk/runtime/common/__init__.py": { - "bytes": 1, - "sha256": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b" + "components/qemedia/runtime/qemedia_compat/environment.py": { + "bytes": 7410, + "sha256": "0fbea553dc22fa2fd72a4590c2c008eeefaa4af5654a2e9936465c18c79c9149" }, - "components/skillsdesk/runtime/common/contracts.py": { - "bytes": 1015, - "sha256": "b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1" + "components/qemedia/runtime/qemedia_compat/server.py": { + "bytes": 543, + "sha256": "1d41688c822b842c70f32502d627c252fcd3526c7be74d6880f2f86d06df981a" }, - "components/skillsdesk/runtime/common/models.py": { + "components/qemedia/upstream/qe_arena/__init__.py": { + "bytes": 72, + "sha256": "f1ce27b1c58f9547059e7f820aa65c1a8d8313144855ee8845b2eca91f7e0db3" + }, + "components/qemedia/upstream/qe_arena/app.py": { + "bytes": 791, + "sha256": "2925e44219fdef6310ac1e2b60532e3ba1f1e768b33e65f14f1f5e8f86b33510" + }, + "components/qemedia/upstream/qe_arena/corpus/__init__.py": { + "bytes": 5497, + "sha256": "978aabadc5044616ff28ab7be69a2e9ff48f1fd82494a6897f4f2b8716283a08" + }, + "components/qemedia/upstream/qe_arena/corpus/aggregate_risk_factors.py": { + "bytes": 2512, + "sha256": "0485dfbc2676a1f666958935602cc2f347e5fcd95b6bfcd32e8af13cafe07e35" + }, + "components/qemedia/upstream/qe_arena/corpus/alternate_chat_roles.py": { + "bytes": 2402, + "sha256": "f999a088228120810c986f249964ba83d7a54a4853c9bebcbf61313b4362247e" + }, + "components/qemedia/upstream/qe_arena/corpus/amortization_schedule.py": { + "bytes": 2769, + "sha256": "4b4f6e1280956988736c2401747ed0c3d633eedfe38e7d24ec815773f5c21711" + }, + "components/qemedia/upstream/qe_arena/corpus/api_complexity_level.py": { + "bytes": 2122, + "sha256": "21517da739674bdc2b22efe9c2a2a7a85d47a7033aae3e24b2c1da8b4ac21684" + }, + "components/qemedia/upstream/qe_arena/corpus/artifact_retention_keep.py": { + "bytes": 2817, + "sha256": "71db4461633e0ad524e11c2384d75675331a515778ce4a8b675c6f738c94a02c" + }, + "components/qemedia/upstream/qe_arena/corpus/backoff_schedule.py": { + "bytes": 2091, + "sha256": "1f1937c25f4717a49a6e809ea81cc20da035f6aa843d4f47ce111b585e3ab4a2" + }, + "components/qemedia/upstream/qe_arena/corpus/badge_dimensions.py": { + "bytes": 2054, + "sha256": "2661b8a01fb4d7d1a31169592eaae370b3d4260d6b32187ce4427ffbcfa097ea" + }, + "components/qemedia/upstream/qe_arena/corpus/baseline_verdict.py": { + "bytes": 2121, + "sha256": "b1d44ea5c1b774f8572374e73468ca34483e3b382c982c28a368549da94656d5" + }, + "components/qemedia/upstream/qe_arena/corpus/booking_conflicts.py": { + "bytes": 2577, + "sha256": "01764d4994630e38a91a6599f90142a9b145084dbd5971c564727ac9855f97f8" + }, + "components/qemedia/upstream/qe_arena/corpus/boundary_violations.py": { + "bytes": 4373, + "sha256": "7f70d489eefbdae5794354fa457a39dc50eb0209929cb0f3a9f9493b41adc88a" + }, + "components/qemedia/upstream/qe_arena/corpus/brace_delta.py": { + "bytes": 1937, + "sha256": "04d411ac8a666d3916c13090c7658e5cc516028ced9b0db45a334062d96683c5" + }, + "components/qemedia/upstream/qe_arena/corpus/calibration_fit.py": { + "bytes": 2530, + "sha256": "6f0982869b0ef19ec7b95863008ea45b1a46dbd46108ee24b44338a383a37d23" + }, + "components/qemedia/upstream/qe_arena/corpus/chat_completion_result.py": { + "bytes": 4015, + "sha256": "42b4727623069a0e774e0d70be6cb9869d871b377ddb6421c60bfa78bd3be126" + }, + "components/qemedia/upstream/qe_arena/corpus/claim_steal_priority.py": { + "bytes": 2528, + "sha256": "f5c6486256438b89565cc1edcaf016d6e91f3c81067a77a30c9792cac7d0ef39" + }, + "components/qemedia/upstream/qe_arena/corpus/compare_versions.py": { + "bytes": 2384, + "sha256": "a77352fd67a18a9c24c3fe697c9310b079c998dc853c2f49eba1a2c877742a62" + }, + "components/qemedia/upstream/qe_arena/corpus/complexity_bucket.py": { + "bytes": 2333, + "sha256": "5e4e65b458e8cd2e9723206e43ea3a85d37df8b82c9f15e19f4da5ce26dd72ff" + }, + "components/qemedia/upstream/qe_arena/corpus/compound_interest.py": { + "bytes": 2693, + "sha256": "3979785d451cc4473ec2b057a404f0a8ea930bd11ce34bedea06f1b953ee9c08" + }, + "components/qemedia/upstream/qe_arena/corpus/convert_timecode.py": { + "bytes": 2696, + "sha256": "30ff0142461a624790a13766f9463c6fd6f21991442e5e37d46febd51f2ca7ad" + }, + "components/qemedia/upstream/qe_arena/corpus/coverage_gap_severity.py": { + "bytes": 2027, + "sha256": "af3e694760997b353678c7350b08e43ed26de256792221420006e5d4837712d5" + }, + "components/qemedia/upstream/qe_arena/corpus/crop_to_aspect.py": { + "bytes": 2252, + "sha256": "f85c6167be7fe0094e36b90d19fb4e382a2e804a34dc96fa09f379caf97d5904" + }, + "components/qemedia/upstream/qe_arena/corpus/debounce_switch.py": { + "bytes": 2416, + "sha256": "61e8975cc643b0bd4d10656d48a77a7314b5e13382794bdcbecf19f2a80b3186" + }, + "components/qemedia/upstream/qe_arena/corpus/decay_table.py": { + "bytes": 2553, + "sha256": "949197b79f96f244ccba1b44236510ec65d8c9aace59850cde4949697791024f" + }, + "components/qemedia/upstream/qe_arena/corpus/efficiency_reward.py": { + "bytes": 2167, + "sha256": "c5033c7d0a147c46e9cf1659187879b00e8f253725f1fcc00b6c4e5529c9685b" + }, + "components/qemedia/upstream/qe_arena/corpus/expense_violations.py": { + "bytes": 2567, + "sha256": "11d505901f9d2e00cc5b475d9cca75b4770db77345c1645b10e70620710a70b0" + }, + "components/qemedia/upstream/qe_arena/corpus/find_stop.py": { + "bytes": 2930, + "sha256": "284d4fcd6c5cb23efc4282659991d9a403b46c0d836641071ad7079d8d2c8d0d" + }, + "components/qemedia/upstream/qe_arena/corpus/flakiness_pattern.py": { + "bytes": 2283, + "sha256": "b3b94bcfe78f97b00187e7fe9783a8ae04b9a9b6af6d788f445f64bd52021aa0" + }, + "components/qemedia/upstream/qe_arena/corpus/flaky_hunter_reward.py": { "bytes": 1941, - "sha256": "6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd" + "sha256": "11c670fbe537cbeeaa101d9b9db49519f5ebd4cca82b7ccfd66d5d68e352e5ba" + }, + "components/qemedia/upstream/qe_arena/corpus/flaky_run_summary.py": { + "bytes": 2235, + "sha256": "f6ebbaffe1dd8aaccef7ad8ce48d8dfa60bacc8a44051880057c52b163e7748b" + }, + "components/qemedia/upstream/qe_arena/corpus/format_duration.py": { + "bytes": 1843, + "sha256": "7e0cf537d1bd38fdbc474bc259a52fbf23f095f35661586d771eca0561481eb0" + }, + "components/qemedia/upstream/qe_arena/corpus/gguf_loader.py": { + "bytes": 4031, + "sha256": "e232fbfe97a36cedf848caa11b9bf51828c5f4c6fe6ad3bf40133c6bc7deabd7" + }, + "components/qemedia/upstream/qe_arena/corpus/gguf_special_ids.py": { + "bytes": 4671, + "sha256": "b5fc54e4b3f6b45af2af289a746fe48d948e806b43910920e6ee31c81bbd805e" + }, + "components/qemedia/upstream/qe_arena/corpus/glob_match.py": { + "bytes": 2785, + "sha256": "52d8da6da1348af21303785a5dabfe36a42f7efeaed9b326b21898387a3e6536" + }, + "components/qemedia/upstream/qe_arena/corpus/income_tax.py": { + "bytes": 2997, + "sha256": "ce28e349ed362052dd0184dc4f1e215344831edc2f74ebe8438c470964fc70a3" + }, + "components/qemedia/upstream/qe_arena/corpus/integer_edge_values.py": { + "bytes": 2422, + "sha256": "edd468fbc9d11830559fbcc2bfb1d7afe35c71980432bb91c87d8c3571a704b7" + }, + "components/qemedia/upstream/qe_arena/corpus/ip_allowlist_match.py": { + "bytes": 3267, + "sha256": "94bc28736f587e3cc350fef83ba95fe70dc44db627bcb037f854332f6b52e7fd" + }, + "components/qemedia/upstream/qe_arena/corpus/is_collection_endpoint.py": { + "bytes": 2344, + "sha256": "87db0af0b61c0b95b0d8acf9235835db9631f9471d0e7dc29b0296abc76bccde" + }, + "components/qemedia/upstream/qe_arena/corpus/latency_percentiles.py": { + "bytes": 2250, + "sha256": "7d91f4eb06374851748cbd3e33ae5f3d2059a491572449d4fc700ecaaed1431c" + }, + "components/qemedia/upstream/qe_arena/corpus/login_rate_limit.py": { + "bytes": 2464, + "sha256": "814fc40372c1ece5068b04848f9c8a2a9069d504cf364df62c00a905d0ec777c" + }, + "components/qemedia/upstream/qe_arena/corpus/loudness_gain.py": { + "bytes": 2668, + "sha256": "ecc262d19d2b27970901017aa4a006ad2ce97861866ccddae2a9c876c4bbec37" + }, + "components/qemedia/upstream/qe_arena/corpus/mail_merge.py": { + "bytes": 2873, + "sha256": "2c3ec2cb2f5e050ff03d772675c372053fe3eb957f505a33d2d127916ee283bf" + }, + "components/qemedia/upstream/qe_arena/corpus/maintainability_index.py": { + "bytes": 1856, + "sha256": "48972588b8f75f1132aaf0eaa112a35875833b7dc661e3c41ff6972f3ce29dd5" + }, + "components/qemedia/upstream/qe_arena/corpus/maintenance_status.py": { + "bytes": 2875, + "sha256": "201bad40ff156e6a0caec2577011286262178000435aacaec83c603ba02aa4f8" + }, + "components/qemedia/upstream/qe_arena/corpus/merge_intervals.py": { + "bytes": 2602, + "sha256": "fd5b0f08e59fc763734cdb43d4cd893ce851403281a806902f5945ce71e7e7cd" + }, + "components/qemedia/upstream/qe_arena/corpus/mod_inverse.py": { + "bytes": 1845, + "sha256": "888558da6833e82d1b2dafadf39aa87609cf5c4bcc96345a4e37ac92cfd1d0de" + }, + "components/qemedia/upstream/qe_arena/corpus/mod_pow.py": { + "bytes": 1729, + "sha256": "58cdc61459945cdd9bf20ab09cfa422c85148d76fecfc70567ef81b1240c2f36" + }, + "components/qemedia/upstream/qe_arena/corpus/networkdays.py": { + "bytes": 2293, + "sha256": "1c72218af8a816d24fc7ba7d88901c83db49c056da34efea5f2ba491a77493d2" + }, + "components/qemedia/upstream/qe_arena/corpus/normalize_rational.py": { + "bytes": 2629, + "sha256": "62e849358e01be48618529568005a1b487b411bdc18a01b4c226b824f77320df" + }, + "components/qemedia/upstream/qe_arena/corpus/parse_cron_field.py": { + "bytes": 3288, + "sha256": "6275cc4556df344a4dfccbcdf5930e9561bcb27b93fcb247c9707a84c48f3231" + }, + "components/qemedia/upstream/qe_arena/corpus/parse_max_age.py": { + "bytes": 1593, + "sha256": "52df1c52ecfe9db206a6322350204d2bbbaeb2fe6bd192d8b98d56de8739bf50" + }, + "components/qemedia/upstream/qe_arena/corpus/parse_signature_header.py": { + "bytes": 2405, + "sha256": "cf81c249d3ff4092557d20bdcf210ce52cbe4c9e2e5e8634d279a46568d2f4df" + }, + "components/qemedia/upstream/qe_arena/corpus/password_violations.py": { + "bytes": 3045, + "sha256": "5d1a27cea4b7db6b2b2484015dfc73e61ddc04b3d021da8adfb1788ebf0dd54c" + }, + "components/qemedia/upstream/qe_arena/corpus/pattern_effectiveness.py": { + "bytes": 2379, + "sha256": "ccf4a9d4183523e3b82f95cf0f5f18efe86881ece0d7274f24f5236233aa4f13" + }, + "components/qemedia/upstream/qe_arena/corpus/pressure_check.py": { + "bytes": 3417, + "sha256": "c7b17812aa575ee19db876d526f0770ad6ee591e6aa2bc624e05527cc1ef7df2" + }, + "components/qemedia/upstream/qe_arena/corpus/quality_gain_reward.py": { + "bytes": 2028, + "sha256": "cca54e5fa4dfed47ac23f06111a357fb1a2f9fbd3b29a8d9873d268a91a754ec" + }, + "components/qemedia/upstream/qe_arena/corpus/quality_grade.py": { + "bytes": 2115, + "sha256": "aafb0bab705f85093cecdfa13bdce9a1f23bbf055b60f50783abc46f020b8fef" + }, + "components/qemedia/upstream/qe_arena/corpus/reconcile_invoices.py": { + "bytes": 3579, + "sha256": "169e88a7162bc1e2a798b76ee491191ca44fca3051d7eb392b56b7672139142e" + }, + "components/qemedia/upstream/qe_arena/corpus/round_sig_figs.py": { + "bytes": 2350, + "sha256": "361cbe3b3c5e2da8317b2cf703dc11405d4c10ad2d62551c65388028238f4fb5" + }, + "components/qemedia/upstream/qe_arena/corpus/safe_join.py": { + "bytes": 2508, + "sha256": "368365c0bd5b318b63d1614caba8bd4f752011f6beecf3ede4fbb42f137441d7" + }, + "components/qemedia/upstream/qe_arena/corpus/sample_variance.py": { + "bytes": 1906, + "sha256": "a26bc6ef76d5dfbc4b0abff3f0189f6bd181f6934bcb6dee3410ab752316223d" + }, + "components/qemedia/upstream/qe_arena/corpus/select_bitrate_rung.py": { + "bytes": 2366, + "sha256": "51ae093e2baeda053434e2e223827384124290ed5317bf160f0b3df366ef02eb" + }, + "components/qemedia/upstream/qe_arena/corpus/shift_cue.py": { + "bytes": 2795, + "sha256": "cce40f8f9266e58918b174e82d1b167523a4df1b78a53f07af06fe43d9c9100e" + }, + "components/qemedia/upstream/qe_arena/corpus/slew_limit.py": { + "bytes": 2885, + "sha256": "540a4e6c04b1e3cc78cf69e42897d6680840c513ffcc86eeba8f2aa735d30cf6" + }, + "components/qemedia/upstream/qe_arena/corpus/spec_readiness_score.py": { + "bytes": 4578, + "sha256": "02936fcc7e5931cad5a46b286d098ae2d34698449f2eaa190eaa44f9785543da" + }, + "components/qemedia/upstream/qe_arena/corpus/split_generic_params.py": { + "bytes": 2201, + "sha256": "9188e0c8045fa0d8e1a7a82153f6ccc791e075dd7a6f3b793abd117bb1064275" + }, + "components/qemedia/upstream/qe_arena/corpus/streamable_len.py": { + "bytes": 3235, + "sha256": "d3aac59af147f657bbe61bb45e368d78cee587be7a4fa58208410fd5a9e3d26c" + }, + "components/qemedia/upstream/qe_arena/corpus/string_length_boundaries.py": { + "bytes": 2253, + "sha256": "62a7ac1680df0375cae8ecb6cf08a3520375cb9c8dea94299a30551d0abe479e" + }, + "components/qemedia/upstream/qe_arena/corpus/threshold_compliance.py": { + "bytes": 4277, + "sha256": "13361068ea0f1ebaacadb264bfec120e990341cf66154f77a1a110777be1754e" + }, + "components/qemedia/upstream/qe_arena/corpus/token_claims_check.py": { + "bytes": 3488, + "sha256": "081ef70cde049750026cc4f60794f46a74a86424c12d73ea5c278b19563b2e77" }, - "components/skillsdesk/runtime/skillsdesk_compat/__init__.py": { - "bytes": 0, - "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + "components/qemedia/upstream/qe_arena/corpus/token_jaccard.py": { + "bytes": 1948, + "sha256": "9d10c0da4d0375ea05c99d0e5d2dd57a4bedf1a4fa5a5f48d6cc9344177f19bb" }, - "components/skillsdesk/runtime/skillsdesk_compat/environment.py": { - "bytes": 8142, - "sha256": "22a0011808344bdeeb635082afbacac2810bdf14e617ac72011e211dfa14c176" + "components/qemedia/upstream/qe_arena/corpus/trace_sampling_decision.py": { + "bytes": 2874, + "sha256": "6e20c250fb2d01cf06ed5b099d67089f43f7851e90224399f5865aee539d4f32" }, - "components/skillsdesk/runtime/skillsdesk_compat/server.py": { - "bytes": 457, - "sha256": "634fd3bd58cb4ade2c5d959ae7fb09dfb24b102830170c00a140a3ff949e590c" + "components/qemedia/upstream/qe_arena/corpus/truncate_to_token_budget.py": { + "bytes": 2451, + "sha256": "5246d62082d3a37dd57e6d3510ea489a4de4c44a31e5bddb2d4d438817b0c43b" }, - "components/skillsdesk/upstream/openenv.yaml": { - "bytes": 403, - "sha256": "88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e" + "components/qemedia/upstream/qe_arena/corpus/uncovered_line_ranges.py": { + "bytes": 1864, + "sha256": "9feb8f950e2cff5904eddba37a15e16a8888a7cb8f5dc893e74808a36c6f1876" }, - "components/skillsdesk/upstream/terminal_desk/__init__.py": { - "bytes": 0, - "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + "components/qemedia/upstream/qe_arena/corpus/validate_csv_row.py": { + "bytes": 2764, + "sha256": "bc332a39e0143f24ee326b0f9343150a22f47fa420dc29ecf1cba816385a1d43" }, - "components/skillsdesk/upstream/terminal_desk/core/__init__.py": { - "bytes": 0, - "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + "components/qemedia/upstream/qe_arena/corpus/vuln_priority_bucket.py": { + "bytes": 1889, + "sha256": "3132a4152e1baf9061b0e70d3192e0617e8de735195eb560dcfee5011c14f6fc" }, - "components/skillsdesk/upstream/terminal_desk/core/grading.py": { - "bytes": 10754, - "sha256": "d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9" + "components/qemedia/upstream/qe_arena/corpus/wilson_interval.py": { + "bytes": 1922, + "sha256": "28e98e2f9b24bb36171fa2f5c5c9d78be23e193615b265aad092bec771eb8021" }, - "components/skillsdesk/upstream/terminal_desk/core/shell.py": { - "bytes": 4743, - "sha256": "e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d" + "components/qemedia/upstream/qe_arena/domains.py": { + "bytes": 1191, + "sha256": "13bb7b068896d5377b8f969c504dde01875df8eef8a0b341348e45bcea5f991b" }, - "components/skillsdesk/upstream/terminal_desk/families/__init__.py": { - "bytes": 2614, - "sha256": "3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411" + "components/qemedia/upstream/qe_arena/edit_budget.py": { + "bytes": 28000, + "sha256": "4b27436ca7c4eed5e7dda34ccfac6c97eb413cf024274793d4d1cf47b50f9494" }, - "components/skillsdesk/upstream/terminal_desk/families/base.py": { - "bytes": 1915, - "sha256": "a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f" + "components/qemedia/upstream/qe_arena/environment.py": { + "bytes": 10774, + "sha256": "9675b6598456b5a8dbfe57eb6e6847998d86f2c93722caff3c8a3716d6ecc102" }, - "components/skillsdesk/upstream/terminal_desk/families/compute.py": { - "bytes": 10755, - "sha256": "60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3" + "components/qemedia/upstream/qe_arena/flaky.py": { + "bytes": 22246, + "sha256": "0db273642496825ec8f8924a164093df1191b29c92ac83b5497261373c20f768" }, - "components/skillsdesk/upstream/terminal_desk/families/compute2.py": { - "bytes": 12743, - "sha256": "91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33" + "components/qemedia/upstream/qe_arena/flaky_gen.py": { + "bytes": 13599, + "sha256": "46e2198bcbe9d415bf775f845a358c2eaa26d390a5aa62d3b806f07b5803fab1" }, - "components/skillsdesk/upstream/terminal_desk/families/constraints.py": { - "bytes": 9807, - "sha256": "25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0" + "components/qemedia/upstream/qe_arena/flaky_templates.py": { + "bytes": 19057, + "sha256": "2272e0617a3a079d2e389bf50d62c4cc5da4ec005d2d68239bdfbf7e795fda92" }, - "components/skillsdesk/upstream/terminal_desk/families/constraints2.py": { - "bytes": 14665, - "sha256": "411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4" + "components/qemedia/upstream/qe_arena/guest_harness.py": { + "bytes": 13974, + "sha256": "5b389cc8ab64218d3bdcc500f584ef0b78da4b68379bfb014e095d755ccdcdb1" }, - "components/skillsdesk/upstream/terminal_desk/families/evidence.py": { - "bytes": 10896, - "sha256": "c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045" + "components/qemedia/upstream/qe_arena/keys/manifest_ed25519.pub": { + "bytes": 113, + "sha256": "ea2b370db92d82e1a0719ecf3416eeafdb7a14a524a94f6d6cd32a5f06b21106" }, - "components/skillsdesk/upstream/terminal_desk/families/evidence2.py": { - "bytes": 14514, - "sha256": "d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60" + "components/qemedia/upstream/qe_arena/manifest.py": { + "bytes": 6932, + "sha256": "1911ef5d3696695364871da7be9744fd7c81d51fe81ae3c137341dd1b06c8494" }, - "components/skillsdesk/upstream/terminal_desk/families/repair.py": { - "bytes": 17806, - "sha256": "a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781" + "components/qemedia/upstream/qe_arena/mutation.py": { + "bytes": 43554, + "sha256": "28a7abc5213c5a1504151d23148695e7f09e4441b39e941377cb7265ba6ff4de" }, - "components/skillsdesk/upstream/terminal_desk/families/repair2.py": { - "bytes": 20016, - "sha256": "1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6" + "components/qemedia/upstream/qe_arena/runtime_pins.json": { + "bytes": 179, + "sha256": "97f080e2505ba4c6034fcc3f0322d9ecd8b9f9852ac19e424cc9273ccd0a9c77" }, - "components/skillsdesk/upstream/terminal_desk/families/transform.py": { - "bytes": 6815, - "sha256": "d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1" + "components/qemedia/upstream/qe_arena/sandbox.py": { + "bytes": 34230, + "sha256": "92faaac323c0b524c0181008c305134fc57d2e4c6af1ea6fbf919b48ec9ea03a" }, - "components/skillsdesk/upstream/terminal_desk/families/transform2.py": { - "bytes": 13415, - "sha256": "2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2" + "components/qemedia/upstream/qe_arena/shell.py": { + "bytes": 26494, + "sha256": "4e9aabefa6f23793a05804ec413aaa5d1c5125365156f22cdb50ff600808d34d" }, - "components/skillsdesk/upstream/terminal_desk/families/util.py": { - "bytes": 3899, - "sha256": "0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832" + "components/qemedia/upstream/qe_arena/skills/__init__.py": { + "bytes": 6616, + "sha256": "c6b045c7b62b762ae4a56b13fcc61bf997ffd710494f9882e775f533dfe8c522" }, - "components/skillsdesk/upstream/terminal_desk/models.py": { - "bytes": 1750, - "sha256": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4" + "components/qemedia/upstream/qe_arena/skills/_common.py": { + "bytes": 1640, + "sha256": "ec722ad0aa0903fbca443dc8325f2569853b7191edfc525602d3cd0ddaf56037" }, - "components/skillsdesk/upstream/terminal_desk/reserved/__init__.py": { - "bytes": 647, - "sha256": "012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330" + "components/qemedia/upstream/qe_arena/skills/formal.py": { + "bytes": 24536, + "sha256": "da87595287e1d253512564769274e3063f262fce0d4d4ea0ef5b26d9285a72e0" }, - "components/skillsdesk/upstream/terminal_desk/reserved/compute.py": { - "bytes": 12349, - "sha256": "e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083" + "components/qemedia/upstream/qe_arena/skills/media.py": { + "bytes": 18987, + "sha256": "005eabea342ba948e6b68dcc341f3756a8ebdd5fb44830cb13bb482a16ef200c" }, - "components/skillsdesk/upstream/terminal_desk/reserved/constraints.py": { - "bytes": 15358, - "sha256": "ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0" + "components/qemedia/upstream/qe_arena/skills/science.py": { + "bytes": 23268, + "sha256": "f198046eb6e9d0610cd966f5e7a99d27e9da2e3f23e3687ecd42f4a5649aab98" }, - "components/skillsdesk/upstream/terminal_desk/reserved/evidence.py": { - "bytes": 12524, - "sha256": "e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0" + "components/qemedia/upstream/qe_arena/skills/subtitles.py": { + "bytes": 8058, + "sha256": "872054f7309500113beab2c853bfeceebd146e60dc36d42f42f9e98e6c4a7b84" }, - "components/skillsdesk/upstream/terminal_desk/reserved/repair.py": { - "bytes": 16541, - "sha256": "121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5" + "components/qemedia/upstream/qe_arena/tasks.py": { + "bytes": 29386, + "sha256": "c540dc8eafd3ac648f768b17682ecb1f8f3bd3e14eed9a353c4021c427dc80bd" }, - "components/skillsdesk/upstream/terminal_desk/reserved/transform.py": { - "bytes": 11909, - "sha256": "bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf" + "components/qemedia/upstream/qe_arena/terminal_app.py": { + "bytes": 801, + "sha256": "d5a630210e1a8330ec3cc00a5b43d7d92b110a6d0eb8ec5e83d3bba13e85fcc0" }, - "components/skillsdesk/upstream/terminal_desk/server/__init__.py": { - "bytes": 0, - "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + "components/qemedia/upstream/qe_arena/terminal_env.py": { + "bytes": 11168, + "sha256": "6ea5cfcffc292e52ead2687728ad6d9c040dfaf32a5610386ac6514d4b1438b3" }, - "components/skillsdesk/upstream/terminal_desk/server/app.py": { - "bytes": 802, - "sha256": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8" + "components/qemedia/upstream/qe_arena/wasi_fs.py": { + "bytes": 14300, + "sha256": "71f35970518b637bfa50fa79897d6f79d065e4531211af402f91a9dba4d31f38" }, - "components/skillsdesk/upstream/terminal_desk/server/environment.py": { - "bytes": 6820, - "sha256": "82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319" + "components/qemedia/upstream/qe_arena/wasi_worker.py": { + "bytes": 17237, + "sha256": "6e81b271a5910977f38deba39ccde6465d70e23e9ed42cbec51f02a6e237c71e" }, "schema.json": { - "bytes": 1911, - "sha256": "10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4" + "bytes": 2557, + "sha256": "c486d87e05b69ab133dd04cba072d5a39de8fda53c9a2f6fd5995570384724b0" }, "tasks.jsonl": { - "bytes": 17061, - "sha256": "2a3fe43c4b55a123f5a80f0c2d60c15f86d94470cd2a4fc86adbaec85c12054b" + "bytes": 2738, + "sha256": "7e16aa89ecd785fe76b4c3b1ef887845d33dbf293a849578a02efafb0da92c00" }, "validate_dataset.py": { - "bytes": 8206, - "sha256": "db3704682eefb03f47a6c951865e9fb2113851f8bdf0266f6c4f517961f2973b" + "bytes": 11813, + "sha256": "3ab9912b176d4555f7d38828bd66854b60311dc42c2e25c665cb8296fffaf9db" } } } diff --git a/README.md b/README.md index f36accc432c6ce086d46ca2e6f32d9a9199c7a70..9540cd027fc9edf14bf7e99d6e806e9879338a31 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ --- language: - en -license: apache-2.0 +license: mit task_categories: - reinforcement-learning configs: @@ -11,10 +11,10 @@ configs: path: tasks.jsonl --- -Twenty original Skills Desk tasks covering evidence matching, computation, data transformation, code repair and constrained planning. +Two original QE media task cells cover timecode arithmetic, catalogue normalization, crop dimensions and subtitle retiming. -Each task ID identifies a fixed original instance. Use the tools shown at reset and `op=finish` to grade the artifact. Reward is one when all original checks pass, otherwise zero. Code repair tasks also run hidden-input checks. +Reset with `task_id` set to `qe_skill-media-d2` or `qe_skill-media-d1`. An explicit seed reproduces the original instance; omitting it draws a fresh instance. Use the native `action_type` values `exec`, `write_file` and `evaluate`. Reward is one when all original checks on the output artifact pass, otherwise zero. -Run one episode per fresh sandbox, with one active session. Each episode allows 32 actions, 8192 completion tokens and 16384 context tokens; later observations count toward completion tokens. Commands have the original 20-second limit. +Run one active session per fresh sandbox. Episodes allow 32 actions, 4096 completion tokens and 8192 context tokens. Observations after reset count toward completion tokens. Commands have the original 30-second limit. -Task IDs and pinned source references are in `tasks.jsonl`. Original licenses and attribution are in `components/skillsdesk/`. Run `python3 -B validate_dataset.py` to verify the file inventory. +Pinned source and task metadata are in `tasks.jsonl` and `components/qemedia/`. Original modules and their import dependencies are included. Run `python3 -B validate_dataset.py` to verify the file inventory. diff --git a/SHA256SUMS b/SHA256SUMS index a9e84d01c4ffab17e81bec6cbd73659b4b7e74cf..0068c4022289fe667ccb0bccfc5912f51b95b26e 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,48 +1,118 @@ -bd0d465f995e6e88f99a624901bbf6577b31c7230a4ff959ca48516be0339af7 README.md -df3acef0a949edac8c6ec87a15e4d7c5a87534a83d49186549699a59bdf22f98 SOURCE_LOCK.json -60c9bdd905fcf45ac485c680d32e9773962cf061b6f041dcddd033911558a672 components/skillsdesk/.dockerignore -843b71a3a9f9de899cbb9d260d55c9bd082f3df2b7771a1c31100ce5767a0a53 components/skillsdesk/ADAPTER_NOTICE -4f047d60bc07987131be2c9cf0662c6e6feef91125adda81eda04d4b88882f6b components/skillsdesk/Dockerfile -cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 components/skillsdesk/LICENSE -dca813e02ab76d4bc5afdcd2a2de3480d3fc0a7a710edea24c395adf23a99883 components/skillsdesk/NOTICE -11775067d2cfb4c254084dd741f0b13a1a5058081c171712bdb9923d430a9cd4 components/skillsdesk/README.md -789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99 components/skillsdesk/SOURCE_MANIFEST.json -2c07033febd78777deeff04350ae6887c9bb170b152d38c26cf148efa1b75d1e components/skillsdesk/UPSTREAM_DOCKERFILE -90e6e08d4269b5bb8308b5f2f05c61aa0cb9b71643b6abe6e47b34795828dd1e components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt -01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b components/skillsdesk/runtime/common/__init__.py -b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1 components/skillsdesk/runtime/common/contracts.py -6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd components/skillsdesk/runtime/common/models.py -e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/runtime/skillsdesk_compat/__init__.py -22a0011808344bdeeb635082afbacac2810bdf14e617ac72011e211dfa14c176 components/skillsdesk/runtime/skillsdesk_compat/environment.py -634fd3bd58cb4ade2c5d959ae7fb09dfb24b102830170c00a140a3ff949e590c components/skillsdesk/runtime/skillsdesk_compat/server.py -88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e components/skillsdesk/upstream/openenv.yaml -e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/__init__.py -e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/core/__init__.py -d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9 components/skillsdesk/upstream/terminal_desk/core/grading.py -e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d components/skillsdesk/upstream/terminal_desk/core/shell.py -3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411 components/skillsdesk/upstream/terminal_desk/families/__init__.py -a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f components/skillsdesk/upstream/terminal_desk/families/base.py -60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3 components/skillsdesk/upstream/terminal_desk/families/compute.py -91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33 components/skillsdesk/upstream/terminal_desk/families/compute2.py -25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0 components/skillsdesk/upstream/terminal_desk/families/constraints.py -411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4 components/skillsdesk/upstream/terminal_desk/families/constraints2.py -c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045 components/skillsdesk/upstream/terminal_desk/families/evidence.py -d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60 components/skillsdesk/upstream/terminal_desk/families/evidence2.py -a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781 components/skillsdesk/upstream/terminal_desk/families/repair.py -1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6 components/skillsdesk/upstream/terminal_desk/families/repair2.py -d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1 components/skillsdesk/upstream/terminal_desk/families/transform.py -2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2 components/skillsdesk/upstream/terminal_desk/families/transform2.py -0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832 components/skillsdesk/upstream/terminal_desk/families/util.py -f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4 components/skillsdesk/upstream/terminal_desk/models.py -012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330 components/skillsdesk/upstream/terminal_desk/reserved/__init__.py -e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083 components/skillsdesk/upstream/terminal_desk/reserved/compute.py -ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0 components/skillsdesk/upstream/terminal_desk/reserved/constraints.py -e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0 components/skillsdesk/upstream/terminal_desk/reserved/evidence.py -121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5 components/skillsdesk/upstream/terminal_desk/reserved/repair.py -bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf components/skillsdesk/upstream/terminal_desk/reserved/transform.py -e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/server/__init__.py -6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8 components/skillsdesk/upstream/terminal_desk/server/app.py -82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319 components/skillsdesk/upstream/terminal_desk/server/environment.py -10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4 schema.json -2a3fe43c4b55a123f5a80f0c2d60c15f86d94470cd2a4fc86adbaec85c12054b tasks.jsonl -db3704682eefb03f47a6c951865e9fb2113851f8bdf0266f6c4f517961f2973b validate_dataset.py +4788fd92c347b0f30ec74e278f1c8d24e91eea0e1fd6106178bb29876e0bc4bd README.md +a3f67ba6d525a1fdffbc87093b0a2b4ee12b7c482b95050dfd7b27b09d19143d SOURCE_LOCK.json +60c9bdd905fcf45ac485c680d32e9773962cf061b6f041dcddd033911558a672 components/qemedia/.dockerignore +5991dc74fa45e42c24120d3ddf4fd39c92f908f44986c71cf658c5b12deda80b components/qemedia/ADAPTER_NOTICE +0edae3727291af6b7ed7b3d38bf94d4aaa2c42c01c4d748d676ef9045de1c8df components/qemedia/Dockerfile +e0a8e97900a1184396b65bca8507d5c7b1a6df58537b61722dfe0f416990f0e2 components/qemedia/LICENSE +1f6d860d8285f6297e5381c08925a1ece2bf88eb5b0344b10740269e222a060d components/qemedia/README.md +f97c7ed6f032ebf9e6276f6156c447a2f128739858fc243143d72b86443292f3 components/qemedia/SOURCE_MANIFEST.json +755b9132babde91fb34bf29a7759c3cead1299484335fcafdb057fd207f210b8 components/qemedia/THIRD_PARTY_NOTICES +acb6b642cd8d1c4f66e8a82a2cc97c9d4643ca484422e225505c0ea2b739e146 components/qemedia/UPSTREAM_DOCKERFILE +bd90e5f33d8c325c978e826c5e7a73e4ad73ff535f367ddfed0dec3d52470ade components/qemedia/runtime/qemedia_compat/__init__.py +0fbea553dc22fa2fd72a4590c2c008eeefaa4af5654a2e9936465c18c79c9149 components/qemedia/runtime/qemedia_compat/environment.py +1d41688c822b842c70f32502d627c252fcd3526c7be74d6880f2f86d06df981a components/qemedia/runtime/qemedia_compat/server.py +f1ce27b1c58f9547059e7f820aa65c1a8d8313144855ee8845b2eca91f7e0db3 components/qemedia/upstream/qe_arena/__init__.py +2925e44219fdef6310ac1e2b60532e3ba1f1e768b33e65f14f1f5e8f86b33510 components/qemedia/upstream/qe_arena/app.py +978aabadc5044616ff28ab7be69a2e9ff48f1fd82494a6897f4f2b8716283a08 components/qemedia/upstream/qe_arena/corpus/__init__.py +0485dfbc2676a1f666958935602cc2f347e5fcd95b6bfcd32e8af13cafe07e35 components/qemedia/upstream/qe_arena/corpus/aggregate_risk_factors.py +f999a088228120810c986f249964ba83d7a54a4853c9bebcbf61313b4362247e components/qemedia/upstream/qe_arena/corpus/alternate_chat_roles.py +4b4f6e1280956988736c2401747ed0c3d633eedfe38e7d24ec815773f5c21711 components/qemedia/upstream/qe_arena/corpus/amortization_schedule.py +21517da739674bdc2b22efe9c2a2a7a85d47a7033aae3e24b2c1da8b4ac21684 components/qemedia/upstream/qe_arena/corpus/api_complexity_level.py +71db4461633e0ad524e11c2384d75675331a515778ce4a8b675c6f738c94a02c components/qemedia/upstream/qe_arena/corpus/artifact_retention_keep.py +1f1937c25f4717a49a6e809ea81cc20da035f6aa843d4f47ce111b585e3ab4a2 components/qemedia/upstream/qe_arena/corpus/backoff_schedule.py +2661b8a01fb4d7d1a31169592eaae370b3d4260d6b32187ce4427ffbcfa097ea components/qemedia/upstream/qe_arena/corpus/badge_dimensions.py +b1d44ea5c1b774f8572374e73468ca34483e3b382c982c28a368549da94656d5 components/qemedia/upstream/qe_arena/corpus/baseline_verdict.py +01764d4994630e38a91a6599f90142a9b145084dbd5971c564727ac9855f97f8 components/qemedia/upstream/qe_arena/corpus/booking_conflicts.py +7f70d489eefbdae5794354fa457a39dc50eb0209929cb0f3a9f9493b41adc88a components/qemedia/upstream/qe_arena/corpus/boundary_violations.py +04d411ac8a666d3916c13090c7658e5cc516028ced9b0db45a334062d96683c5 components/qemedia/upstream/qe_arena/corpus/brace_delta.py +6f0982869b0ef19ec7b95863008ea45b1a46dbd46108ee24b44338a383a37d23 components/qemedia/upstream/qe_arena/corpus/calibration_fit.py +42b4727623069a0e774e0d70be6cb9869d871b377ddb6421c60bfa78bd3be126 components/qemedia/upstream/qe_arena/corpus/chat_completion_result.py +f5c6486256438b89565cc1edcaf016d6e91f3c81067a77a30c9792cac7d0ef39 components/qemedia/upstream/qe_arena/corpus/claim_steal_priority.py +a77352fd67a18a9c24c3fe697c9310b079c998dc853c2f49eba1a2c877742a62 components/qemedia/upstream/qe_arena/corpus/compare_versions.py +5e4e65b458e8cd2e9723206e43ea3a85d37df8b82c9f15e19f4da5ce26dd72ff components/qemedia/upstream/qe_arena/corpus/complexity_bucket.py +3979785d451cc4473ec2b057a404f0a8ea930bd11ce34bedea06f1b953ee9c08 components/qemedia/upstream/qe_arena/corpus/compound_interest.py +30ff0142461a624790a13766f9463c6fd6f21991442e5e37d46febd51f2ca7ad components/qemedia/upstream/qe_arena/corpus/convert_timecode.py +af3e694760997b353678c7350b08e43ed26de256792221420006e5d4837712d5 components/qemedia/upstream/qe_arena/corpus/coverage_gap_severity.py +f85c6167be7fe0094e36b90d19fb4e382a2e804a34dc96fa09f379caf97d5904 components/qemedia/upstream/qe_arena/corpus/crop_to_aspect.py +61e8975cc643b0bd4d10656d48a77a7314b5e13382794bdcbecf19f2a80b3186 components/qemedia/upstream/qe_arena/corpus/debounce_switch.py +949197b79f96f244ccba1b44236510ec65d8c9aace59850cde4949697791024f components/qemedia/upstream/qe_arena/corpus/decay_table.py +c5033c7d0a147c46e9cf1659187879b00e8f253725f1fcc00b6c4e5529c9685b components/qemedia/upstream/qe_arena/corpus/efficiency_reward.py +11d505901f9d2e00cc5b475d9cca75b4770db77345c1645b10e70620710a70b0 components/qemedia/upstream/qe_arena/corpus/expense_violations.py +284d4fcd6c5cb23efc4282659991d9a403b46c0d836641071ad7079d8d2c8d0d components/qemedia/upstream/qe_arena/corpus/find_stop.py +b3b94bcfe78f97b00187e7fe9783a8ae04b9a9b6af6d788f445f64bd52021aa0 components/qemedia/upstream/qe_arena/corpus/flakiness_pattern.py +11c670fbe537cbeeaa101d9b9db49519f5ebd4cca82b7ccfd66d5d68e352e5ba components/qemedia/upstream/qe_arena/corpus/flaky_hunter_reward.py +f6ebbaffe1dd8aaccef7ad8ce48d8dfa60bacc8a44051880057c52b163e7748b components/qemedia/upstream/qe_arena/corpus/flaky_run_summary.py +7e0cf537d1bd38fdbc474bc259a52fbf23f095f35661586d771eca0561481eb0 components/qemedia/upstream/qe_arena/corpus/format_duration.py +e232fbfe97a36cedf848caa11b9bf51828c5f4c6fe6ad3bf40133c6bc7deabd7 components/qemedia/upstream/qe_arena/corpus/gguf_loader.py +b5fc54e4b3f6b45af2af289a746fe48d948e806b43910920e6ee31c81bbd805e components/qemedia/upstream/qe_arena/corpus/gguf_special_ids.py +52d8da6da1348af21303785a5dabfe36a42f7efeaed9b326b21898387a3e6536 components/qemedia/upstream/qe_arena/corpus/glob_match.py +ce28e349ed362052dd0184dc4f1e215344831edc2f74ebe8438c470964fc70a3 components/qemedia/upstream/qe_arena/corpus/income_tax.py +edd468fbc9d11830559fbcc2bfb1d7afe35c71980432bb91c87d8c3571a704b7 components/qemedia/upstream/qe_arena/corpus/integer_edge_values.py +94bc28736f587e3cc350fef83ba95fe70dc44db627bcb037f854332f6b52e7fd components/qemedia/upstream/qe_arena/corpus/ip_allowlist_match.py +87db0af0b61c0b95b0d8acf9235835db9631f9471d0e7dc29b0296abc76bccde components/qemedia/upstream/qe_arena/corpus/is_collection_endpoint.py +7d91f4eb06374851748cbd3e33ae5f3d2059a491572449d4fc700ecaaed1431c components/qemedia/upstream/qe_arena/corpus/latency_percentiles.py +814fc40372c1ece5068b04848f9c8a2a9069d504cf364df62c00a905d0ec777c components/qemedia/upstream/qe_arena/corpus/login_rate_limit.py +ecc262d19d2b27970901017aa4a006ad2ce97861866ccddae2a9c876c4bbec37 components/qemedia/upstream/qe_arena/corpus/loudness_gain.py +2c3ec2cb2f5e050ff03d772675c372053fe3eb957f505a33d2d127916ee283bf components/qemedia/upstream/qe_arena/corpus/mail_merge.py +48972588b8f75f1132aaf0eaa112a35875833b7dc661e3c41ff6972f3ce29dd5 components/qemedia/upstream/qe_arena/corpus/maintainability_index.py +201bad40ff156e6a0caec2577011286262178000435aacaec83c603ba02aa4f8 components/qemedia/upstream/qe_arena/corpus/maintenance_status.py +fd5b0f08e59fc763734cdb43d4cd893ce851403281a806902f5945ce71e7e7cd components/qemedia/upstream/qe_arena/corpus/merge_intervals.py +888558da6833e82d1b2dafadf39aa87609cf5c4bcc96345a4e37ac92cfd1d0de components/qemedia/upstream/qe_arena/corpus/mod_inverse.py +58cdc61459945cdd9bf20ab09cfa422c85148d76fecfc70567ef81b1240c2f36 components/qemedia/upstream/qe_arena/corpus/mod_pow.py +1c72218af8a816d24fc7ba7d88901c83db49c056da34efea5f2ba491a77493d2 components/qemedia/upstream/qe_arena/corpus/networkdays.py +62e849358e01be48618529568005a1b487b411bdc18a01b4c226b824f77320df components/qemedia/upstream/qe_arena/corpus/normalize_rational.py +6275cc4556df344a4dfccbcdf5930e9561bcb27b93fcb247c9707a84c48f3231 components/qemedia/upstream/qe_arena/corpus/parse_cron_field.py +52df1c52ecfe9db206a6322350204d2bbbaeb2fe6bd192d8b98d56de8739bf50 components/qemedia/upstream/qe_arena/corpus/parse_max_age.py +cf81c249d3ff4092557d20bdcf210ce52cbe4c9e2e5e8634d279a46568d2f4df components/qemedia/upstream/qe_arena/corpus/parse_signature_header.py +5d1a27cea4b7db6b2b2484015dfc73e61ddc04b3d021da8adfb1788ebf0dd54c components/qemedia/upstream/qe_arena/corpus/password_violations.py +ccf4a9d4183523e3b82f95cf0f5f18efe86881ece0d7274f24f5236233aa4f13 components/qemedia/upstream/qe_arena/corpus/pattern_effectiveness.py +c7b17812aa575ee19db876d526f0770ad6ee591e6aa2bc624e05527cc1ef7df2 components/qemedia/upstream/qe_arena/corpus/pressure_check.py +cca54e5fa4dfed47ac23f06111a357fb1a2f9fbd3b29a8d9873d268a91a754ec components/qemedia/upstream/qe_arena/corpus/quality_gain_reward.py +aafb0bab705f85093cecdfa13bdce9a1f23bbf055b60f50783abc46f020b8fef components/qemedia/upstream/qe_arena/corpus/quality_grade.py +169e88a7162bc1e2a798b76ee491191ca44fca3051d7eb392b56b7672139142e components/qemedia/upstream/qe_arena/corpus/reconcile_invoices.py +361cbe3b3c5e2da8317b2cf703dc11405d4c10ad2d62551c65388028238f4fb5 components/qemedia/upstream/qe_arena/corpus/round_sig_figs.py +368365c0bd5b318b63d1614caba8bd4f752011f6beecf3ede4fbb42f137441d7 components/qemedia/upstream/qe_arena/corpus/safe_join.py +a26bc6ef76d5dfbc4b0abff3f0189f6bd181f6934bcb6dee3410ab752316223d components/qemedia/upstream/qe_arena/corpus/sample_variance.py +51ae093e2baeda053434e2e223827384124290ed5317bf160f0b3df366ef02eb components/qemedia/upstream/qe_arena/corpus/select_bitrate_rung.py +cce40f8f9266e58918b174e82d1b167523a4df1b78a53f07af06fe43d9c9100e components/qemedia/upstream/qe_arena/corpus/shift_cue.py +540a4e6c04b1e3cc78cf69e42897d6680840c513ffcc86eeba8f2aa735d30cf6 components/qemedia/upstream/qe_arena/corpus/slew_limit.py +02936fcc7e5931cad5a46b286d098ae2d34698449f2eaa190eaa44f9785543da components/qemedia/upstream/qe_arena/corpus/spec_readiness_score.py +9188e0c8045fa0d8e1a7a82153f6ccc791e075dd7a6f3b793abd117bb1064275 components/qemedia/upstream/qe_arena/corpus/split_generic_params.py +d3aac59af147f657bbe61bb45e368d78cee587be7a4fa58208410fd5a9e3d26c components/qemedia/upstream/qe_arena/corpus/streamable_len.py +62a7ac1680df0375cae8ecb6cf08a3520375cb9c8dea94299a30551d0abe479e components/qemedia/upstream/qe_arena/corpus/string_length_boundaries.py +13361068ea0f1ebaacadb264bfec120e990341cf66154f77a1a110777be1754e components/qemedia/upstream/qe_arena/corpus/threshold_compliance.py +081ef70cde049750026cc4f60794f46a74a86424c12d73ea5c278b19563b2e77 components/qemedia/upstream/qe_arena/corpus/token_claims_check.py +9d10c0da4d0375ea05c99d0e5d2dd57a4bedf1a4fa5a5f48d6cc9344177f19bb components/qemedia/upstream/qe_arena/corpus/token_jaccard.py +6e20c250fb2d01cf06ed5b099d67089f43f7851e90224399f5865aee539d4f32 components/qemedia/upstream/qe_arena/corpus/trace_sampling_decision.py +5246d62082d3a37dd57e6d3510ea489a4de4c44a31e5bddb2d4d438817b0c43b components/qemedia/upstream/qe_arena/corpus/truncate_to_token_budget.py +9feb8f950e2cff5904eddba37a15e16a8888a7cb8f5dc893e74808a36c6f1876 components/qemedia/upstream/qe_arena/corpus/uncovered_line_ranges.py +bc332a39e0143f24ee326b0f9343150a22f47fa420dc29ecf1cba816385a1d43 components/qemedia/upstream/qe_arena/corpus/validate_csv_row.py +3132a4152e1baf9061b0e70d3192e0617e8de735195eb560dcfee5011c14f6fc components/qemedia/upstream/qe_arena/corpus/vuln_priority_bucket.py +28e98e2f9b24bb36171fa2f5c5c9d78be23e193615b265aad092bec771eb8021 components/qemedia/upstream/qe_arena/corpus/wilson_interval.py +13bb7b068896d5377b8f969c504dde01875df8eef8a0b341348e45bcea5f991b components/qemedia/upstream/qe_arena/domains.py +4b27436ca7c4eed5e7dda34ccfac6c97eb413cf024274793d4d1cf47b50f9494 components/qemedia/upstream/qe_arena/edit_budget.py +9675b6598456b5a8dbfe57eb6e6847998d86f2c93722caff3c8a3716d6ecc102 components/qemedia/upstream/qe_arena/environment.py +0db273642496825ec8f8924a164093df1191b29c92ac83b5497261373c20f768 components/qemedia/upstream/qe_arena/flaky.py +46e2198bcbe9d415bf775f845a358c2eaa26d390a5aa62d3b806f07b5803fab1 components/qemedia/upstream/qe_arena/flaky_gen.py +2272e0617a3a079d2e389bf50d62c4cc5da4ec005d2d68239bdfbf7e795fda92 components/qemedia/upstream/qe_arena/flaky_templates.py +5b389cc8ab64218d3bdcc500f584ef0b78da4b68379bfb014e095d755ccdcdb1 components/qemedia/upstream/qe_arena/guest_harness.py +ea2b370db92d82e1a0719ecf3416eeafdb7a14a524a94f6d6cd32a5f06b21106 components/qemedia/upstream/qe_arena/keys/manifest_ed25519.pub +1911ef5d3696695364871da7be9744fd7c81d51fe81ae3c137341dd1b06c8494 components/qemedia/upstream/qe_arena/manifest.py +28a7abc5213c5a1504151d23148695e7f09e4441b39e941377cb7265ba6ff4de components/qemedia/upstream/qe_arena/mutation.py +97f080e2505ba4c6034fcc3f0322d9ecd8b9f9852ac19e424cc9273ccd0a9c77 components/qemedia/upstream/qe_arena/runtime_pins.json +92faaac323c0b524c0181008c305134fc57d2e4c6af1ea6fbf919b48ec9ea03a components/qemedia/upstream/qe_arena/sandbox.py +4e9aabefa6f23793a05804ec413aaa5d1c5125365156f22cdb50ff600808d34d components/qemedia/upstream/qe_arena/shell.py +c6b045c7b62b762ae4a56b13fcc61bf997ffd710494f9882e775f533dfe8c522 components/qemedia/upstream/qe_arena/skills/__init__.py +ec722ad0aa0903fbca443dc8325f2569853b7191edfc525602d3cd0ddaf56037 components/qemedia/upstream/qe_arena/skills/_common.py +da87595287e1d253512564769274e3063f262fce0d4d4ea0ef5b26d9285a72e0 components/qemedia/upstream/qe_arena/skills/formal.py +005eabea342ba948e6b68dcc341f3756a8ebdd5fb44830cb13bb482a16ef200c components/qemedia/upstream/qe_arena/skills/media.py +f198046eb6e9d0610cd966f5e7a99d27e9da2e3f23e3687ecd42f4a5649aab98 components/qemedia/upstream/qe_arena/skills/science.py +872054f7309500113beab2c853bfeceebd146e60dc36d42f42f9e98e6c4a7b84 components/qemedia/upstream/qe_arena/skills/subtitles.py +c540dc8eafd3ac648f768b17682ecb1f8f3bd3e14eed9a353c4021c427dc80bd components/qemedia/upstream/qe_arena/tasks.py +d5a630210e1a8330ec3cc00a5b43d7d92b110a6d0eb8ec5e83d3bba13e85fcc0 components/qemedia/upstream/qe_arena/terminal_app.py +6ea5cfcffc292e52ead2687728ad6d9c040dfaf32a5610386ac6514d4b1438b3 components/qemedia/upstream/qe_arena/terminal_env.py +71f35970518b637bfa50fa79897d6f79d065e4531211af402f91a9dba4d31f38 components/qemedia/upstream/qe_arena/wasi_fs.py +6e81b271a5910977f38deba39ccde6465d70e23e9ed42cbec51f02a6e237c71e components/qemedia/upstream/qe_arena/wasi_worker.py +c486d87e05b69ab133dd04cba072d5a39de8fda53c9a2f6fd5995570384724b0 schema.json +7e16aa89ecd785fe76b4c3b1ef887845d33dbf293a849578a02efafb0da92c00 tasks.jsonl +3ab9912b176d4555f7d38828bd66854b60311dc42c2e25c665cb8296fffaf9db validate_dataset.py diff --git a/SOURCE_LOCK.json b/SOURCE_LOCK.json index f9da22f89b66a4f4ea7c8a46e89a6f86f908def1..97ba8594d4f7ee6af9245011356df50bbbfa5b4a 100644 --- a/SOURCE_LOCK.json +++ b/SOURCE_LOCK.json @@ -1,11 +1,11 @@ { "components": { - "skillsdesk": { - "repository": "Syndicate604/skills-desk", - "revision": "a785ccdc9784ed863d0ffecec826d72176c0a785", - "license": "Apache-2.0", + "qemedia": { + "repository": "proffesor-for-testing/openenv-qe-arena", + "revision": "7490e2dc371b5060601ff4399a3d3688bff3ca80", + "license": "MIT", "source_file": "SOURCE_MANIFEST.json", - "record_sha256": "789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99" + "record_sha256": "f97c7ed6f032ebf9e6276f6156c447a2f128739858fc243143d72b86443292f3" } } } diff --git a/components/skillsdesk/.dockerignore b/components/qemedia/.dockerignore similarity index 100% rename from components/skillsdesk/.dockerignore rename to components/qemedia/.dockerignore diff --git a/components/qemedia/ADAPTER_NOTICE b/components/qemedia/ADAPTER_NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..7bdb3852e627957033848988c899c56a3e1e5051 --- /dev/null +++ b/components/qemedia/ADAPTER_NOTICE @@ -0,0 +1,3 @@ +This distribution adds a two-task registry, source integrity checks and a single-session OpenEnv transport. +Original QE generators, graders, task instructions and seed behavior are retained. +The included qe_arena modules provide the original import dependencies; media tasks are the served selection. diff --git a/components/qemedia/Dockerfile b/components/qemedia/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..38e879027f6f0312d41f2e5bc17a909c70cb1291 --- /dev/null +++ b/components/qemedia/Dockerfile @@ -0,0 +1,16 @@ +FROM ghcr.io/proffesor-for-testing/openenv-qe-arena-terminal@sha256:57dd0c2bfde0e503f1ff43400530cf99a6e2b8a5d9b1f42e0ae7471501f4b971 +USER root +COPY upstream/qe_arena /opt/qemedia/qe_arena +COPY runtime /opt/qemedia +COPY SOURCE_MANIFEST.json /opt/qemedia/SOURCE_MANIFEST.json +COPY LICENSE THIRD_PARTY_NOTICES ADAPTER_NOTICE /opt/qemedia/licenses/ +RUN rm -rf /app/qe_arena && chmod -R go-rwx /opt/qemedia /app /opt/qe-arena +ENV PYTHONPATH=/opt/qemedia PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 OPENENV_MODE=production ENABLE_WEB_INTERFACE=false QE_ARENA_UNSANDBOXED_SHELL=0 +WORKDIR /opt/qemedia +LABEL org.opencontainers.image.title="Media Workflows v11" \ + org.opencontainers.image.description="Original QE media artifact tasks" \ + org.opencontainers.image.source="https://huggingface.co/datasets/bochencs/openenv-multidomain" \ + org.opencontainers.image.licenses="MIT" +EXPOSE 8000 +ENTRYPOINT ["/usr/bin/tini", "--"] +CMD ["python", "-m", "qemedia_compat.server"] diff --git a/components/qemedia/LICENSE b/components/qemedia/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..486e40556480e2ccfc2e5db0c49d5d5df8505369 --- /dev/null +++ b/components/qemedia/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Dragan Spiridonov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/components/qemedia/README.md b/components/qemedia/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7010f5ee001c0a65e8c396d181daf59273ad8033 --- /dev/null +++ b/components/qemedia/README.md @@ -0,0 +1,4 @@ +Original QE media tasks by Dragan Spiridonov, with a two-task OpenEnv transport. + +Run `python -m qemedia_compat.server` as root. Commands run through the original isolated shell. +Use one active session per sandbox. The selected original task IDs and source hashes are in SOURCE_MANIFEST.json. diff --git a/components/qemedia/SOURCE_MANIFEST.json b/components/qemedia/SOURCE_MANIFEST.json new file mode 100644 index 0000000000000000000000000000000000000000..bbead6df6afb94d7596e91ffb9f85af6c3a54fa7 --- /dev/null +++ b/components/qemedia/SOURCE_MANIFEST.json @@ -0,0 +1,131 @@ +{ + "repository": "proffesor-for-testing/openenv-qe-arena", + "revision": "7490e2dc371b5060601ff4399a3d3688bff3ca80", + "dataset": "Profa-QE/openenv-qe-arena-tasks", + "dataset_revision": "f5e0b952cffbb5d82e0c54c131e7b8a68abce69d", + "license": "MIT", + "base_image": "ghcr.io/proffesor-for-testing/openenv-qe-arena-terminal@sha256:57dd0c2bfde0e503f1ff43400530cf99a6e2b8a5d9b1f42e0ae7471501f4b971", + "sdk_revision": "86a180ede21e044f7929b9a7783ad83aa67d83a3", + "original_files": { + "qe_arena/__init__.py": "f1ce27b1c58f9547059e7f820aa65c1a8d8313144855ee8845b2eca91f7e0db3", + "qe_arena/app.py": "2925e44219fdef6310ac1e2b60532e3ba1f1e768b33e65f14f1f5e8f86b33510", + "qe_arena/corpus/__init__.py": "978aabadc5044616ff28ab7be69a2e9ff48f1fd82494a6897f4f2b8716283a08", + "qe_arena/corpus/aggregate_risk_factors.py": "0485dfbc2676a1f666958935602cc2f347e5fcd95b6bfcd32e8af13cafe07e35", + "qe_arena/corpus/alternate_chat_roles.py": "f999a088228120810c986f249964ba83d7a54a4853c9bebcbf61313b4362247e", + "qe_arena/corpus/amortization_schedule.py": "4b4f6e1280956988736c2401747ed0c3d633eedfe38e7d24ec815773f5c21711", + "qe_arena/corpus/api_complexity_level.py": "21517da739674bdc2b22efe9c2a2a7a85d47a7033aae3e24b2c1da8b4ac21684", + "qe_arena/corpus/artifact_retention_keep.py": "71db4461633e0ad524e11c2384d75675331a515778ce4a8b675c6f738c94a02c", + "qe_arena/corpus/backoff_schedule.py": "1f1937c25f4717a49a6e809ea81cc20da035f6aa843d4f47ce111b585e3ab4a2", + "qe_arena/corpus/badge_dimensions.py": "2661b8a01fb4d7d1a31169592eaae370b3d4260d6b32187ce4427ffbcfa097ea", + "qe_arena/corpus/baseline_verdict.py": "b1d44ea5c1b774f8572374e73468ca34483e3b382c982c28a368549da94656d5", + "qe_arena/corpus/booking_conflicts.py": "01764d4994630e38a91a6599f90142a9b145084dbd5971c564727ac9855f97f8", + "qe_arena/corpus/boundary_violations.py": "7f70d489eefbdae5794354fa457a39dc50eb0209929cb0f3a9f9493b41adc88a", + "qe_arena/corpus/brace_delta.py": "04d411ac8a666d3916c13090c7658e5cc516028ced9b0db45a334062d96683c5", + "qe_arena/corpus/calibration_fit.py": "6f0982869b0ef19ec7b95863008ea45b1a46dbd46108ee24b44338a383a37d23", + "qe_arena/corpus/chat_completion_result.py": "42b4727623069a0e774e0d70be6cb9869d871b377ddb6421c60bfa78bd3be126", + "qe_arena/corpus/claim_steal_priority.py": "f5c6486256438b89565cc1edcaf016d6e91f3c81067a77a30c9792cac7d0ef39", + "qe_arena/corpus/compare_versions.py": "a77352fd67a18a9c24c3fe697c9310b079c998dc853c2f49eba1a2c877742a62", + "qe_arena/corpus/complexity_bucket.py": "5e4e65b458e8cd2e9723206e43ea3a85d37df8b82c9f15e19f4da5ce26dd72ff", + "qe_arena/corpus/compound_interest.py": "3979785d451cc4473ec2b057a404f0a8ea930bd11ce34bedea06f1b953ee9c08", + "qe_arena/corpus/convert_timecode.py": "30ff0142461a624790a13766f9463c6fd6f21991442e5e37d46febd51f2ca7ad", + "qe_arena/corpus/coverage_gap_severity.py": "af3e694760997b353678c7350b08e43ed26de256792221420006e5d4837712d5", + "qe_arena/corpus/crop_to_aspect.py": "f85c6167be7fe0094e36b90d19fb4e382a2e804a34dc96fa09f379caf97d5904", + "qe_arena/corpus/debounce_switch.py": "61e8975cc643b0bd4d10656d48a77a7314b5e13382794bdcbecf19f2a80b3186", + "qe_arena/corpus/decay_table.py": "949197b79f96f244ccba1b44236510ec65d8c9aace59850cde4949697791024f", + "qe_arena/corpus/efficiency_reward.py": "c5033c7d0a147c46e9cf1659187879b00e8f253725f1fcc00b6c4e5529c9685b", + "qe_arena/corpus/expense_violations.py": "11d505901f9d2e00cc5b475d9cca75b4770db77345c1645b10e70620710a70b0", + "qe_arena/corpus/find_stop.py": "284d4fcd6c5cb23efc4282659991d9a403b46c0d836641071ad7079d8d2c8d0d", + "qe_arena/corpus/flakiness_pattern.py": "b3b94bcfe78f97b00187e7fe9783a8ae04b9a9b6af6d788f445f64bd52021aa0", + "qe_arena/corpus/flaky_hunter_reward.py": "11c670fbe537cbeeaa101d9b9db49519f5ebd4cca82b7ccfd66d5d68e352e5ba", + "qe_arena/corpus/flaky_run_summary.py": "f6ebbaffe1dd8aaccef7ad8ce48d8dfa60bacc8a44051880057c52b163e7748b", + "qe_arena/corpus/format_duration.py": "7e0cf537d1bd38fdbc474bc259a52fbf23f095f35661586d771eca0561481eb0", + "qe_arena/corpus/gguf_loader.py": "e232fbfe97a36cedf848caa11b9bf51828c5f4c6fe6ad3bf40133c6bc7deabd7", + "qe_arena/corpus/gguf_special_ids.py": "b5fc54e4b3f6b45af2af289a746fe48d948e806b43910920e6ee31c81bbd805e", + "qe_arena/corpus/glob_match.py": "52d8da6da1348af21303785a5dabfe36a42f7efeaed9b326b21898387a3e6536", + "qe_arena/corpus/income_tax.py": "ce28e349ed362052dd0184dc4f1e215344831edc2f74ebe8438c470964fc70a3", + "qe_arena/corpus/integer_edge_values.py": "edd468fbc9d11830559fbcc2bfb1d7afe35c71980432bb91c87d8c3571a704b7", + "qe_arena/corpus/ip_allowlist_match.py": "94bc28736f587e3cc350fef83ba95fe70dc44db627bcb037f854332f6b52e7fd", + "qe_arena/corpus/is_collection_endpoint.py": "87db0af0b61c0b95b0d8acf9235835db9631f9471d0e7dc29b0296abc76bccde", + "qe_arena/corpus/latency_percentiles.py": "7d91f4eb06374851748cbd3e33ae5f3d2059a491572449d4fc700ecaaed1431c", + "qe_arena/corpus/login_rate_limit.py": "814fc40372c1ece5068b04848f9c8a2a9069d504cf364df62c00a905d0ec777c", + "qe_arena/corpus/loudness_gain.py": "ecc262d19d2b27970901017aa4a006ad2ce97861866ccddae2a9c876c4bbec37", + "qe_arena/corpus/mail_merge.py": "2c3ec2cb2f5e050ff03d772675c372053fe3eb957f505a33d2d127916ee283bf", + "qe_arena/corpus/maintainability_index.py": "48972588b8f75f1132aaf0eaa112a35875833b7dc661e3c41ff6972f3ce29dd5", + "qe_arena/corpus/maintenance_status.py": "201bad40ff156e6a0caec2577011286262178000435aacaec83c603ba02aa4f8", + "qe_arena/corpus/merge_intervals.py": "fd5b0f08e59fc763734cdb43d4cd893ce851403281a806902f5945ce71e7e7cd", + "qe_arena/corpus/mod_inverse.py": "888558da6833e82d1b2dafadf39aa87609cf5c4bcc96345a4e37ac92cfd1d0de", + "qe_arena/corpus/mod_pow.py": "58cdc61459945cdd9bf20ab09cfa422c85148d76fecfc70567ef81b1240c2f36", + "qe_arena/corpus/networkdays.py": "1c72218af8a816d24fc7ba7d88901c83db49c056da34efea5f2ba491a77493d2", + "qe_arena/corpus/normalize_rational.py": "62e849358e01be48618529568005a1b487b411bdc18a01b4c226b824f77320df", + "qe_arena/corpus/parse_cron_field.py": "6275cc4556df344a4dfccbcdf5930e9561bcb27b93fcb247c9707a84c48f3231", + "qe_arena/corpus/parse_max_age.py": "52df1c52ecfe9db206a6322350204d2bbbaeb2fe6bd192d8b98d56de8739bf50", + "qe_arena/corpus/parse_signature_header.py": "cf81c249d3ff4092557d20bdcf210ce52cbe4c9e2e5e8634d279a46568d2f4df", + "qe_arena/corpus/password_violations.py": "5d1a27cea4b7db6b2b2484015dfc73e61ddc04b3d021da8adfb1788ebf0dd54c", + "qe_arena/corpus/pattern_effectiveness.py": "ccf4a9d4183523e3b82f95cf0f5f18efe86881ece0d7274f24f5236233aa4f13", + "qe_arena/corpus/pressure_check.py": "c7b17812aa575ee19db876d526f0770ad6ee591e6aa2bc624e05527cc1ef7df2", + "qe_arena/corpus/quality_gain_reward.py": "cca54e5fa4dfed47ac23f06111a357fb1a2f9fbd3b29a8d9873d268a91a754ec", + "qe_arena/corpus/quality_grade.py": "aafb0bab705f85093cecdfa13bdce9a1f23bbf055b60f50783abc46f020b8fef", + "qe_arena/corpus/reconcile_invoices.py": "169e88a7162bc1e2a798b76ee491191ca44fca3051d7eb392b56b7672139142e", + "qe_arena/corpus/round_sig_figs.py": "361cbe3b3c5e2da8317b2cf703dc11405d4c10ad2d62551c65388028238f4fb5", + "qe_arena/corpus/safe_join.py": "368365c0bd5b318b63d1614caba8bd4f752011f6beecf3ede4fbb42f137441d7", + "qe_arena/corpus/sample_variance.py": "a26bc6ef76d5dfbc4b0abff3f0189f6bd181f6934bcb6dee3410ab752316223d", + "qe_arena/corpus/select_bitrate_rung.py": "51ae093e2baeda053434e2e223827384124290ed5317bf160f0b3df366ef02eb", + "qe_arena/corpus/shift_cue.py": "cce40f8f9266e58918b174e82d1b167523a4df1b78a53f07af06fe43d9c9100e", + "qe_arena/corpus/slew_limit.py": "540a4e6c04b1e3cc78cf69e42897d6680840c513ffcc86eeba8f2aa735d30cf6", + "qe_arena/corpus/spec_readiness_score.py": "02936fcc7e5931cad5a46b286d098ae2d34698449f2eaa190eaa44f9785543da", + "qe_arena/corpus/split_generic_params.py": "9188e0c8045fa0d8e1a7a82153f6ccc791e075dd7a6f3b793abd117bb1064275", + "qe_arena/corpus/streamable_len.py": "d3aac59af147f657bbe61bb45e368d78cee587be7a4fa58208410fd5a9e3d26c", + "qe_arena/corpus/string_length_boundaries.py": "62a7ac1680df0375cae8ecb6cf08a3520375cb9c8dea94299a30551d0abe479e", + "qe_arena/corpus/threshold_compliance.py": "13361068ea0f1ebaacadb264bfec120e990341cf66154f77a1a110777be1754e", + "qe_arena/corpus/token_claims_check.py": "081ef70cde049750026cc4f60794f46a74a86424c12d73ea5c278b19563b2e77", + "qe_arena/corpus/token_jaccard.py": "9d10c0da4d0375ea05c99d0e5d2dd57a4bedf1a4fa5a5f48d6cc9344177f19bb", + "qe_arena/corpus/trace_sampling_decision.py": "6e20c250fb2d01cf06ed5b099d67089f43f7851e90224399f5865aee539d4f32", + "qe_arena/corpus/truncate_to_token_budget.py": "5246d62082d3a37dd57e6d3510ea489a4de4c44a31e5bddb2d4d438817b0c43b", + "qe_arena/corpus/uncovered_line_ranges.py": "9feb8f950e2cff5904eddba37a15e16a8888a7cb8f5dc893e74808a36c6f1876", + "qe_arena/corpus/validate_csv_row.py": "bc332a39e0143f24ee326b0f9343150a22f47fa420dc29ecf1cba816385a1d43", + "qe_arena/corpus/vuln_priority_bucket.py": "3132a4152e1baf9061b0e70d3192e0617e8de735195eb560dcfee5011c14f6fc", + "qe_arena/corpus/wilson_interval.py": "28e98e2f9b24bb36171fa2f5c5c9d78be23e193615b265aad092bec771eb8021", + "qe_arena/domains.py": "13bb7b068896d5377b8f969c504dde01875df8eef8a0b341348e45bcea5f991b", + "qe_arena/edit_budget.py": "4b27436ca7c4eed5e7dda34ccfac6c97eb413cf024274793d4d1cf47b50f9494", + "qe_arena/environment.py": "9675b6598456b5a8dbfe57eb6e6847998d86f2c93722caff3c8a3716d6ecc102", + "qe_arena/flaky.py": "0db273642496825ec8f8924a164093df1191b29c92ac83b5497261373c20f768", + "qe_arena/flaky_gen.py": "46e2198bcbe9d415bf775f845a358c2eaa26d390a5aa62d3b806f07b5803fab1", + "qe_arena/flaky_templates.py": "2272e0617a3a079d2e389bf50d62c4cc5da4ec005d2d68239bdfbf7e795fda92", + "qe_arena/guest_harness.py": "5b389cc8ab64218d3bdcc500f584ef0b78da4b68379bfb014e095d755ccdcdb1", + "qe_arena/keys/manifest_ed25519.pub": "ea2b370db92d82e1a0719ecf3416eeafdb7a14a524a94f6d6cd32a5f06b21106", + "qe_arena/manifest.py": "1911ef5d3696695364871da7be9744fd7c81d51fe81ae3c137341dd1b06c8494", + "qe_arena/mutation.py": "28a7abc5213c5a1504151d23148695e7f09e4441b39e941377cb7265ba6ff4de", + "qe_arena/runtime_pins.json": "97f080e2505ba4c6034fcc3f0322d9ecd8b9f9852ac19e424cc9273ccd0a9c77", + "qe_arena/sandbox.py": "92faaac323c0b524c0181008c305134fc57d2e4c6af1ea6fbf919b48ec9ea03a", + "qe_arena/shell.py": "4e9aabefa6f23793a05804ec413aaa5d1c5125365156f22cdb50ff600808d34d", + "qe_arena/skills/__init__.py": "c6b045c7b62b762ae4a56b13fcc61bf997ffd710494f9882e775f533dfe8c522", + "qe_arena/skills/_common.py": "ec722ad0aa0903fbca443dc8325f2569853b7191edfc525602d3cd0ddaf56037", + "qe_arena/skills/formal.py": "da87595287e1d253512564769274e3063f262fce0d4d4ea0ef5b26d9285a72e0", + "qe_arena/skills/media.py": "005eabea342ba948e6b68dcc341f3756a8ebdd5fb44830cb13bb482a16ef200c", + "qe_arena/skills/science.py": "f198046eb6e9d0610cd966f5e7a99d27e9da2e3f23e3687ecd42f4a5649aab98", + "qe_arena/skills/subtitles.py": "872054f7309500113beab2c853bfeceebd146e60dc36d42f42f9e98e6c4a7b84", + "qe_arena/tasks.py": "c540dc8eafd3ac648f768b17682ecb1f8f3bd3e14eed9a353c4021c427dc80bd", + "qe_arena/terminal_app.py": "d5a630210e1a8330ec3cc00a5b43d7d92b110a6d0eb8ec5e83d3bba13e85fcc0", + "qe_arena/terminal_env.py": "6ea5cfcffc292e52ead2687728ad6d9c040dfaf32a5610386ac6514d4b1438b3", + "qe_arena/wasi_fs.py": "71f35970518b637bfa50fa79897d6f79d065e4531211af402f91a9dba4d31f38", + "qe_arena/wasi_worker.py": "6e81b271a5910977f38deba39ccde6465d70e23e9ed42cbec51f02a6e237c71e" + }, + "selected_tasks": [ + "qe_skill-media-d2", + "qe_skill-media-d1" + ], + "native_pools": { + "qe_skill-media-d2": [ + "subtitles", + "timecode", + "catalogue", + "assets" + ], + "qe_skill-media-d1": [ + "timecode", + "catalogue", + "assets" + ] + }, + "instance_policy": "Native seeded generation; omitted seed draws original randomness." +} diff --git a/components/qemedia/THIRD_PARTY_NOTICES b/components/qemedia/THIRD_PARTY_NOTICES new file mode 100644 index 0000000000000000000000000000000000000000..b52ed8e7e3eea25f68be720da560dd4bdd2ecff5 --- /dev/null +++ b/components/qemedia/THIRD_PARTY_NOTICES @@ -0,0 +1,63 @@ +Third-party notices +=================== + +The real-bug corpus entries listed below are Python ports of code from RuVector, +https://github.com/ruvnet/RuVector, used under the MIT License. The fixed code comes from +merged PR #1125 (32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef). Each recorded fault reproduces +pre-fix behaviour from its parent commit (3e1d1886c50f2db817664648b95fab18e3e4c34b). + +Entries and origins: + +- qe_arena/corpus/chat_completion_result.py + fixed code: ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm-cli/src/commands/serve.rs + fault chat_completion_result/always-stop: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm-cli/src/commands/serve.rs + fault chat_completion_result/whitespace-token-count: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm-cli/src/commands/serve.rs + +- qe_arena/corpus/find_stop.py + fixed code: ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs + fault find_stop/first-listed: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs + fault find_stop/empty-matches: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs + +- qe_arena/corpus/gguf_loader.py + fixed code: ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs + fault gguf_loader/no-split-check: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs + fault gguf_loader/qwen-rejected: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs + fault gguf_loader/substring-match: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs + +- qe_arena/corpus/gguf_special_ids.py + fixed code: ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs + fixed code: ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/candle_backend.rs + fault gguf_special_ids/eos-from-vocab-guess: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs (pre-fix behaviour (EOS guessed from the vocabulary) expressed through the fixed function's interface) + fault gguf_special_ids/stop-is-only-eos: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs (pre-fix behaviour (stop on the single EOS id) expressed through the fixed function's interface) + +- qe_arena/corpus/streamable_len.py + fixed code: ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs + fault streamable_len/no-holdback: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs (reconstructed from the pre-fix streaming behaviour; the pre-fix code had no streamable_len) + fault streamable_len/streams-pending-bytes: ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs (reconstructed from the pre-fix streaming behaviour; the pre-fix code had no streamable_len) + +Other corpus entries adapt MIT-licensed code by the same authors as this repository; their +origins are recorded per entry in META["origin"]. + +RuVector licence: + +MIT License + +Copyright (c) 2025 rUv + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/components/qemedia/UPSTREAM_DOCKERFILE b/components/qemedia/UPSTREAM_DOCKERFILE new file mode 100644 index 0000000000000000000000000000000000000000..a44261e74a1e28d6a437754f3408e75786046fef --- /dev/null +++ b/components/qemedia/UPSTREAM_DOCKERFILE @@ -0,0 +1,33 @@ +# The terminal-interface image (qe_arena.terminal_app): the same tasks and WASM graders as Dockerfile, behind +# tbench2_env-shaped actions (exec / write_file / evaluate) with a real bash per episode. +# +# Unlike Dockerfile, the server runs as root: that is what lets qe_arena/shell.py run every episode's commands +# as its own unprivileged uid (20000-20063). The sources and the WASI runtime are 0700 root, so an episode's +# shell can read neither the corpus (the reference implementations) nor the graders. On a host that drops +# CAP_SETUID the shell reports "disabled" at start-up and exec is refused; write_file and evaluate still work. +FROM python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1 AS wasi-runtime +WORKDIR /build +COPY requirements-wasmtime.lock /build/requirements-wasmtime.lock +RUN pip install --no-cache-dir --require-hashes -r /build/requirements-wasmtime.lock +COPY scripts/build_wasi_runtime.py qe_arena/runtime_pins.json /build/ +RUN python /build/build_wasi_runtime.py --out /opt/qe-arena/wasi --pins /build/runtime_pins.json + +FROM python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1 +LABEL org.opencontainers.image.source="https://github.com/proffesor-for-testing/openenv-qe-arena" +LABEL org.opencontainers.image.description="OpenEnv Arena training environment: QE tasks behind a terminal interface" +LABEL org.opencontainers.image.licenses="MIT" +WORKDIR /app +RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates tini && rm -rf /var/lib/apt/lists/* +COPY requirements.lock requirements-wasmtime.lock /app/ +RUN pip install --no-cache-dir --require-hashes -r /app/requirements-wasmtime.lock \ + && pip install --no-cache-dir -r /app/requirements.lock +COPY --from=wasi-runtime /opt/qe-arena/wasi /opt/qe-arena/wasi +COPY qe_arena /app/qe_arena +COPY openenv.terminal.yaml /app/openenv.yaml +COPY THIRD_PARTY_NOTICES /app/THIRD_PARTY_NOTICES +# The sources and runtime are root-only; the image's own world-writable dirs are locked (shell.SHARED_DIRS). +RUN chmod 0700 /app /opt/qe-arena && chmod 0711 /var/tmp /run/lock +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 ENABLE_WEB_INTERFACE=false QE_ARENA_WASI_ROOT=/opt/qe-arena/wasi +EXPOSE 8000 +ENTRYPOINT ["/usr/bin/tini", "--"] +CMD ["python", "-m", "uvicorn", "qe_arena.terminal_app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"] diff --git a/components/qemedia/runtime/qemedia_compat/__init__.py b/components/qemedia/runtime/qemedia_compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01fa3bcb9e4dc41fa33cb80c6fe9818b5a57e83b --- /dev/null +++ b/components/qemedia/runtime/qemedia_compat/__init__.py @@ -0,0 +1 @@ +"""OpenEnv transport for the selected original QE media tasks.""" diff --git a/components/qemedia/runtime/qemedia_compat/environment.py b/components/qemedia/runtime/qemedia_compat/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..4125f3b5161fd35f987efef10a03ca98b1a35ebf --- /dev/null +++ b/components/qemedia/runtime/qemedia_compat/environment.py @@ -0,0 +1,170 @@ +"""Select original QE media tasks and manage a single active episode.""" +import hashlib +import json +import math +import os +from pathlib import Path +from threading import RLock +import weakref + +from openenv.core.env_server.interfaces import Environment +from openenv.core.env_server.types import EnvironmentMetadata + +ROOT = Path(__file__).resolve().parents[1] +SOURCE_REVISION = '7490e2dc371b5060601ff4399a3d3688bff3ca80' +TASK_IDS = ('qe_skill-media-d2', 'qe_skill-media-d1') +MANIFEST = json.loads((ROOT / 'SOURCE_MANIFEST.json').read_text()) +if MANIFEST['revision'] != SOURCE_REVISION or tuple(MANIFEST['selected_tasks']) != TASK_IDS: + raise RuntimeError('Unexpected original source or selected tasks') + + +def verify_original_source(): + expected = MANIFEST['original_files'] + if any(p.is_symlink() for p in (ROOT / 'qe_arena').rglob('*')): + raise RuntimeError('Symlink in original source tree') + actual = {p.relative_to(ROOT).as_posix() for p in (ROOT / 'qe_arena').rglob('*') if p.is_file()} + if actual != set(expected): + raise RuntimeError('Original source inventory mismatch') + for relative, digest in expected.items(): + path = ROOT / relative + if (path.is_symlink() or not path.is_file() + or not path.resolve().is_relative_to(ROOT) + or hashlib.sha256(path.read_bytes()).hexdigest() != digest): + raise RuntimeError('Original source hash mismatch: ' + relative) + + +verify_original_source() +from qe_arena import shell, skills # noqa: E402 +from qe_arena.terminal_env import TerminalAction, TerminalEnvironment, TerminalObservation # noqa: E402 + + +def verify_runtime(): + if os.geteuid() != 0 or os.environ.get('QE_ARENA_UNSANDBOXED_SHELL') == '1': + raise RuntimeError('The service requires root and the native isolated shell') + import sys + for name, module in tuple(sys.modules.items()): + if name == 'qe_arena' or name.startswith('qe_arena.'): + filename = getattr(module, '__file__', None) + if filename is None or not Path(filename).resolve().is_relative_to(ROOT / 'qe_arena'): + raise RuntimeError('Original module resolved outside the source tree: ' + name) + if shell.mode() != 'uid': + raise RuntimeError('Native isolated exec is unavailable') + if (shell.EXEC_TIMEOUT_S != 30 or shell.MAX_OUTPUT_BYTES != 8192 + or shell.MAX_WRITE_BYTES != 65536 or shell.MAX_READ_BYTES != 65536): + raise RuntimeError('Native shell limits changed') + if skills.SERVED['qe_skill-media-d2'] != ('subtitles', 'timecode', 'catalogue', 'assets'): + raise RuntimeError('Native media d2 pool changed') + if skills.SERVED['qe_skill-media-d1'] != ('timecode', 'catalogue', 'assets'): + raise RuntimeError('Native media d1 pool changed') + + +_SESSION_LOCK = RLock() +_OWNER = None + + +class CompatEnvironment(Environment): + SUPPORTS_CONCURRENT_SESSIONS = False + + def __init__(self): + super().__init__() + self._original = TerminalEnvironment() + self._task_id = None + self._terminal = None + + def reset(self, seed=None, episode_id=None, *, task_id=None, index=None, split='train', **kwargs): + global _OWNER + # Validate before touching an existing episode, including the seed-zero case. + if kwargs: + raise ValueError('Unsupported reset arguments: ' + ', '.join(sorted(kwargs))) + if split != 'train': + raise ValueError('Unknown split') + if index is not None: + if type(index) is not int or not 0 <= index < len(TASK_IDS): + raise ValueError('Invalid task index') + if task_id is not None and task_id != TASK_IDS[index]: + raise ValueError('Task selection mismatch') + task_id = TASK_IDS[index] + if type(task_id) is not str or task_id not in TASK_IDS: + raise ValueError('Reset requires a selected task_id or index') + if seed is not None and (type(seed) is not int or not 0 <= seed < 2**64): + raise ValueError('Seed must be an unsigned 64-bit integer') + with _SESSION_LOCK: + verify_runtime() + owner = _OWNER() if _OWNER is not None else None + if owner is not None and owner is not self: + raise RuntimeError('Another episode is active in this sandbox') + was_active = owner is self + _OWNER = weakref.ref(self) + try: + opening = self._original.reset(task_id=task_id, seed=seed, episode_id=episode_id) + except BaseException: + if not was_active: + self._original.close() + _OWNER = None + self._task_id = None + raise + self._task_id = task_id + self._terminal = None + return opening + + def step(self, action, timeout_s=None, **kwargs): + global _OWNER + with _SESSION_LOCK: + if self._task_id is None: + raise RuntimeError('Reset before stepping') + if self._terminal is not None: + return self._terminal.model_copy(deep=True) + native = action if isinstance(action, TerminalAction) else TerminalAction.model_validate(action) + observed = self._original.step(native, timeout_s=timeout_s, **kwargs) + if observed.done: + reward = observed.reward + if (isinstance(reward, bool) or not isinstance(reward, (int, float)) + or not math.isfinite(reward) or reward not in (0, 1)): + raise RuntimeError('Original terminal reward is not binary') + self._terminal = observed.model_copy(deep=True) + if _OWNER is not None and _OWNER() is self: + _OWNER = None + return observed + + @property + def state(self): + return self._original.state + + def close(self): + global _OWNER + with _SESSION_LOCK: + # This closes only this instance's workspace, including metadata-only instances. + self._original.close() + if _OWNER is not None and _OWNER() is self: + _OWNER = None + self._task_id = None + self._terminal = None + + def get_metadata(self): + return EnvironmentMetadata(name='qemedia', version='1.0.0', + description='Original QE media artifact tasks') + + def list_splits(self): + return ['train'] + + def list_tasks(self, split): + if split != 'train': + raise ValueError('Unknown split') + return [{'id': task_id, 'index': i} for i, task_id in enumerate(TASK_IDS)] + + def num_tasks(self, split): + return len(self.list_tasks(split)) + + def get_task(self, split, index): + if type(index) is not int or not 0 <= index < len(TASK_IDS): + raise ValueError('Invalid task index') + return self.list_tasks(split)[index] + + def get_task_range(self, split, start=None, stop=None): + tasks = self.list_tasks(split) + for bound in (start, stop): + if bound is not None and (type(bound) is not int or not 0 <= bound <= len(tasks)): + raise ValueError('Invalid task range') + if start is not None and stop is not None and start > stop: + raise ValueError('Invalid task range') + return tasks[start:stop] diff --git a/components/qemedia/runtime/qemedia_compat/server.py b/components/qemedia/runtime/qemedia_compat/server.py new file mode 100644 index 0000000000000000000000000000000000000000..09cc8c23db9de75bfde99144ce650a993406fcd8 --- /dev/null +++ b/components/qemedia/runtime/qemedia_compat/server.py @@ -0,0 +1,16 @@ +"""Serve the original terminal action and observation models.""" +from openenv.core.env_server.http_server import create_app +from .environment import CompatEnvironment, TerminalAction, TerminalObservation, verify_runtime + +verify_runtime() +app = create_app(CompatEnvironment, TerminalAction, TerminalObservation, + env_name='qemedia', max_concurrent_envs=1, mode='production') + + +def main(): + import uvicorn + uvicorn.run(app, host='0.0.0.0', port=8000, workers=1, log_level='warning') + + +if __name__ == '__main__': + main() diff --git a/components/qemedia/upstream/qe_arena/__init__.py b/components/qemedia/upstream/qe_arena/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a87f090f15c31dc23c182a15993cc5c53108a471 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/__init__.py @@ -0,0 +1 @@ +"""OpenEnv Arena training environment for quality-engineering tasks.""" diff --git a/components/qemedia/upstream/qe_arena/app.py b/components/qemedia/upstream/qe_arena/app.py new file mode 100644 index 0000000000000000000000000000000000000000..88750aeef963baf46406c97dbc5eee9b7c358274 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/app.py @@ -0,0 +1,21 @@ +import logging +import threading + +from openenv.core.env_server.http_server import create_app + +from . import sandbox +from .environment import QEAction, QEEnvironment, QEObservation + +app = create_app(QEEnvironment, QEAction, QEObservation, env_name="qe_arena", max_concurrent_envs=8) + + +def _warm_sandbox() -> None: + # Each sandbox worker compiles python.wasm (~5 s each at --cpus=2, measured in the image). Do it + # now, off the request path, so /health answers at once and the first episode does not wait. + try: + sandbox.warm() + except Exception: # noqa: BLE001 - logged here; the next run_calls raises the same error + logging.getLogger(__name__).exception("sandbox warm-up failed") + + +threading.Thread(target=_warm_sandbox, name="sandbox-warm", daemon=True).start() diff --git a/components/qemedia/upstream/qe_arena/corpus/__init__.py b/components/qemedia/upstream/qe_arena/corpus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9ede354e9aefba034b69194d82e839f977ba4b --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/__init__.py @@ -0,0 +1,154 @@ +"""Corpus of small, pure QE functions used by the bug-fix and mutant-kill task families. + +Each module in this package follows the corpus contract in docs/DESIGN.md: a one-line module +docstring, a ``META`` dict, the entry function plus any helpers, and ``gen_inputs(rng, n)``. + +An entry whose META has ``real_faults`` is a real-bug entry: the function is the fixed upstream code +and each real fault records the pre-fix logic as an exact text replacement in ``function_source``. +Real-bug entries are served only by the qe_bugfix real tier (``REAL_NAMES``); the injected tiers and +qe_mutant_kill draw from ``INJECTED_NAMES``. + +``META["domain"]`` names the arena domain the code belongs to (``qe_arena.domains.DOMAINS``). A task +cell draws only entries of its own domain (``domain_names``). +""" +from __future__ import annotations + +import ast +import importlib +import pkgutil +import random +from dataclasses import dataclass +from pathlib import Path + +from ..domains import DOMAINS, SOFTWARE + +_PACKAGE_DIR = Path(__file__).resolve().parent + + +@dataclass(frozen=True) +class RealFault: + """A defect that existed upstream before a fix, as an exact replacement in ``function_source``.""" + + id: str + kind: str + summary: str + origin: str + find: str + replace: str + note: str = "" # how the fault relates to the pre-fix code when it is not a literal copy of it + + +@dataclass(frozen=True) +class CorpusEntry: + name: str + entry: str + origin: str + tags: tuple[str, ...] + source: str + function_source: str + summary: str + domain: str = SOFTWARE + real_faults: tuple[RealFault, ...] = () + + +def _is_kept(node: ast.stmt) -> bool: + if isinstance(node, (ast.Import, ast.ImportFrom)): + return True + return isinstance(node, ast.FunctionDef) and node.name != "gen_inputs" + + +def _start_line(node: ast.stmt) -> int: + decorators = getattr(node, "decorator_list", []) + return min([node.lineno] + [d.lineno for d in decorators]) + + +def extract_function_source(text: str) -> str: + """Return the imports plus every function except ``gen_inputs``, verbatim from ``text``. + + Consecutive kept top-level statements form one run, copied with their original + formatting and comments. Runs are joined with two blank lines. + """ + lines = text.splitlines() + runs: list[list[ast.stmt]] = [] + previous_kept = False + for node in ast.parse(text).body: + kept = _is_kept(node) + if kept and previous_kept: + runs[-1].append(node) + elif kept: + runs.append([node]) + previous_kept = kept + chunks = [ + "\n".join(lines[_start_line(run[0]) - 1 : run[-1].end_lineno]) + for run in runs + ] + return "\n\n\n".join(chunks) + "\n" + + +def _summary(text: str) -> str: + docstring = ast.get_docstring(ast.parse(text)) or "" + first_line = docstring.strip().splitlines()[0] if docstring.strip() else "" + for marker in (" Adapted from ", " Ported from ", " Original."): + if marker in first_line: + first_line = first_line.split(marker, 1)[0] + return first_line.strip() + + +def _load_entries() -> dict[str, CorpusEntry]: + entries: dict[str, CorpusEntry] = {} + names = sorted( + info.name + for info in pkgutil.iter_modules([str(_PACKAGE_DIR)]) + if not info.name.startswith("_") + ) + for name in names: + module = importlib.import_module(f"{__name__}.{name}") + text = (_PACKAGE_DIR / f"{name}.py").read_text(encoding="utf-8") + meta = module.META + if meta.get("domain") not in DOMAINS: + raise ValueError(f"corpus entry {name}: META domain must be one of {DOMAINS}, got {meta.get('domain')!r}") + entries[name] = CorpusEntry( + name=name, + entry=meta["entry"], + origin=meta["origin"], + tags=tuple(meta["tags"]), + source=text, + function_source=extract_function_source(text), + summary=_summary(text), + domain=meta["domain"], + real_faults=tuple(RealFault(**fault) for fault in meta.get("real_faults", ())), + ) + return entries + + +ENTRIES: dict[str, CorpusEntry] = _load_entries() +REAL_NAMES: tuple[str, ...] = tuple(name for name, e in ENTRIES.items() if e.real_faults) +INJECTED_NAMES: tuple[str, ...] = tuple(name for name, e in ENTRIES.items() if not e.real_faults) + + +def domain_names(domain: str, names: tuple[str, ...] = INJECTED_NAMES) -> tuple[str, ...]: + """The entries of ``names`` that belong to ``domain``, in their original (sorted) order.""" + if domain not in DOMAINS: + raise ValueError(f"unknown domain: {domain!r}") + return tuple(name for name in names if ENTRIES[name].domain == domain) + + +def _module(name: str): + if name not in ENTRIES: + raise KeyError(f"unknown corpus entry: {name}") + return importlib.import_module(f"{__name__}.{name}") + + +def call_reference(name: str, args: list): + """Call the original entry function directly. For tests only; the verifier runs it in a sandbox.""" + module = _module(name) + return getattr(module, ENTRIES[name].entry)(*args) + + +def gen_inputs(name: str, seed: int, n: int) -> list[list]: + """Deterministic argument lists for ``name``: boundary cases first, then seeded random ones.""" + return _module(name).gen_inputs(random.Random(seed), n) + + +__all__ = ["CorpusEntry", "ENTRIES", "INJECTED_NAMES", "REAL_NAMES", "RealFault", "call_reference", + "domain_names", "extract_function_source", "gen_inputs"] diff --git a/components/qemedia/upstream/qe_arena/corpus/aggregate_risk_factors.py b/components/qemedia/upstream/qe_arena/corpus/aggregate_risk_factors.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbd43542564aa0dea2b4f8234a58c00775c11d7 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/aggregate_risk_factors.py @@ -0,0 +1,53 @@ +"""Rank defect-risk factors by their average contribution across files. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/tools/defect-intelligence/predict.ts (MIT).""" + +META = { + "entry": "aggregate_risk_factors", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/tools/defect-intelligence/predict.ts", + "tags": ["defect-prediction", "grouping", "sorting"], + "domain": "software-engineering", +} + + +def aggregate_risk_factors(predictions): + """Aggregate per-file risk factors into the top five factors overall. + + predictions is a list (one item per file) of lists of [factor_name, contribution] + pairs, where contribution is an int. Every occurrence counts, even if a factor + repeats within one file. For each factor name: count = number of occurrences and + impact = round(sum of contributions / count, 2). Returns [name, impact, count] + rows sorted by impact descending; ties keep the order in which the factor names + first appeared. At most the first 5 rows are returned. + """ + totals = {} + for factors in predictions: + for name, contribution in factors: + impact, count = totals.get(name, [0, 0]) + totals[name] = [impact + contribution, count + 1] + ranked = [] + for name, (impact, count) in totals.items(): + ranked.append([name, round(impact / count, 2), count]) + ranked.sort(key=lambda row: row[1], reverse=True) + return ranked[:5] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[]], + [[[]]], + [[[["churn", 30]]]], + [[[["churn", 30]], [["churn", 10]]]], + [[[["churn", 30], ["churn", 0]]]], + [[[["a", 10], ["b", 20]], [["b", 0], ["c", 5]]]], + [[[["a", 7], ["b", 7], ["c", 7]]]], + [[[["a", 1], ["b", 2], ["c", 3], ["d", 4], ["e", 5], ["f", 6]]]], + [[[["a", 6], ["b", 5], ["c", 4], ["d", 3], ["e", 2], ["f", 1]]]], + [[[["a", 1], ["b", 1], ["c", 1], ["d", 1], ["e", 1], ["f", 1]]]], + [[[["x", 10]], [["x", 11]], [["x", 11]]]], + [[[["size", -5], ["age", 3]]]], + ] + names = ["churn", "size", "age", "authors", "bugs", "deps", "lint"] + while len(cases) < n: + cases.append([[[[rng.choice(names), rng.randint(0, 50)] for _ in range(rng.randint(0, 3))] + for _ in range(rng.randint(1, 4))]]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/alternate_chat_roles.py b/components/qemedia/upstream/qe_arena/corpus/alternate_chat_roles.py new file mode 100644 index 0000000000000000000000000000000000000000..a198fe3827fab539d5886ebf97e0b91a1fe50005 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/alternate_chat_roles.py @@ -0,0 +1,53 @@ +"""Normalize a chat transcript into strict user/assistant alternation. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/llm_providers/providers/anthropic_provider.py (MIT).""" + +META = { + "entry": "alternate_chat_roles", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/llm_providers/providers/anthropic_provider.py", + "tags": ["llm", "normalization", "lists"], + "domain": "software-engineering", +} + + +def alternate_chat_roles(messages): + """Return a new transcript whose roles strictly alternate and start and end with "user". + + messages is a list of {"role": "user" or "assistant", "content": str}; the input is + not modified. Consecutive messages with the same role are merged into one message, + joining the contents with "\n\n". After merging: if the first message is not from + "user", {"role": "user", "content": "Continue."} is inserted at the front; then if + the last message is not from "user", {"role": "user", "content": "Please respond."} + is appended. An empty list returns []. + """ + result = [] + for msg in messages: + if result and result[-1]["role"] == msg["role"]: + result[-1]["content"] += "\n\n" + msg["content"] + else: + result.append({"role": msg["role"], "content": msg["content"]}) + if result and result[0]["role"] != "user": + result.insert(0, {"role": "user", "content": "Continue."}) + if result and result[-1]["role"] != "user": + result.append({"role": "user", "content": "Please respond."}) + return result + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + def _m(role, content): + return {"role": role, "content": content} + + u, a = "user", "assistant" + cases = [ + [[]], + [[_m(u, "hi")]], + [[_m(a, "hi")]], + [[_m(u, "q"), _m(a, "r")]], + [[_m(u, "a"), _m(u, "b")]], + [[_m(a, "a"), _m(a, "b"), _m(u, "c")]], + [[_m(u, "a"), _m(a, "b"), _m(a, "c"), _m(u, "d")]], + [[_m(a, "x"), _m(u, "y"), _m(u, "z"), _m(a, "w")]], + [[_m(u, ""), _m(u, ""), _m(u, "")]], + ] + while len(cases) < n: + cases.append([[_m(rng.choice([u, a]), rng.choice("abcdefg")) for _ in range(rng.randint(1, 6))]]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/amortization_schedule.py b/components/qemedia/upstream/qe_arena/corpus/amortization_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..12df42e31ee17c6a3fb110858bbdf01f1088eeae --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/amortization_schedule.py @@ -0,0 +1,71 @@ +"""Summarise a level-payment loan in integer cents. Original.""" + +import math +from fractions import Fraction + +META = { + "entry": "amortization_schedule", + "origin": "Original.", + "tags": ["loan", "amortization", "money"], + "domain": "finance-economics", +} + + +def amortization_schedule(principal_cents, annual_rate_bp, months): + """Summarise a fixed-rate level-payment loan in integer cents. + + r = annual_rate_bp / 120000 per month, exact. payment = ceil(principal_cents / months) if the + rate is 0, else ceil(principal_cents * r / (1 - (1 + r) ** -months)). From balance = + principal_cents, each month's interest is balance * r rounded half up to a cent. The loan closes + in the first month where balance + interest <= payment, or in month `months`, by paying + balance + interest; otherwise balance becomes balance + interest - payment. + Returns [payment, final_payment, total_interest, months_paid]. + Raises ValueError if principal_cents < 1, months < 1 or annual_rate_bp is outside 0..5000. + """ + if principal_cents < 1 or months < 1 or not 0 <= annual_rate_bp <= 5000: + raise ValueError + if annual_rate_bp == 0: + payment = math.ceil(Fraction(principal_cents, months)) + else: + rate = Fraction(annual_rate_bp, 120000) + payment = math.ceil(principal_cents * rate / (1 - (1 + rate) ** -months)) + balance, total_interest = principal_cents, 0 + for month in range(1, months + 1): + interest = (balance * annual_rate_bp + 60000) // 120000 + total_interest += interest + if balance + interest <= payment or month == months: + return [payment, balance + interest, total_interest, month] + balance += interest - payment + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [100, 0, 3], + [10, 0, 7], + [9, 0, 7], + [7, 1200, 2], + [1000, 3000, 3], + [705, 2132, 7], + [1229, 2598, 5], + [1774, 608, 6], + [59999, 1, 1], + [100000, 0, 12], + [100000, 600, 12], + [100000, 600, 1], + [1, 600, 1], + [1, 1, 1], + [25000000, 450, 360], + [2000000, 5000, 24], + [2000000, 4999, 24], + [500000, 1200, 6], + [0, 600, 12], + [100000, 600, 0], + [100000, -1, 12], + [100000, 5001, 12], + ] + while len(cases) < n: + months = rng.choice([1, 2, 3, 6, 12, 24, 36, 48, 60, rng.randint(1, 120), rng.choice([180, 240, 360])]) + rate = rng.choice([0, rng.randint(1, 3000), rng.randint(1, 3000), rng.randint(1, 5000)]) + cases.append([rng.randint(1, 50) * rng.choice([1, 100, 1000, 10000]) + rng.randint(0, 99), rate, months]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/api_complexity_level.py b/components/qemedia/upstream/qe_arena/corpus/api_complexity_level.py new file mode 100644 index 0000000000000000000000000000000000000000..3b08e981600cfacd7fd2f0a0e357597135f1098c --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/api_complexity_level.py @@ -0,0 +1,57 @@ +"""Bucket an API's performance-test planning complexity. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/performance_planner_agent.py (MIT).""" + +META = { + "entry": "api_complexity_level", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/performance_planner_agent.py", + "tags": ["performance", "planning", "thresholds"], + "domain": "software-engineering", +} + + +def api_complexity_level(total_endpoints, critical_paths, data_intensive_ops): + """Return "low", "medium" or "high" for the planning complexity of an API. + + score = total_endpoints + 2 * critical_paths + 3 * data_intensive_ops. + score < 10 is "low", 10 <= score < 25 is "medium", score >= 25 is "high". + Raises ValueError if any count is negative, or if critical_paths or + data_intensive_ops is greater than total_endpoints. + """ + if min(total_endpoints, critical_paths, data_intensive_ops) < 0: + raise ValueError("counts must be non-negative") + if critical_paths > total_endpoints or data_intensive_ops > total_endpoints: + raise ValueError("subset counts cannot exceed total_endpoints") + score = total_endpoints + critical_paths * 2 + data_intensive_ops * 3 + if score < 10: + return "low" + if score < 25: + return "medium" + return "high" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 0, 0], + [9, 0, 0], + [10, 0, 0], + [7, 1, 0], + [6, 0, 1], + [8, 1, 0], + [24, 0, 0], + [25, 0, 0], + [18, 2, 1], + [17, 2, 1], + [12, 3, 2], + [3, 3, 3], + [4, 3, 3], + [-1, 0, 0], + [5, -1, 0], + [5, 0, -2], + [2, 3, 0], + [2, 0, 3], + [3, 3, 0], + ] + while len(cases) < n: + total = rng.randint(0, 20) + cases.append([total, rng.randint(0, total), rng.randint(0, total)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/artifact_retention_keep.py b/components/qemedia/upstream/qe_arena/corpus/artifact_retention_keep.py new file mode 100644 index 0000000000000000000000000000000000000000..b21b72710cf4d41356be86fd2b6b76407dad2672 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/artifact_retention_keep.py @@ -0,0 +1,62 @@ +"""Decide whether a stored test artifact survives the retention policy. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/storage/utils/retention.py (MIT).""" + +META = { + "entry": "artifact_retention_keep", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/storage/utils/retention.py", + "tags": ["storage", "time-window", "policy"], + "domain": "software-engineering", +} + + +def artifact_retention_keep(rank, keep_latest_n, created_day, retention_days, expires_day, + default_ttl_days, today): + """Return True if an artifact should be kept. Days are integer day numbers. + + rank is the artifact's 0-based position among the newest artifacts (0 = newest), + or None if unranked. Rules in order: + 1. rank is not None and rank < keep_latest_n -> True (always kept). + 2. retention_days is not None and today > created_day + retention_days -> False. + 3. expires_day is not None and today > expires_day -> False. + 4. retention_days and expires_day are both None and + today > created_day + default_ttl_days -> False. + 5. Otherwise True. An artifact is still kept on its last day (today equal to the limit). + """ + if rank is not None and rank < keep_latest_n: + return True + if retention_days is not None and today > created_day + retention_days: + return False + if expires_day is not None and today > expires_day: + return False + if retention_days is None and expires_day is None: + if today > created_day + default_ttl_days: + return False + return True + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 1, 0, None, None, 30, 100], + [1, 1, 0, None, None, 30, 100], + [None, 5, 0, None, None, 30, 100], + [None, 5, 0, None, None, 30, 30], + [None, 5, 0, None, None, 30, 31], + [None, 0, 10, 7, None, 30, 17], + [None, 0, 10, 7, None, 30, 18], + [None, 0, 10, 7, None, 3, 16], + [None, 0, 10, None, 20, 3, 20], + [None, 0, 10, None, 20, 3, 21], + [None, 0, 10, None, 20, 300, 21], + [None, 0, 10, 30, 20, 300, 21], + [None, 0, 10, 5, 40, 30, 16], + [2, 3, 0, 1, 1, 1, 50], + [3, 3, 0, 1, 1, 1, 50], + [0, 0, 0, None, None, 0, 1], + ] + while len(cases) < n: + created = rng.randint(0, 50) + cases.append([rng.choice([None, rng.randint(0, 5)]), rng.randint(0, 4), created, + rng.choice([None, rng.randint(0, 30)]), + rng.choice([None, created + rng.randint(0, 40)]), + rng.randint(1, 40), created + rng.randint(0, 60)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/backoff_schedule.py b/components/qemedia/upstream/qe_arena/corpus/backoff_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..2843302569a930b36629f0eedf3b1f98703e14d9 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/backoff_schedule.py @@ -0,0 +1,53 @@ +"""List capped exponential retry delays with their jitter allowance. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/retry-engine.ts (MIT).""" + +META = { + "entry": "backoff_schedule", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/retry-engine.ts", + "tags": ["retry", "backoff", "arithmetic"], + "domain": "software-engineering", +} + + +def backoff_schedule(attempts, base_ms, max_ms, jitter_pct): + """Return the maximum delay (ms) before each retry attempt 0..attempts-1. + + For attempt k: exponential = min(base_ms * 2**k, max_ms) and the delay is + exponential + exponential * jitter_pct // 100 (the largest value the random jitter + can add, using integer division). Returns a list of `attempts` ints ([] for 0). + Raises ValueError if attempts < 0, base_ms < 1, max_ms < base_ms, or jitter_pct + is outside 0..100. + """ + if attempts < 0 or base_ms < 1 or max_ms < base_ms: + raise ValueError("invalid backoff parameters") + if jitter_pct < 0 or jitter_pct > 100: + raise ValueError("jitter_pct must be within 0..100") + delays = [] + for attempt in range(attempts): + exponential = min(base_ms * 2 ** attempt, max_ms) + delays.append(exponential + exponential * jitter_pct // 100) + return delays + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 100, 1000, 0], + [1, 100, 1000, 0], + [4, 100, 1000, 0], + [5, 100, 1000, 0], + [6, 100, 1600, 25], + [5, 1000, 32000, 25], + [3, 7, 7, 50], + [4, 3, 20, 33], + [3, 10, 100, 100], + [2, 10, 100, 101], + [2, 10, 100, -1], + [-1, 10, 100, 0], + [2, 0, 100, 0], + [2, 50, 49, 0], + [10, 1, 1000, 10], + ] + while len(cases) < n: + base = rng.randint(1, 500) + cases.append([rng.randint(0, 10), base, base * rng.randint(1, 40), rng.randint(0, 100)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/badge_dimensions.py b/components/qemedia/upstream/qe_arena/corpus/badge_dimensions.py new file mode 100644 index 0000000000000000000000000000000000000000..583c5936a54b860edddb33283613a3f6cfb4e165 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/badge_dimensions.py @@ -0,0 +1,52 @@ +"""Compute SVG badge geometry from label and message lengths. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/badges/generator.py (MIT).""" + +META = { + "entry": "badge_dimensions", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/badges/generator.py", + "tags": ["reporting", "arithmetic"], + "domain": "software-engineering", +} + + +def badge_dimensions(label, message): + """Return the integer layout of a two-part status badge (shields.io style). + + With char_width = 6 pixels: + label_width = len(label) * 6 + 10 + message_width = len(message) * 6 + 10 + width = label_width + message_width + label_x = label_width * 10 // 2 + message_x = label_width * 10 + message_width * 10 // 2 + label_text_length = len(label) * 6 * 10 + message_text_length = len(message) * 6 * 10 + Returns a dict with exactly those seven keys. + """ + char_width = 6 + label_width = len(label) * char_width + 10 + message_width = len(message) * char_width + 10 + return { + "width": label_width + message_width, + "label_width": label_width, + "message_width": message_width, + "label_x": (label_width * 10) // 2, + "message_x": (label_width * 10) + (message_width * 10) // 2, + "label_text_length": len(label) * char_width * 10, + "message_text_length": len(message) * char_width * 10, + } + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["", ""], + ["a", ""], + ["", "a"], + ["coverage", "87%"], + ["build", "passing"], + ["tests", "1203 passed"], + ["quality gate", "failed"], + ] + words = ["coverage", "tests", "build", "flaky", "mutation", "92%", "ok", "failed", "A+", "v3.1.0"] + while len(cases) < n: + cases.append([rng.choice(words)[: rng.randint(0, 8)], rng.choice(words)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/baseline_verdict.py b/components/qemedia/upstream/qe_arena/corpus/baseline_verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..3717a523a50c7ec9213725d1fc38e41bb165ed18 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/baseline_verdict.py @@ -0,0 +1,60 @@ +"""Compare a test success rate against its baseline. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/services/pattern_analytics.py (MIT).""" + +META = { + "entry": "baseline_verdict", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/services/pattern_analytics.py", + "tags": ["analytics", "thresholds", "regression"], + "domain": "software-engineering", +} + + +def baseline_verdict(current_success, baseline_success): + """Classify the change of a test success rate (integer percent) versus a baseline. + + baseline_success None -> "no baseline", without checking current_success at all. + Otherwise with d = current - baseline: + d > 10 -> "significantly improved" + 0 < d <= 10 -> "improved" + -5 <= d <= 0 -> "maintained" + d < -5 -> "degraded" + When baseline_success is not None, raises ValueError if either rate is outside 0..100. + """ + if baseline_success is None: + return "no baseline" + for rate in (current_success, baseline_success): + if rate < 0 or rate > 100: + raise ValueError("rates are percentages") + if current_success > baseline_success + 10: + return "significantly improved" + if current_success > baseline_success: + return "improved" + if current_success >= baseline_success - 5: + return "maintained" + return "degraded" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [50, None], + [0, 0], + [61, 50], + [60, 50], + [59, 50], + [51, 50], + [50, 50], + [46, 50], + [45, 50], + [44, 50], + [100, 89], + [100, 90], + [0, 6], + [0, 5], + [101, 50], + [50, -1], + [-1, None], + ] + while len(cases) < n: + base = rng.randint(0, 100) + cases.append([max(0, min(100, base + rng.randint(-15, 15))), base]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/booking_conflicts.py b/components/qemedia/upstream/qe_arena/corpus/booking_conflicts.py new file mode 100644 index 0000000000000000000000000000000000000000..683ba6ce9380161f76b559cfedbf25c0b41080f3 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/booking_conflicts.py @@ -0,0 +1,60 @@ +"""Find meeting-room bookings that clash once a cleaning turnover gap is required. Original.""" + +META = { + "entry": "booking_conflicts", + "origin": "Original.", + "tags": ["scheduling", "intervals", "calendar"], + "domain": "office-white-collar", +} + + +def booking_conflicts(bookings, turnover): + """Return clashing meeting-room bookings as a list of [i, j, shortfall], i < j, sorted. + + bookings are [room, start, end] with integer minutes 0 <= start < end <= 1440; a room + needs turnover (int >= 0) free minutes between meetings. i and j clash when the room is + the same and start_i < end_j + turnover and start_j < end_i + turnover; shortfall is + min(end_i, end_j) + turnover - max(start_i, start_j). Raises ValueError for a negative + turnover or a booking time outside 0 <= start < end <= 1440. + """ + if turnover < 0: + raise ValueError("turnover must be >= 0") + for room, start, end in bookings: + if not 0 <= start < end <= 1440: + raise ValueError("bad booking time") + clashes = [] + for i in range(len(bookings)): + room_i, start_i, end_i = bookings[i] + for j in range(i + 1, len(bookings)): + room_j, start_j, end_j = bookings[j] + if room_i == room_j and start_i < end_j + turnover and start_j < end_i + turnover: + clashes.append([i, j, min(end_i, end_j) + turnover - max(start_i, start_j)]) + return clashes + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], 0], + [[["Oak", 540, 600], ["Oak", 600, 660]], 0], + [[["Oak", 540, 600], ["Oak", 600, 660]], 10], + [[["Oak", 540, 600], ["Oak", 610, 660]], 10], + [[["Oak", 540, 600], ["Oak", 609, 660]], 10], + [[["Oak", 540, 600], ["Elm", 570, 630]], 0], + [[["Oak", 0, 30], ["Oak", 1380, 1440], ["Oak", 20, 40]], 0], + [[["Oak", 600, 660], ["Oak", 540, 600], ["Oak", 630, 700]], 5], + [[["Oak", 600, 660], ["Oak", 540, 600]], 0], + [[["Oak", 540, 600]], -1], + [[["Oak", 600, 600]], 0], + [[["Oak", -1, 30]], 0], + [[["Oak", 1400, 1441]], 0], + [[["Elm", 480, 540], ["Oak", 700, 650]], 0], + ] + rooms = ["A", "B", "C"] + while len(cases) < n: + bookings = [] + for _ in range(rng.choice([2, 2, 3, 4])): + start = 5 * rng.randint(96, 216) + bookings.append([rng.choice(rooms), start, start + 5 * rng.randint(3, 24)]) + cases.append([bookings, rng.choice([0, 0, 5, 10, 15])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/boundary_violations.py b/components/qemedia/upstream/qe_arena/corpus/boundary_violations.py new file mode 100644 index 0000000000000000000000000000000000000000..aad7cb510596a5a8262a06d54a835bf5f043abf7 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/boundary_violations.py @@ -0,0 +1,83 @@ +"""Build request values that each violate one schema boundary. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/functional_negative_agent.py (MIT).""" + +META = { + "entry": "boundary_violations", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/functional_negative_agent.py", + "tags": ["api", "negative-testing", "boundary-values"], + "domain": "software-engineering", +} + + +def boundary_violations(properties): + """Return up to three property values that each break one JSON-schema boundary. + + properties maps a name to a schema dict and is visited in insertion order. + - "integer" or "number": maximum + 1 if "maximum" is set, else minimum - 1 if + "minimum" is set. + - "string" (also the default when "type" is missing): "x" * (maxLength + 1) if + "maxLength" is set, else "x" * (minLength - 1) if minLength is set and > 0. + - "array": ["item"] * (maxItems + 1) if "maxItems" is set, else + ["item"] * (minItems - 1) if minItems is set and > 0. + Other types, and properties with no usable boundary, are skipped. Stops as soon + as three modifications exist. Returns a dict of property name -> violating value. + """ + modifications = {} + for name, schema in properties.items(): + kind = schema.get("type", "string") + if kind in ("integer", "number"): + if "maximum" in schema: + modifications[name] = schema["maximum"] + 1 + elif "minimum" in schema: + modifications[name] = schema["minimum"] - 1 + elif kind == "string": + if "maxLength" in schema: + modifications[name] = "x" * (schema["maxLength"] + 1) + elif "minLength" in schema and schema["minLength"] > 0: + modifications[name] = "x" * (schema["minLength"] - 1) + elif kind == "array": + if "maxItems" in schema: + modifications[name] = ["item"] * (schema["maxItems"] + 1) + elif "minItems" in schema and schema["minItems"] > 0: + modifications[name] = ["item"] * (schema["minItems"] - 1) + if len(modifications) >= 3: + break + return modifications + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + def _schema(rng): + kind = rng.choice(["integer", "number", "string", "array", "boolean", None]) + schema = {} if kind is None else {"type": kind} + names = {"integer": ("minimum", "maximum"), "number": ("minimum", "maximum"), + "string": ("minLength", "maxLength"), "array": ("minItems", "maxItems")} + low_key, high_key = names.get(kind or "string", ("minLength", "maxLength")) + if rng.random() < 0.6: + schema[low_key] = rng.randint(0, 4) + if rng.random() < 0.5: + schema[high_key] = rng.randint(1, 6) + return schema + + cases = [ + [{}], + [{"a": {"type": "integer", "maximum": 10}}], + [{"a": {"type": "number", "minimum": 0}}], + [{"a": {"type": "integer", "minimum": 2, "maximum": 5}}], + [{"a": {"type": "integer"}}], + [{"s": {"maxLength": 3}}], + [{"s": {"type": "string", "minLength": 0}}], + [{"s": {"type": "string", "minLength": 1}}], + [{"s": {"type": "string", "minLength": 3, "maxLength": 4}}], + [{"s": {"type": "string", "minLength": 4}}], + [{"l": {"type": "array", "maxItems": 1}}], + [{"l": {"type": "array", "minItems": 1}}], + [{"l": {"type": "array", "minItems": 3}}], + [{"l": {"type": "array", "minItems": 0}}], + [{"b": {"type": "boolean", "maximum": 1}}], + [{"a": {"type": "integer", "maximum": 1}, "b": {"maxLength": 0}, "c": {"type": "array", "maxItems": 0}}], + [{"a": {"type": "integer", "maximum": 1}, "b": {"maxLength": 0}, "c": {"type": "array", "maxItems": 0}, "d": {"type": "number", "minimum": 1}}], + [{"a": {"type": "integer"}, "b": {"maxLength": 1}, "c": {"type": "boolean"}, "d": {"type": "number", "minimum": -3}, "e": {"type": "array", "minItems": 2}}], + ] + while len(cases) < n: + cases.append([{f"p{i}": _schema(rng) for i in range(rng.randint(1, 5))}]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/brace_delta.py b/components/qemedia/upstream/qe_arena/corpus/brace_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..b440e3637695f811c09f19d87559c2c99dd6057c --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/brace_delta.py @@ -0,0 +1,59 @@ +"""Count the net curly-brace depth change of a source line, ignoring strings. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/parsers/multi-language-parser.ts (MIT).""" + +META = { + "entry": "brace_delta", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/parsers/multi-language-parser.ts", + "tags": ["parsing", "strings"], + "domain": "software-engineering", +} + + +def brace_delta(line): + """Return (number of "{") - (number of "}") in line, ignoring braces inside strings. + + A string starts at ", ' or ` and ends at the next occurrence of the same quote + character that is not immediately preceded by a backslash. Braces inside a string + are not counted. An unterminated string runs to the end of the line. + """ + delta = 0 + in_string = False + quote = "" + for i in range(len(line)): + ch = line[i] + if in_string: + if ch == quote and line[i - 1] != "\\": + in_string = False + continue + if ch == '"' or ch == "'" or ch == "`": + in_string = True + quote = ch + elif ch == "{": + delta += 1 + elif ch == "}": + delta -= 1 + return delta + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [""], + ["{"], + ["}"], + ["{}"], + ["if (x) {"], + ["} else {"], + ["'{'"], + ['"}" + {'], + ["`${a}` {"], + ['"a\\"{" }'], + ["'it\\'s {' {"], + ['"{" \'}\' {'], + ["'{"], + ['"x" {{ "y" }'], + ["{'\"'}"], + ] + alphabet = ['{', '}', '{', '}', '"', "'", '`', '\\', 'a', ' '] + while len(cases) < n: + cases.append(["".join(rng.choice(alphabet) for _ in range(rng.randint(1, 16)))]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/calibration_fit.py b/components/qemedia/upstream/qe_arena/corpus/calibration_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..84faedc7228fc605c8f8856acaa17817d38ae2f5 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/calibration_fit.py @@ -0,0 +1,52 @@ +"""Least-squares gain and offset calibration in exact arithmetic. Original.""" + +from fractions import Fraction + +META = { + "entry": "calibration_fit", + "origin": "Original.", + "tags": ["calibration", "regression", "exact-arithmetic"], + "domain": "natural-science", +} + + +def calibration_fit(pairs, tolerance): + """Fit reference = gain * raw + offset to [raw, reference] integer pairs by ordinary least squares. + + With n pairs and sums Sx = sum(raw), Sy = sum(reference), Sxx = sum(raw * raw) and + Sxy = sum(raw * reference): gain = (n * Sxy - Sx * Sy) / (n * Sxx - Sx * Sx) and + offset = (Sy - gain * Sx) / n, both exact. A pair's residual is + gain * raw + offset - reference; the fit is accepted when every residual's absolute value is + <= tolerance. Returns [[gain_num, gain_den], [offset_num, offset_den], accepted], the + fractions in lowest terms with a positive denominator and accepted a bool. + Raises ValueError if fewer than two distinct raw readings are given (including no pairs). + """ + n = len(pairs) + sx = sum(raw for raw, _ in pairs) + sy = sum(ref for _, ref in pairs) + sxx = sum(raw * raw for raw, _ in pairs) + sxy = sum(raw * ref for raw, ref in pairs) + denominator = n * sxx - sx * sx + if denominator == 0: + raise ValueError("need at least two distinct raw readings") + gain = Fraction(n * sxy - sx * sy, denominator) + offset = (sy - gain * sx) / n + worst = max(abs(gain * raw + offset - ref) for raw, ref in pairs) + return [[gain.numerator, gain.denominator], [offset.numerator, offset.denominator], worst <= tolerance] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], 0], [[[5, 10]], 0], [[[5, 10], [5, 12]], 1], [[[0, 1], [10, 21]], 0], + [[[0, 3], [1, 5], [2, 7]], 0], [[[0, 0], [1, 1], [2, 3]], 0], [[[0, 0], [1, 1], [2, 3]], 1], + [[[1, 2], [2, 3], [3, 5], [4, 4]], 1], [[[-2, 7], [2, -1]], 0], [[[3, 4], [7, 4]], 0], + [[[100, 251], [200, 498], [300, 752]], 2], [[[100, 251], [200, 498], [300, 752]], 1], + [[[1, 10], [3, 2]], 5], [[[0, 5], [4, 9], [8, 11], [12, 18]], 1], + ] + while len(cases) < n: + gain, offset = rng.randint(-3, 5), rng.randint(-20, 20) + raws = [rng.randint(-10, 40) for _ in range(rng.randint(2, 4 if rng.random() < 0.6 else 7))] + pairs = [[x, gain * x + offset + rng.randint(-2, 2)] for x in raws] + cases.append([pairs, rng.randint(0, 3)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/chat_completion_result.py b/components/qemedia/upstream/qe_arena/corpus/chat_completion_result.py new file mode 100644 index 0000000000000000000000000000000000000000..72b55cbc6331e06e20a280b49701d18726e9aeae --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/chat_completion_result.py @@ -0,0 +1,71 @@ +"""Build the finish_reason and token usage of an OpenAI-style chat completion. Ported from Rust; adapted from ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm-cli/src/commands/serve.rs (MIT).""" + +PRE_FIX = "ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm-cli/src/commands/serve.rs" +META = { + "entry": "chat_completion_result", + "origin": "ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm-cli/src/commands/serve.rs", + "tags": ["llm", "api", "accounting"], + "domain": "software-engineering", + "real_faults": [ + {"id": "chat_completion_result/always-stop", "kind": "constant-field", "origin": PRE_FIX, + "summary": "finish_reason is always stop, even when max_tokens cut the reply or generation failed", + "find": " if cause == \"length\":\n finish_reason = \"length\"\n" + " elif cause in (\"stop\", \"end_of_sequence\", \"cancelled\"):\n finish_reason = \"stop\"\n" + " else:\n raise ValueError(\"generation ended with an error\")\n", + "replace": " finish_reason = \"stop\"\n"}, + {"id": "chat_completion_result/whitespace-token-count", "kind": "placeholder-approximation", + "origin": PRE_FIX, "summary": "usage counts whitespace-separated words, not tokens", + "find": " used = [prompt_tokens, completion_tokens]\n", + "replace": " used = [len(prompt.split()), len(completion.split())]\n"}, + ], +} + + +def chat_completion_result(cause, prompt, completion, prompt_tokens, completion_tokens): + """Return {"finish_reason": ..., "usage": {...}} for a finished chat completion. + + cause says how generation ended. "length" (max_tokens reached) gives finish_reason + "length"; "stop" (a stop sequence), "end_of_sequence" (an end-of-turn token) and + "cancelled" give "stop"; "error" or any other cause raises ValueError. usage is + {"prompt_tokens": p, "completion_tokens": c, "total_tokens": p + c} where p and c + are the tokenizer's counts prompt_tokens and completion_tokens; the prompt and + completion texts do not affect usage. Raises ValueError if a count is negative. + """ + if prompt_tokens < 0 or completion_tokens < 0: + raise ValueError("token counts must be non-negative") + if cause == "length": + finish_reason = "length" + elif cause in ("stop", "end_of_sequence", "cancelled"): + finish_reason = "stop" + else: + raise ValueError("generation ended with an error") + used = [prompt_tokens, completion_tokens] + usage = {"prompt_tokens": used[0], "completion_tokens": used[1], "total_tokens": used[0] + used[1]} + return {"finish_reason": finish_reason, "usage": usage} + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["stop", "", "", 0, 0], + ["length", "Hi", "Hello there", 1, 2], + ["end_of_sequence", "Capital of France?", "Paris", 5, 1], + ["cancelled", "a b", "c", 2, 1], + ["error", "a", "b", 1, 1], + ["timeout", "a", "b", 1, 1], + ["stop", "one two three", "four five", 3, 2], + ["length", "x", "y", -1, 0], + ["stop", "x", "y", 0, -1], + ["STOP", "x", "y", 1, 1], + ["stop", "Hello, world!", "Bonjour", 4, 3], + ["end_of_sequence", "a b c d", "", 9, 0], + ] + words = ["the", "cat", "sat", "Paris", "is", "x=1;", "ok", "no"] + causes = ["stop", "stop", "end_of_sequence", "end_of_sequence", "length", "cancelled", "error"] + while len(cases) < n: + prompt = " ".join(rng.choice(words) for _ in range(rng.randint(0, 5))) + completion = " ".join(rng.choice(words) for _ in range(rng.randint(0, 5))) + p = len(prompt.split()) + (rng.randint(0, 3) if rng.random() < 0.6 else 0) + c = len(completion.split()) + (rng.randint(0, 3) if rng.random() < 0.6 else 0) + cases.append([rng.choice(causes), prompt, completion, p, c]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/claim_steal_priority.py b/components/qemedia/upstream/qe_arena/corpus/claim_steal_priority.py new file mode 100644 index 0000000000000000000000000000000000000000..f310dfccfbf0aa335184a4c31b3d6f8093a2228a --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/claim_steal_priority.py @@ -0,0 +1,60 @@ +"""Score how urgently a stalled work claim should be stolen. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/coordination/claims/work-stealing.ts (MIT).""" + +META = { + "entry": "claim_steal_priority", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/coordination/claims/work-stealing.ts", + "tags": ["scheduling", "scoring"], + "domain": "software-engineering", +} + + +def claim_steal_priority(priority, stale_ms, time_to_deadline_ms, steal_count): + """Return the integer steal priority of a work claim (higher = steal sooner). + + score = base + staleness + deadline - 10 * steal_count, where + - base is 100 for "p0", 75 for "p1", 50 for "p2", 25 for "p3"; + - staleness = min(stale_ms // 60000, 50) (whole minutes since the last update); + - deadline is 0 when time_to_deadline_ms is None, otherwise 50 if it is < 3600000 + (under an hour, including overdue negatives), 25 if < 86400000, else 0. + Raises ValueError for an unknown priority or a negative stale_ms or steal_count. + """ + base = {"p0": 100, "p1": 75, "p2": 50, "p3": 25} + if priority not in base: + raise ValueError("unknown priority") + if stale_ms < 0 or steal_count < 0: + raise ValueError("stale_ms and steal_count must be non-negative") + score = base[priority] + min(stale_ms // 60000, 50) + if time_to_deadline_ms is not None: + if time_to_deadline_ms < 3600000: + score += 50 + elif time_to_deadline_ms < 86400000: + score += 25 + score -= steal_count * 10 + return score + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["p0", 0, None, 0], + ["p1", 59999, None, 0], + ["p2", 60000, None, 0], + ["p3", 3000000, None, 0], + ["p3", 3060000, None, 0], + ["p3", 2999999, None, 0], + ["p1", 0, 3599999, 0], + ["p1", 0, 3600000, 0], + ["p1", 0, 86399999, 0], + ["p1", 0, 86400000, 0], + ["p0", 0, -5000, 0], + ["p2", 120000, 7200000, 2], + ["p0", 0, None, 13], + ["p4", 0, None, 0], + ["P0", 0, None, 0], + ["p1", -1, None, 0], + ["p1", 0, None, -1], + ] + while len(cases) < n: + cases.append([rng.choice(["p0", "p1", "p2", "p3"]), rng.randint(0, 4000000), + rng.choice([None, rng.randint(-100000, 100000000)]), rng.randint(0, 4)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/compare_versions.py b/components/qemedia/upstream/qe_arena/corpus/compare_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..8c402a51b347129705813a17d05bbab039c16b37 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/compare_versions.py @@ -0,0 +1,67 @@ +"""Compare two dotted version strings. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/tools/security-compliance/scan.ts (MIT).""" + +META = { + "entry": "compare_versions", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/tools/security-compliance/scan.ts", + "tags": ["versions", "parsing"], + "domain": "software-engineering", +} + + +def parse_version(text): + """Return the first three numeric components of a version string, padded with 0.""" + if text.startswith("v"): + text = text[1:] + parts = text.split(".")[:3] + for part in parts: + if not part.isdigit(): + raise ValueError("bad version component: " + part) + numbers = [int(part) for part in parts] + return numbers + [0] * (3 - len(numbers)) + + +def compare_versions(a, b): + """Compare versions like "1.2.3": return -1 if a < b, 0 if equal, 1 if a > b. + + One leading "v" is ignored. Only the first three dot-separated components are + read (later ones are ignored without validation); missing components count as 0, + so "1.2" equals "1.2.0". Components compare numerically ("1.10" > "1.9"). + Raises ValueError if one of the first three components is empty or not all digits. + """ + pa, pb = parse_version(a), parse_version(b) + for i in range(3): + if pa[i] < pb[i]: + return -1 + if pa[i] > pb[i]: + return 1 + return 0 + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["1.0.0", "1.0.0"], + ["1.2", "1.2.0"], + ["1", "1.0.1"], + ["1.10.0", "1.9.9"], + ["1.9.9", "1.10.0"], + ["2.0.0", "1.99.99"], + ["0.0.1", "0.0.2"], + ["0.1.0", "0.0.9"], + ["v1.2.3", "1.2.3"], + ["vv1.0", "1.0"], + ["1.2.3.9", "1.2.3.1"], + ["1.2.3", "1.2.4.x"], + ["1..3", "1.0.3"], + ["1.2.beta", "1.2.0"], + ["", "0"], + ["3.0.1", "3.0.0"], + ["10.0.0", "9.0.0"], + ] + while len(cases) < n: + def version(): + return ".".join(str(rng.randint(0, 12)) for _ in range(rng.randint(1, 4))) + a = version() + b = a if rng.random() < 0.2 else version() + cases.append([rng.choice(["", "v"]) + a, b]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/complexity_bucket.py b/components/qemedia/upstream/qe_arena/corpus/complexity_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e85c11a405d8af8246778c5ecbf8c5a910f461 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/complexity_bucket.py @@ -0,0 +1,68 @@ +"""Bucket a QE task's complexity from code-size signals. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/state_encoder.py (MIT).""" + +META = { + "entry": "complexity_bucket", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/state_encoder.py", + "tags": ["scoring", "thresholds"], + "domain": "software-engineering", +} + + +def complexity_bucket(lines_of_code, cyclomatic, num_dependencies, num_tests): + """Return "simple", "moderate" or "complex" for a task context. + + Points: lines_of_code > 500 adds 2, else > 100 adds 1; cyclomatic > 20 adds 2, + else > 10 adds 1; num_dependencies > 10 adds 1; num_tests > 100 adds 1. + A total of 4 or more is "complex", 2 or 3 is "moderate", 0 or 1 is "simple". + Raises ValueError if any argument is negative. + """ + if min(lines_of_code, cyclomatic, num_dependencies, num_tests) < 0: + raise ValueError("signals must be non-negative") + score = 0 + if lines_of_code > 500: + score += 2 + elif lines_of_code > 100: + score += 1 + if cyclomatic > 20: + score += 2 + elif cyclomatic > 10: + score += 1 + if num_dependencies > 10: + score += 1 + if num_tests > 100: + score += 1 + if score >= 4: + return "complex" + if score >= 2: + return "moderate" + return "simple" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 0, 0, 0], + [100, 10, 10, 100], + [101, 0, 0, 0], + [101, 11, 0, 0], + [500, 20, 0, 0], + [501, 0, 0, 0], + [501, 11, 0, 0], + [0, 21, 0, 0], + [0, 21, 11, 101], + [0, 0, 11, 0], + [0, 0, 11, 101], + [0, 11, 0, 101], + [501, 21, 0, 0], + [101, 11, 11, 0], + [101, 11, 11, 101], + [101, 0, 0, 100], + [101, 0, 10, 0], + [-1, 0, 0, 0], + [0, 0, 0, -5], + ] + while len(cases) < n: + cases.append([rng.choice([rng.randint(0, 700), rng.choice([100, 101, 500, 501])]), + rng.choice([rng.randint(0, 30), rng.choice([10, 11, 20, 21])]), + rng.randint(5, 15), rng.randint(80, 120)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/compound_interest.py b/components/qemedia/upstream/qe_arena/corpus/compound_interest.py new file mode 100644 index 0000000000000000000000000000000000000000..4be7d270304610ef08b9e4a821ff421ece378c1e --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/compound_interest.py @@ -0,0 +1,70 @@ +"""Grow a deposit by compound interest with banker's rounding of each period. Original.""" + +META = { + "entry": "compound_interest", + "origin": "Original.", + "tags": ["interest", "rounding", "money"], + "domain": "finance-economics", +} + + +def compound_interest(principal_cents, annual_rate_bp, periods_per_year, years): + """Compound a deposit in integer cents, rounding each period's interest half to even. + + There are periods_per_year * years periods. Each period's interest is + balance * annual_rate_bp / (10000 * periods_per_year) rounded to a whole cent, an exact half + cent going to the even neighbour (banker's rounding), and is added to the balance. + Returns [final_balance, total_interest, ties]; ties counts periods whose exact interest ended + in exactly half a cent. + Raises ValueError if periods_per_year is not 1, 2, 4 or 12, or if principal_cents < 0, + annual_rate_bp < 0, or years is outside 0..50. + """ + if periods_per_year not in (1, 2, 4, 12): + raise ValueError("invalid frequency") + if principal_cents < 0 or annual_rate_bp < 0 or years < 0 or years > 50: + raise ValueError("invalid terms") + denominator = 10000 * periods_per_year + balance, ties = principal_cents, 0 + for _ in range(periods_per_year * years): + whole, rest = divmod(balance * annual_rate_bp, denominator) + if 2 * rest == denominator: + ties += 1 + whole += whole % 2 + elif 2 * rest > denominator: + whole += 1 + balance += whole + return [balance, balance - principal_cents, ties] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [50, 10000, 1, 1], + [150, 10000, 1, 1], + [250, 10000, 1, 1], + [149, 10000, 1, 1], + [151, 10000, 1, 1], + [1050, 1200, 12, 1], + [1150, 1200, 12, 1], + [100000, 500, 1, 0], + [100000, 500, 1, 1], + [100000, 500, 2, 1], + [100000, 500, 4, 2], + [100000, 500, 12, 50], + [0, 500, 12, 10], + [100000, 0, 12, 10], + [100000, 500, 3, 1], + [100000, 500, 365, 1], + [-1, 500, 12, 1], + [100000, -1, 12, 1], + [100000, 500, 12, -1], + [100000, 500, 12, 51], + [350, 2000, 4, 3], + [12345, 375, 2, 7], + ] + while len(cases) < n: + periods = rng.choice([1, 2, 4, 12]) + rate = rng.choice([600, 1200, 2400, 10000, 400 * periods, rng.randint(1, 2500)]) + principal = rng.randint(0, 2000) * 100 + rng.choice([50, 50, rng.randint(0, 99)]) + cases.append([principal, rate, periods, rng.randint(0, 12)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/convert_timecode.py b/components/qemedia/upstream/qe_arena/corpus/convert_timecode.py new file mode 100644 index 0000000000000000000000000000000000000000..7d76b7b5f7460e1eb41650bed73b3d69bd9f939d --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/convert_timecode.py @@ -0,0 +1,63 @@ +"""Convert a non-drop-frame SMPTE timecode between integer frame rates. Original.""" + +import re + +META = { + "entry": "convert_timecode", + "origin": "Original.", + "tags": ["timecode", "smpte", "frame-rate"], + "domain": "media-content-production", +} + + +def convert_timecode(timecode, src_fps, dst_fps): + """Convert a non-drop-frame "HH:MM:SS:FF" timecode; return [dst frames, dst timecode]. + + Rates must be 24, 25, 30, 48, 50 or 60. Fields are two digits: HH 00-23, MM and SS + 00-59, FF 00 to src_fps - 1. frames = ((HH * 60 + MM) * 60 + SS) * src_fps + FF becomes + frames * dst_fps // src_fps (rounded down) at dst_fps, written back as "HH:MM:SS:FF". + Raises ValueError for another rate, a malformed timecode or a field out of range. + """ + for fps in (src_fps, dst_fps): + if fps not in (24, 25, 30, 48, 50, 60): + raise ValueError("unsupported frame rate") + match = re.fullmatch(r"(\d\d):(\d\d):(\d\d):(\d\d)", timecode) + if not match: + raise ValueError("timecode must be HH:MM:SS:FF") + hours, minutes, seconds, frame = (int(part) for part in match.groups()) + if hours > 23 or minutes > 59 or seconds > 59 or frame >= src_fps: + raise ValueError("field out of range") + count = ((hours * 60 + minutes) * 60 + seconds) * src_fps + frame + frames = count * dst_fps // src_fps + whole, frame = divmod(frames, dst_fps) + return [frames, "%02d:%02d:%02d:%02d" % (whole // 3600, whole // 60 % 60, whole % 60, frame)] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["00:00:00:00", 24, 25], + ["01:00:00:00", 25, 30], + ["00:00:01:23", 24, 48], + ["00:00:01:24", 24, 48], + ["00:00:01:29", 30, 25], + ["00:00:01:12", 25, 24], + ["23:59:59:59", 60, 50], + ["24:00:00:00", 25, 25], + ["00:60:00:00", 25, 25], + ["00:00:60:00", 25, 25], + ["00:59:59:24", 25, 60], + ["10:10:10:10", 23, 25], + ["10:10:10:10", 25, 29], + ["1:00:00:00", 25, 25], + ["01:00:00;00", 30, 30], + ["12:34:56:07", 30, 24], + ] + rates = [24, 25, 30, 48, 50, 60] + while len(cases) < n: + src, dst = rng.choice(rates), rng.choice(rates + [29] if rng.random() < 0.1 else rates) + hours = rng.choice([0, 0, 0, 1, rng.randint(0, 23)]) # most clips are under an hour + last_frame = src - 1 if rng.random() < 0.9 else src # sometimes one frame too many + parts = [hours, rng.choice([0, rng.randint(0, 59)]), rng.randint(0, 59), rng.randint(0, last_frame)] + cases.append([":".join("%02d" % p for p in parts), src, dst]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/coverage_gap_severity.py b/components/qemedia/upstream/qe_arena/corpus/coverage_gap_severity.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab5f69d3193ed2acbde4a226193ab57da6a006b --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/coverage_gap_severity.py @@ -0,0 +1,59 @@ +"""Rate the severity of an uncovered code range. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/coverage-analysis/services/coverage-parser.ts (MIT).""" + +META = { + "entry": "coverage_gap_severity", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/coverage-analysis/services/coverage-parser.ts", + "tags": ["coverage", "thresholds"], + "domain": "software-engineering", +} + + +def coverage_gap_severity(range_size, total_lines): + """Return "critical", "high", "medium" or "low" for an uncovered range. + + percentage = range_size * 100 / total_lines (exact, not rounded). + - percentage > 20 or range_size > 50 -> "critical" + - percentage > 10 or range_size > 20 -> "high" + - percentage > 5 or range_size > 10 -> "medium" + - otherwise "low". + Raises ValueError if total_lines < 1, range_size < 0 or range_size > total_lines. + """ + if total_lines < 1 or range_size < 0 or range_size > total_lines: + raise ValueError("invalid range") + percentage = range_size * 100 / total_lines + if percentage > 20 or range_size > 50: + return "critical" + if percentage > 10 or range_size > 20: + return "high" + if percentage > 5 or range_size > 10: + return "medium" + return "low" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 1], + [1, 5], + [1, 4], + [10, 100], + [11, 100], + [20, 200], + [21, 200], + [5, 100], + [6, 100], + [50, 1000], + [51, 1000], + [20, 1000], + [21, 1000], + [10, 1000], + [11, 1000], + [21, 100], + [5, 0], + [-1, 10], + [11, 10], + ] + while len(cases) < n: + total = rng.choice([rng.randint(1, 100), rng.randint(100, 2000)]) + cases.append([rng.randint(0, min(total, 80)), total]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/crop_to_aspect.py b/components/qemedia/upstream/qe_arena/corpus/crop_to_aspect.py new file mode 100644 index 0000000000000000000000000000000000000000..d74440e56aef26430b60512061a1b933510a7657 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/crop_to_aspect.py @@ -0,0 +1,56 @@ +"""Center-crop an image to a target aspect ratio and report which dimension was cut. Original.""" + +META = { + "entry": "crop_to_aspect", + "origin": "Original.", + "tags": ["aspect-ratio", "image", "crop"], + "domain": "media-content-production", +} + + +def crop_to_aspect(src_w, src_h, aspect_w, aspect_h): + """Center-crop a src_w x src_h image to the aspect_w:aspect_h shape; return [x, y, w, h, cut]. + + Let wide = src_w * aspect_h and tall = aspect_w * src_h; divisions round down. If + wide > tall the width is cut: w = src_h * aspect_w // aspect_h, h = src_h, cut "width". + If wide < tall the height is cut: w = src_w, h = src_w * aspect_h // aspect_w, cut + "height". Otherwise the whole image is kept, cut "none". The box is centered: + x = (src_w - w) // 2, y = (src_h - h) // 2. Raises ValueError if any argument is below 1. + """ + if min(src_w, src_h, aspect_w, aspect_h) < 1: + raise ValueError("sizes must be >= 1") + wide, tall = src_w * aspect_h, aspect_w * src_h + if wide > tall: + w, h, cut = src_h * aspect_w // aspect_h, src_h, "width" + elif wide < tall: + w, h, cut = src_w, src_w * aspect_h // aspect_w, "height" + else: + w, h, cut = src_w, src_h, "none" + return [(src_w - w) // 2, (src_h - h) // 2, w, h, cut] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [1920, 1080, 16, 9], + [1920, 1080, 4, 3], + [1920, 1080, 9, 16], + [4000, 3000, 16, 9], + [1080, 1920, 1, 1], + [1080, 1080, 1, 1], + [2560, 1080, 64, 27], + [1, 1, 1, 1], + [1, 3, 2, 1], + [3, 1, 1, 2], + [1001, 600, 5, 3], + [1000, 601, 5, 3], + [0, 1080, 16, 9], + [1920, 1080, 16, 0], + ] + aspects = [[16, 9], [4, 3], [1, 1], [9, 16], [21, 9], [2, 1], [3, 2], [4, 5]] + sizes = [1, 2, 3, 5, 7, 16, 100, 333, 720, 1080, 1280, 1920, 2160, 3840] + while len(cases) < n: + dims = [rng.choice(sizes) if rng.random() < 0.3 else rng.randint(1, 4000) for _ in range(2)] + aspect = rng.choice(aspects) if rng.random() < 0.7 else [rng.randint(1, 30), rng.randint(1, 30)] + cases.append(dims + aspect) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/debounce_switch.py b/components/qemedia/upstream/qe_arena/corpus/debounce_switch.py new file mode 100644 index 0000000000000000000000000000000000000000..fcea68c1987b3ee53547785bccf781ec8fbee438 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/debounce_switch.py @@ -0,0 +1,63 @@ +"""Debounce an analogue sensor into an on/off signal with hysteresis. Original.""" + +META = { + "entry": "debounce_switch", + "origin": "Original.", + "tags": ["sensor", "debounce", "hysteresis"], + "domain": "industrial-physical-systems", +} + + +def debounce_switch(samples, low, high, hold): + """Turn sensor samples into a debounced on/off state with hysteresis. + + The state starts off. While off, it turns on once `hold` consecutive samples are >= high; while + on, it turns off once `hold` consecutive samples are <= low. A sample that does not continue + the run resets the count to zero, and the count restarts at zero after every change. + Returns [final_state, changes]; changes lists [index, state] for every change, index being the + position of the sample that completed the run. + Raises ValueError if low >= high or hold < 1. + """ + if low >= high or hold < 1: + raise ValueError("invalid debounce settings") + state, run, changes = False, 0, [] + for index, sample in enumerate(samples): + crossing = sample <= low if state else sample >= high + run = run + 1 if crossing else 0 + if run >= hold: + state, run = not state, 0 + changes.append([index, state]) + return [state, changes] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], 10, 20, 1], + [[20], 10, 20, 1], + [[19], 10, 20, 1], + [[21, 9], 10, 20, 1], + [[21, 10], 10, 20, 1], + [[21, 11], 10, 20, 1], + [[25, 25], 10, 20, 2], + [[25, 15, 25], 10, 20, 2], + [[25, 25, 25, 5, 5], 10, 20, 2], + [[25, 25, 5, 25, 5, 5], 10, 20, 2], + [[25, 25, 25, 25], 10, 20, 3], + [[30, 0, 30, 0], 10, 20, 1], + [[15, 15, 15], 10, 20, 1], + [[5, 5, 5], 10, 20, 1], + [[25], 20, 20, 1], + [[25], 21, 20, 1], + [[25], 10, 20, 0], + [[0, 100, 100, 100, 0, 0, 0, 0], 40, 60, 3], + [[1], -5, 0, 0], + [[1], 0, 5, 0], + ] + while len(cases) < n: + low = rng.randint(0, 50) + high = low + rng.randint(1, 30) + samples = [rng.choice([rng.randint(low - 10, low), rng.randint(high, high + 10), rng.randint(low, high)]) + for _ in range(rng.randint(1, 12))] + cases.append([samples, low, high, rng.choice([1, 1, 2, 2, 3])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/decay_table.py b/components/qemedia/upstream/qe_arena/corpus/decay_table.py new file mode 100644 index 0000000000000000000000000000000000000000..1a372575295cca9ff568faf3a79fb82b7a9a32c7 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/decay_table.py @@ -0,0 +1,54 @@ +"""Tabulate a decaying activity in integer counts and find its half-life step. Original.""" + +META = { + "entry": "decay_table", + "origin": "Original.", + "tags": ["simulation", "decay", "integer-arithmetic"], + "domain": "natural-science", +} + + +def decay_table(activity, keep_num, keep_den, threshold, max_steps): + """Tabulate a first-order decay (radioactive source or drug dose), one level per time step. + + Each step multiplies the previous activity by keep_num / keep_den, the fraction retained per + step, and rounds down to an integer count. Steps continue while the current activity is + >= threshold and fewer than max_steps steps have been taken, so the first activity below + threshold is the last one listed and at most max_steps steps are listed. + Returns [levels, h]: levels[k] is the activity after k steps (levels[0] is the initial + activity), and h is the first step k >= 1 with 2 * levels[k] <= levels[0], or None if no + listed step reaches it. + Raises ValueError if activity < 0, threshold < 1, max_steps < 0, or unless + 0 <= keep_num < keep_den. + """ + if activity < 0 or threshold < 1 or max_steps < 0: + raise ValueError("bad table parameters") + if not 0 <= keep_num < keep_den: + raise ValueError("the retained fraction must be in [0, 1)") + levels = [activity] + half_life_step = None + current, step = activity, 0 + while current >= threshold and step < max_steps: + step += 1 + current = current * keep_num // keep_den + levels.append(current) + if half_life_step is None and 2 * current <= activity: + half_life_step = step + return [levels, half_life_step] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [1000, 1, 2, 100, 20], [1000, 9, 10, 1, 0], [1000, 9, 10, 1, 1], [1000, 9, 10, 500, 30], + [0, 1, 2, 1, 5], [-1, 1, 2, 1, 5], [100, 1, 2, 0, 5], [100, 1, 2, 1, -1], + [100, 0, 3, 1, 5], [100, 3, 3, 1, 5], [100, -1, 3, 1, 5], [100, 4, 3, 1, 5], + [64, 1, 2, 1, 10], [64, 1, 2, 64, 10], [64, 1, 2, 65, 10], [7, 2, 3, 2, 10], + [10, 1, 2, 5, 10], [11, 1, 2, 6, 10], [1, 1, 2, 1, 3], [500, 7, 8, 100, 4], + ] + while len(cases) < n: + den = rng.randint(2, 12) + steps = rng.randint(0, 5) if rng.random() < 0.6 else rng.randint(6, 25) + cases.append([rng.randint(0, rng.choice([200, 5000])), rng.randint(0, den - 1), den, + rng.randint(1, 120), steps]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/efficiency_reward.py b/components/qemedia/upstream/qe_arena/corpus/efficiency_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..e74f151ba563185ecb6819f4aca44bbeb111f64e --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/efficiency_reward.py @@ -0,0 +1,54 @@ +"""Reward an agent for finishing faster and cheaper than estimated. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/reward_calculator.py (MIT).""" + +META = { + "entry": "efficiency_reward", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/reward_calculator.py", + "tags": ["reward", "clamping"], + "domain": "software-engineering", +} + + +def efficiency_reward(actual_seconds, expected_seconds, actual_cost, estimated_cost): + """Return [time_reward, cost_reward], each rounded to 2 decimals. + + time_reward: 0.0 if actual_seconds <= 0; otherwise + (expected_seconds / actual_seconds - 1) * 50 clamped to [-50, 50]. + cost_reward: 0.0 if actual_cost <= 0; otherwise + (estimated_cost / actual_cost - 1) * 50 clamped to [-25, 50]. + The clamps are inclusive: values outside are replaced by the nearest bound. + Rounding is Python's round(x, 2): an exact half goes to the even digit, so + actual_seconds 16 with expected_seconds 3 gives -40.625 -> -40.62. + """ + if actual_seconds <= 0: + time_reward = 0.0 + else: + time_reward = (expected_seconds / actual_seconds - 1.0) * 50.0 + time_reward = max(-50.0, min(time_reward, 50.0)) + if actual_cost <= 0: + cost_reward = 0.0 + else: + cost_reward = (estimated_cost / actual_cost - 1.0) * 50.0 + cost_reward = max(-25.0, min(cost_reward, 50.0)) + return [round(time_reward, 2), round(cost_reward, 2)] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 10, 0, 10], + [-5, 10, -1, 10], + [10, 10, 10, 10], + [5, 10, 5, 10], + [4, 10, 4, 10], + [20, 10, 20, 10], + [30, 10, 30, 10], + [11, 10, 11, 10], + [8, 10, 8, 10], + [100, 1, 100, 1], + [1, 100, 1, 100], + [40, 30, 3, 2], + [7, 9, 15, 12], + ] + while len(cases) < n: + cases.append([rng.randint(0, 40), rng.randint(1, 40), rng.randint(0, 40), rng.randint(1, 40)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/expense_violations.py b/components/qemedia/upstream/qe_arena/corpus/expense_violations.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc37222a94c79c0fe3e9182209cf9e678595936 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/expense_violations.py @@ -0,0 +1,62 @@ +"""Check expense claim lines against a travel-and-expense policy. Original.""" + +META = { + "entry": "expense_violations", + "origin": "Original.", + "tags": ["expenses", "policy", "compliance"], + "domain": "office-white-collar", +} + + +def expense_violations(items): + """Return one day's expense-policy violations as [index, code] pairs. + + items are [category, cents, receipt] lines, checked in order; a line adds its codes + in this order: "OVER_CAP" if cents exceed the cap (meal 7500, hotel 25000, taxi 6000, + other 10000); "NO_RECEIPT" if cents >= 2500 and receipt is false; "DAILY_MEALS" for a + meal after which the day's meal total so far exceeds 10000. Raises ValueError at the + first line with an unknown category or cents <= 0. + """ + caps = {"meal": 7500, "hotel": 25000, "taxi": 6000, "other": 10000} + meals, found = 0, [] + for index, (category, cents, receipt) in enumerate(items): + if category not in caps: + raise ValueError("unknown category") + if cents <= 0: + raise ValueError("cents must be positive") + if cents > caps[category]: + found.append([index, "OVER_CAP"]) + if cents >= 2500 and not receipt: + found.append([index, "NO_RECEIPT"]) + if category == "meal": + meals += cents + if meals > 10000: + found.append([index, "DAILY_MEALS"]) + return found + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[]], + [[["meal", 7500, True]]], + [[["meal", 7501, True]]], + [[["hotel", 25000, True], ["hotel", 25001, True]]], + [[["taxi", 6000, True], ["taxi", 6001, True]]], + [[["other", 10000, True], ["other", 10001, True]]], + [[["taxi", 2499, False], ["taxi", 2500, False]]], + [[["meal", 1, False], ["meal", 9999, True]]], + [[["meal", 4000, True], ["meal", 6001, True]]], + [[["meal", 3000, False], ["hotel", 30000, False]]], + [[["taxi", 1200, True], ["meal", 0, True]]], + [[["taxi", 1200, True], ["bar", 900, True]]], + [[["meal", -5, True]]], + ] + categories = ["meal", "meal", "hotel", "taxi", "other"] + while len(cases) < n: + claim = [] + for _ in range(rng.choice([1, 2, 2, 3])): + cents = rng.choice([rng.randint(1, 4000), rng.randint(2000, 12000), rng.randint(5000, 32000)]) + claim.append([rng.choice(categories), cents, rng.random() < 0.7]) + cases.append([claim]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/find_stop.py b/components/qemedia/upstream/qe_arena/corpus/find_stop.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff34d45f547a543cd3ccb31684de689b2b79ba4 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/find_stop.py @@ -0,0 +1,66 @@ +"""Find where generated text is cut at the earliest stop sequence. Ported from Rust; adapted from ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs (MIT).""" + +PRE_FIX = "ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs" +META = { + "entry": "find_stop", + "origin": "ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs", + "tags": ["llm", "strings", "streaming"], + "domain": "software-engineering", + "real_faults": [ + {"id": "find_stop/first-listed", "kind": "first-match-vs-best", "origin": PRE_FIX, + "summary": "cuts at the first stop sequence in list order that occurs, not at the earliest offset", + "find": " if pos != -1 and (earliest is None or pos < earliest):\n earliest = pos\n", + "replace": " if pos != -1:\n return pos\n"}, + {"id": "find_stop/empty-matches", "kind": "missing-guard", "origin": PRE_FIX, + "summary": "an empty stop sequence matches at offset 0, so the whole output is cut", + "find": " if not stop:\n continue\n", "replace": ""}, + ], +} + + +def find_stop(text, stop_sequences): + """Return the offset in text where the earliest stop sequence starts, or None. + + Every non-empty string in stop_sequences is searched for in text. The result is the + smallest index at which any of them occurs (0 means the whole text is cut away). + The order of stop_sequences does not matter. Empty stop sequences never match. + Returns None when no non-empty stop sequence occurs, including for an empty list. + """ + earliest = None + for stop in stop_sequences: + if not stop: + continue + pos = text.find(stop) + if pos != -1 and (earliest is None or pos < earliest): + earliest = pos + return earliest + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["", []], + ["hello", []], + ["hello", ["lo", "l"]], + ["hello", ["", "lo", "l"]], + ["hey", ["", "lo", "l"]], + ["abc", [""]], + ["", ["a"]], + ["abcabc", ["c", "b"]], + ["abcabc", ["b", "c"]], + ["a\nUser: hi", ["User:", "\n"]], + ["donemore", ["", ""]], + ["xy", ["", ""]], + ["aaaa", ["aa", "a"]], + ] + alphabet = "abcab\n " + while len(cases) < n: + text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 16))) + stops = [] + for _ in range(rng.randint(0, 3)): + if rng.random() < 0.12: + stops.append("") + else: + stops.append("".join(rng.choice("abc\n") for _ in range(rng.randint(1, 3)))) + cases.append([text, stops]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/flakiness_pattern.py b/components/qemedia/upstream/qe_arena/corpus/flakiness_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..71b592d6dfa420ed5a97a5fb02a2c156a70f5c35 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/flakiness_pattern.py @@ -0,0 +1,68 @@ +"""Classify the flakiness pattern of repeated test runs. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/agents/flaky_test_hunter.py (MIT).""" + +META = { + "entry": "flakiness_pattern", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/agents/flaky_test_hunter.py", + "tags": ["flaky-tests", "sequences"], + "domain": "software-engineering", +} + + +def flakiness_pattern(results): + """Classify a sequence of test outcomes (True = passed) from repeated runs. + + Let n = len(results) and let the longest consecutive run of passes and of failures + be max_pass and max_fail. + - Empty list -> "UNKNOWN". + - max_pass == n -> "STABLE_PASS"; max_fail == n -> "STABLE_FAIL". + - max_pass or max_fail strictly greater than 70% of n (x * 10 > n * 7) + -> "INTERMITTENT". + - Otherwise -> "RANDOM". + """ + if not results: + return "UNKNOWN" + passes = fails = max_pass = max_fail = 0 + for passed in results: + if passed: + passes += 1 + fails = 0 + max_pass = max(max_pass, passes) + else: + fails += 1 + passes = 0 + max_fail = max(max_fail, fails) + total = len(results) + if max_pass == total: + return "STABLE_PASS" + if max_fail == total: + return "STABLE_FAIL" + if max_pass * 10 > total * 7 or max_fail * 10 > total * 7: + return "INTERMITTENT" + return "RANDOM" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + T, F = True, False + cases = [ + [[]], + [[T]], + [[F]], + [[T, T, T]], + [[F, F, F, F]], + [[T, F]], + [[T, T, T, F]], + [[F, T, T, T]], + [[T, T, T, T, T, T, T, F, F, F]], + [[T, T, T, T, T, T, T, T, F, F]], + [[F, F, F, F, F, F, F, F, T, T]], + [[F, F, F, F, F, F, F, T, T, T]], + [[T, F, T, F, T, F]], + [[T, T, F, F, T, T]], + [[F, T, F, F, F, F]], + [[T, F, F, F, F, F, F, F, F]], + ] + while len(cases) < n: + bias = rng.random() + cases.append([[rng.random() < bias for _ in range(rng.randint(1, 12))]]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/flaky_hunter_reward.py b/components/qemedia/upstream/qe_arena/corpus/flaky_hunter_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..ef866a6bf12fab28b45ed980580ea80b30993131 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/flaky_hunter_reward.py @@ -0,0 +1,53 @@ +"""Reward a flaky-test hunter with an F1 score minus miss penalties. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/reward_calculator.py (MIT).""" + +META = { + "entry": "flaky_hunter_reward", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/reward_calculator.py", + "tags": ["flaky-tests", "metrics", "reward"], + "domain": "software-engineering", +} + + +def flaky_hunter_reward(true_positives, false_positives, false_negatives): + """Reward for a flaky-test detector, rounded to 2 decimals. + + precision = tp / (tp + fp), or 0.0 when tp + fp == 0. + recall = tp / (tp + fn), or 0.0 when tp + fn == 0. + f1 = 2 * precision * recall / (precision + recall), or 0.0 when both are 0. + reward = f1 * 100 - 20 * false_negatives - 5 * false_positives (may be negative). + Raises ValueError if any count is negative. + """ + tp, fp, fn = true_positives, false_positives, false_negatives + if min(tp, fp, fn) < 0: + raise ValueError("counts must be non-negative") + precision = tp / (tp + fp) if tp + fp > 0 else 0.0 + recall = tp / (tp + fn) if tp + fn > 0 else 0.0 + if precision + recall > 0: + f1 = 2 * precision * recall / (precision + recall) + else: + f1 = 0.0 + reward = f1 * 100.0 + reward -= fn * 20.0 + reward -= fp * 5.0 + return round(reward, 2) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 0, 0], + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [3, 1, 0], + [3, 0, 1], + [2, 2, 2], + [5, 1, 2], + [1, 4, 0], + [10, 0, 3], + [-1, 0, 0], + [0, 0, -2], + ] + while len(cases) < n: + cases.append([rng.randint(0, 10), rng.randint(0, 4), rng.randint(0, 4)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/flaky_run_summary.py b/components/qemedia/upstream/qe_arena/corpus/flaky_run_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..f67dec6969636a0c58c07bfb79d9f98cc1faaf9c --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/flaky_run_summary.py @@ -0,0 +1,58 @@ +"""Summarize repeated runs of one test into a flakiness verdict. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/agents/flaky_test_hunter.py (MIT).""" + +META = { + "entry": "flaky_run_summary", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/agents/flaky_test_hunter.py", + "tags": ["flaky-tests", "statistics"], + "domain": "software-engineering", +} + + +def flaky_run_summary(results, iterations): + """Summarize `iterations` runs of one test; results lists the outcomes seen (True = passed). + + Runs missing from results (when len(results) < iterations) count as failures. + Returns {"passed", "failed", "is_flaky", "flakiness_pct", "pass_rate_pct"} where + passed = number of True values, failed = iterations - passed, + is_flaky = 0 < passed < iterations, + flakiness_pct = min(passed, failed) * 200 // iterations (integer division, 0..100), + pass_rate_pct = round(passed * 100 / iterations, 1). + Raises ValueError if iterations < 1 or len(results) > iterations. + """ + if iterations < 1: + raise ValueError("iterations must be positive") + if len(results) > iterations: + raise ValueError("more results than iterations") + passed = sum(1 for r in results if r) + failed = iterations - passed + return { + "passed": passed, + "failed": failed, + "is_flaky": 0 < passed < iterations, + "flakiness_pct": min(passed, failed) * 200 // iterations, + "pass_rate_pct": round(passed * 100 / iterations, 1), + } + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + T, F = True, False + cases = [ + [[], 1], + [[T], 1], + [[F], 1], + [[T, F], 2], + [[T, T], 2], + [[T], 2], + [[T, T, F], 3], + [[T, F, F], 3], + [[T, T, T, F, F, F, T], 7], + [[T, T, T], 7], + [[], 0], + [[T, T], 1], + [[T, F, T, T, T, T, T, T, T, T, T, T], 12], + ] + while len(cases) < n: + k = rng.randint(1, 12) + cases.append([[rng.random() < 0.6 for _ in range(rng.randint(0, k))], k]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/format_duration.py b/components/qemedia/upstream/qe_arena/corpus/format_duration.py new file mode 100644 index 0000000000000000000000000000000000000000..8b3a3f4090a2a856504088d6aba999da5c8701bc --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/format_duration.py @@ -0,0 +1,42 @@ +"""Format a duration in milliseconds for CLI output. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/cli/handlers/interfaces.ts (MIT).""" + +META = { + "entry": "format_duration", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/cli/handlers/interfaces.ts", + "tags": ["formatting", "durations", "thresholds"], + "domain": "software-engineering", +} + + +def one_decimal(ms, unit): + """ms / unit rounded half up to one decimal place, as text (exact integer arithmetic).""" + tenths = (ms * 10 + unit // 2) // unit + return str(tenths // 10) + "." + str(tenths % 10) + + +def format_duration(ms): + """Render a non-negative integer millisecond duration as a short string. + + ms < 1000 -> "ms"; ms < 60000 -> seconds + "s"; ms < 3600000 -> minutes + "m"; + otherwise hours + "h". Seconds, minutes and hours have exactly one decimal, rounded + half up from the exact value: 1500 -> "1.5s", 1450 -> "1.5s", 14350 -> "14.4s", + 59999 -> "60.0s", 90000 -> "1.5m". Raises ValueError if ms is negative. + """ + if ms < 0: + raise ValueError("duration must be non-negative") + if ms < 1000: + return str(ms) + "ms" + if ms < 60000: + return one_decimal(ms, 1000) + "s" + if ms < 3600000: + return one_decimal(ms, 60000) + "m" + return one_decimal(ms, 3600000) + "h" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [[0], [999], [1000], [1500], [59999], [60000], [90000], [3599999], + [3600000], [5400000], [86400000], [-1], [12345], [654321]] + while len(cases) < n: + cases.append([rng.choice([rng.randint(0, 2000), rng.randint(0, 120000), rng.randint(0, 20000000)])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/gguf_loader.py b/components/qemedia/upstream/qe_arena/corpus/gguf_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..c23b01affe3e73a47e434a0e8495564df4e30c97 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/gguf_loader.py @@ -0,0 +1,79 @@ +"""Choose the weight loader for a GGUF model file from its metadata. Ported from Rust; adapted from ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs (MIT).""" + +PRE_FIX = "ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs" +META = { + "entry": "gguf_loader", + "origin": "ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs", + "tags": ["llm", "dispatch", "validation"], + "domain": "software-engineering", + "real_faults": [ + {"id": "gguf_loader/no-split-check", "kind": "missing-guard", "origin": PRE_FIX, + "summary": "a split (multi-part) GGUF is not rejected", + "find": " if isinstance(parts, int) and parts > 1:\n raise ValueError(\"split GGUF files are not supported\")\n", + "replace": ""}, + {"id": "gguf_loader/qwen-rejected", "kind": "allowlist-too-narrow", "origin": PRE_FIX, + "summary": "only llama-family layouts load; qwen2 and qwen3 are rejected", + "find": " if name == \"qwen2\":\n return \"qwen2\"\n if name == \"qwen3\":\n return \"qwen3\"\n", + "replace": ""}, + {"id": "gguf_loader/substring-match", "kind": "allowlist-too-wide", "origin": PRE_FIX, + "summary": "any architecture containing llama or mistral loads as llama", + "find": " if name in (\"\", \"llama\", \"mistral\"):\n", + "replace": " if name in (\"\", \"llama\", \"mistral\") or \"llama\" in name or \"mistral\" in name:\n"}, + ], +} + + +def gguf_loader(metadata): + """Return the weight loader ("llama", "qwen2" or "qwen3") for a GGUF file's metadata. + + If metadata["split.count"] is an int greater than 1, the model is split into several + files, which is not supported: raise ValueError. The architecture is + metadata["general.architecture"]; a missing key or a non-string value counts as "". + It is matched case-insensitively and exactly: "", "llama" and "mistral" use the + "llama" loader, "qwen2" uses "qwen2" and "qwen3" uses "qwen3". Every other + architecture (for example "qwen35", "qwen3moe", "llama4", "codellama") raises + ValueError naming it. + """ + parts = metadata.get("split.count") + if isinstance(parts, int) and parts > 1: + raise ValueError("split GGUF files are not supported") + arch = metadata.get("general.architecture", "") + name = arch.lower() if isinstance(arch, str) else "" + if name in ("", "llama", "mistral"): + return "llama" + if name == "qwen2": + return "qwen2" + if name == "qwen3": + return "qwen3" + raise ValueError("GGUF architecture " + repr(arch) + " is not supported") + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + arches = ["", "llama", "LLaMA", "mistral", "Mistral", "qwen2", "Qwen2", "qwen3", "QWEN3", "qwen35", + "qwen3moe", "qwen3next", "llama4", "codellama", "mistral-nemo", "phi3", "gemma2"] + cases = [ + [{}], + [{"general.architecture": "LLaMA"}], + [{"general.architecture": "qwen2"}], + [{"general.architecture": "qwen3"}], + [{"general.architecture": "qwen35"}], + [{"general.architecture": "llama4"}], + [{"general.architecture": "qwen2", "split.count": 3}], + [{"split.count": 1}], + [{"split.count": 2}], + [{"general.architecture": 7}], + [{"general.architecture": "phi3", "split.count": 0}], + [{"general.architecture": "mistral", "split.count": 2}], + [{"general.architecture": "Qwen2"}], + [{"general.architecture": "codellama"}], + [{"general.architecture": "Mistral-Nemo"}], + ] + while len(cases) < n: + md = {} + if rng.random() < 0.9: + md["general.architecture"] = rng.choice(arches) + if rng.random() < 0.35: + md["split.count"] = rng.choice([0, 1, 1, 2, 3, 5]) + cases.append([md]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/gguf_special_ids.py b/components/qemedia/upstream/qe_arena/corpus/gguf_special_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a2619f609bc6bb5c52aea24a90d2dae8befb64 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/gguf_special_ids.py @@ -0,0 +1,85 @@ +"""Resolve a GGUF model's end-of-sequence id and the ids that stop generation. Ported from Rust; adapted from ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs; ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/candle_backend.rs (MIT).""" + +PRE_FIX = "ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs" +META = { + "entry": "gguf_special_ids", + "origin": "ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs; ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/candle_backend.rs", + "tags": ["llm", "tokenizer", "lookup"], + "domain": "software-engineering", + "real_faults": [ + {"id": "gguf_special_ids/eos-from-vocab-guess", "kind": "wrong-sibling-constant", "origin": PRE_FIX, + "summary": "the declared EOS id is ignored: a Qwen instruct model gets its end-of-text token, not end-of-turn", + "note": "pre-fix behaviour (EOS guessed from the vocabulary) expressed through the fixed function's interface", + "find": " eos = declared(\"eos\")\n if eos is None:\n eos = guess\n", + "replace": " eos = guess\n"}, + {"id": "gguf_special_ids/stop-is-only-eos", "kind": "missing-logic", "origin": PRE_FIX, + "summary": "generation stops only at the EOS id, never at end-of-turn tokens", + "note": "pre-fix behaviour (stop on the single EOS id) expressed through the fixed function's interface", + "find": " stop = [vocab[t] for t in STOPS if t in vocab]\n for name in (\"eos\", \"eot\", \"eom\"):\n" + " value = declared(name)\n if value is not None and value not in stop:\n" + " stop.append(value)\n", + "replace": " stop = [] if eos is None else [eos]\n"}, + ], +} + + +def gguf_special_ids(metadata, vocab): + """Return {"eos": id or None, "stop": [ids]} for a GGUF model. + + vocab maps token text to id. A declared id metadata["tokenizer.ggml._token_id"] + (x is eos, eot or eom) counts only if it is an int (not a bool) with 0 <= id < len(vocab). + eos is the declared eos id; without one, the id of the first of "", + "", "", "" present in vocab; else None. + stop lists the vocab ids of "", "", "", + "", "" (in that order, when present), then the declared eos, + eot and eom ids, skipping any id already in the list. + """ + def declared(x): + value = metadata.get("tokenizer.ggml." + x + "_token_id") + ok = isinstance(value, int) and not isinstance(value, bool) and 0 <= value < len(vocab) + return value if ok else None + + candidates = ["", "", "", ""] + guess = next((vocab[t] for t in candidates if t in vocab), None) + STOPS = ["", "", "", "", ""] + eos = declared("eos") + if eos is None: + eos = guess + stop = [vocab[t] for t in STOPS if t in vocab] + for name in ("eos", "eot", "eom"): + value = declared(name) + if value is not None and value not in stop: + stop.append(value) + return {"eos": eos, "stop": stop} + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + qwen = {"a": 0, "b": 1, "": 2, "": 3, "": 4} + llama = {"": 0, "": 1, "a": 2, "b": 3} + llama3 = {"": 0, "": 1, "": 2, "a": 3, "b": 4, "c": 5} + key = "tokenizer.ggml.{}_token_id".format + cases = [ + [{}, {}], + [{}, qwen], + [{key("eos"): 4}, qwen], + [{key("eos"): 2}, qwen], + [{key("eos"): 5, key("eot"): 6, key("eom"): 99}, {"a": 0, "b": 1, "c": 2, "d": 3, "": 4, + "e": 5, "f": 6, "g": 7}], + [{key("eos"): 1}, llama], + [{key("eos"): 4}, llama], + [{key("eos"): -1}, llama], + [{key("eos"): True}, llama], + [{key("eos"): "1"}, llama3], + [{key("eot"): 2, key("eom"): 2}, llama3], + [{key("eos"): 5}, llama3], + ] + vocabs = [qwen, llama, llama3, {"x": 0, "y": 1, "z": 2}] + while len(cases) < n: + vocab = rng.choice(vocabs) + md = {} + for x in ("eos", "eot", "eom"): + if rng.random() < 0.5: + md[key(x)] = rng.choice([rng.randint(-1, len(vocab) + 1), rng.randrange(len(vocab))]) + cases.append([md, vocab]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/glob_match.py b/components/qemedia/upstream/qe_arena/corpus/glob_match.py new file mode 100644 index 0000000000000000000000000000000000000000..851c1d8891d9c975cfef77564b7d2dade983f94e --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/glob_match.py @@ -0,0 +1,82 @@ +"""Match a file path against a glob with *, ** and ? wildcards. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/io/file-reader.ts (MIT).""" + +import re + +META = { + "entry": "glob_match", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/io/file-reader.ts", + "tags": ["glob", "parsing", "paths"], + "domain": "software-engineering", +} + + +def glob_to_regex(pattern): + """Translate a glob into a regular expression body (without anchors).""" + regex = "" + i = 0 + while i < len(pattern): + char = pattern[i] + if pattern[i:i + 2] == "**": + if pattern[i + 2:i + 3] == "/": + regex += "(?:.*/)?" + i += 3 + else: + regex += ".*" + i += 2 + elif char == "*": + regex += "[^/]*" + i += 1 + elif char == "?": + regex += "[^/]" + i += 1 + elif char in ".+^${}()|[]\\": + regex += "\\" + char + i += 1 + else: + regex += char + i += 1 + return regex + + +def glob_match(pattern, path): + """Return True if the whole path matches the glob pattern. + + "**/" anywhere in the pattern matches zero or more whole directories (nothing, or + any text ending in "/"), so "a/**/b" matches "a/b"; "**" elsewhere matches anything, + including "/"; "*" matches any run of characters except "/"; "?" matches exactly + one character except "/". Every other character matches itself literally. + """ + return re.fullmatch(glob_to_regex(pattern), path, re.DOTALL) is not None + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["*.py", "a.py"], + ["*.py", "src/a.py"], + ["**/*.py", "a.py"], + ["**/*.py", "src/pkg/a.py"], + ["src/**", "src/a/b.ts"], + ["src/**", "src"], + ["src/**/test_*.py", "src/test_a.py"], + ["src/**/test_*.py", "src/x/y/test_a.py"], + ["a?c", "abc"], + ["a?c", "a/c"], + ["a?c", "ac"], + ["a.b", "axb"], + ["a.b", "a.b"], + ["(x)+[y]", "(x)+[y]"], + ["*", ""], + ["**", "a/b/c"], + ["*/*", "a/b"], + ["*/*", "a/b/c"], + ["$x^", "$x^"], + ["a**b", "a/x/b"], + ] + parts = ["src", "tests", "*", "**", "a", "b.py", "?", "c.ts", "*.py"] + names = ["src", "tests", "a", "bb", "b.py", "c.ts", "x.py"] + while len(cases) < n: + pattern = "/".join(rng.choice(parts) for _ in range(rng.randint(1, 3))) + path = "/".join(rng.choice(names) for _ in range(rng.randint(1, 3))) + cases.append([pattern, path]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/income_tax.py b/components/qemedia/upstream/qe_arena/corpus/income_tax.py new file mode 100644 index 0000000000000000000000000000000000000000..b97681ff6ea30b57268632e744caea7fb1bda3e8 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/income_tax.py @@ -0,0 +1,73 @@ +"""Progressive income tax over marginal bands in integer cents. Original.""" + +META = { + "entry": "income_tax", + "origin": "Original.", + "tags": ["tax", "brackets", "money"], + "domain": "finance-economics", +} + + +def income_tax(income_cents, allowance_cents, bands, top_rate_bp): + """Compute progressive income tax in integer cents. + + taxable = max(0, income_cents - allowance_cents). bands lists [upper_cents, rate_bp] with + increasing uppers. A band runs from the previous upper (0 for the first) to its own, and + taxable income inside it is taxed at rate_bp / 10000; income above the last upper (all of it + when bands is empty) is taxed at top_rate_bp / 10000. The tax is the exact sum, rounded half + up to a cent once at the end. + Returns [tax_cents, marginal_rate_bp], the rate of the band holding the last cent of taxable + (0 when taxable is 0). + Raises ValueError if income_cents or allowance_cents is negative or any rate is outside 0..10000. + """ + if income_cents < 0 or allowance_cents < 0: + raise ValueError + taxable = max(0, income_cents - allowance_cents) + lower, owed, marginal = 0, 0, 0 + for upper, rate in bands + [[taxable, top_rate_bp]]: + if rate < 0 or rate > 10000: + raise ValueError + top = min(taxable, upper) + if top > lower: + owed += (top - lower) * rate + marginal = rate + lower = max(lower, upper) + return [(owed + 5000) // 10000, marginal] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + uk = [[3770000, 2000], [12514000, 4000]] + cases = [ + [0, 0, uk, 4500], + [1257000, 1257000, uk, 4500], + [1257100, 1257000, uk, 4500], + [5027000, 1257000, uk, 4500], + [5027100, 1257000, uk, 4500], + [13771000, 1257000, uk, 4500], + [13771100, 1257000, uk, 4500], + [20000000, 0, uk, 4500], + [1000, 2000, uk, 4500], + [3, 0, [], 1500], + [1, 0, [], 5000], + [10, 0, [[5, 0]], 10000], + [5, 0, [[5, 0]], 10000], + [6, 0, [[5, 1000]], 3000], + [-1, 0, uk, 4500], + [100, -1, uk, 4500], + [100, 0, [[50, -1]], 2000], + [100, 0, [[50, 1000]], 10001], + [100, 0, [[50, 1000]], 10000], + [0, 0, [[50, -1]], 1000], + [0, 0, [[50, 1000]], 10001], + [40, 0, [[50, 1000]], 10001], + [4999, 0, [], 1], + ] + while len(cases) < n: + scale = rng.choice([1, 1, 1000]) + uppers = [u * scale for u in sorted(rng.sample(range(1, 20000), rng.randint(0, 3)))] + rates = sorted(rng.randint(0, 6000) for _ in range(len(uppers) + 1)) + bands = [[u, r] for u, r in zip(uppers, rates)] + income = rng.choice([rng.randint(0, 25000) * scale, rng.choice(uppers + [0]) + rng.choice([-1, 0, 1, 37])]) + cases.append([max(0, income), rng.choice([0, 0, 1257 * scale, rng.randint(0, 2000) * scale]), bands, rates[-1]]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/integer_edge_values.py b/components/qemedia/upstream/qe_arena/corpus/integer_edge_values.py new file mode 100644 index 0000000000000000000000000000000000000000..0e8fc6be6c5841b0b6aeb027d3958c5701c89c18 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/integer_edge_values.py @@ -0,0 +1,61 @@ +"""Choose integer test values for a bounded schema field. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/data_mocking_agent.py (MIT).""" + +META = { + "entry": "integer_edge_values", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/data_mocking_agent.py", + "tags": ["test-data", "boundary-values"], + "domain": "software-engineering", +} + + +def integer_edge_values(minimum, maximum, strategy): + """Return the integers a test-data generator should try for a bounded field. + + minimum defaults to 0 and maximum to 1000000 when None. + - strategy "boundary": [minimum, maximum] (both, even when equal). + - strategy "edge_cases": minimum, minimum + 1, maximum - 1, maximum in that order, + keeping only values inside [minimum, maximum] and skipping duplicates. + - any other strategy: [(minimum + maximum) // 2]. + Raises ValueError if minimum > maximum. + """ + if minimum is None: + minimum = 0 + if maximum is None: + maximum = 1000000 + if minimum > maximum: + raise ValueError("minimum exceeds maximum") + if strategy == "boundary": + return [minimum, maximum] + if strategy == "edge_cases": + values = [] + for value in (minimum, minimum + 1, maximum - 1, maximum): + if minimum <= value <= maximum and value not in values: + values.append(value) + return values + return [(minimum + maximum) // 2] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [None, None, "edge_cases"], + [None, None, "boundary"], + [None, None, "random"], + [5, 5, "edge_cases"], + [5, 5, "boundary"], + [5, 6, "edge_cases"], + [5, 7, "edge_cases"], + [5, 8, "edge_cases"], + [-3, None, "edge_cases"], + [None, -1, "edge_cases"], + [None, 1, "edge_cases"], + [6, 5, "boundary"], + [-7, -2, "mid"], + [-7, -4, "mid"], + [1, 2, "mid"], + ] + while len(cases) < n: + low = rng.choice([None, rng.randint(-20, 20)]) + high = rng.choice([None, rng.randint(-20, 30)]) + cases.append([low, high, rng.choice(["edge_cases", "boundary", "random"])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/ip_allowlist_match.py b/components/qemedia/upstream/qe_arena/corpus/ip_allowlist_match.py new file mode 100644 index 0000000000000000000000000000000000000000..68bcbd6d2cacf9f5db44c073e6a2a411dd36a478 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/ip_allowlist_match.py @@ -0,0 +1,65 @@ +"""Match an IPv4 address against a CIDR allowlist. Original.""" + +META = { + "entry": "ip_allowlist_match", + "origin": "Original.", + "tags": ["security", "network", "access-control", "parsing"], + "domain": "cybersecurity", +} + + +def parse_ipv4(text): + """Return a dotted-quad IPv4 address as an int.""" + parts = text.split(".") + if len(parts) != 4: + raise ValueError("bad address") + for part in parts: + if not part.isdigit() or (len(part) > 1 and part[0] == "0") or int(part) > 255: + raise ValueError("bad octet") + return sum(int(part) << (24 - 8 * i) for i, part in enumerate(parts)) + + +def ip_allowlist_match(ip, allowlist): + """Return the first allowlist entry whose network contains ip, or None. + + An address is four "."-separated decimal numbers 0..255 with no sign or leading zero ("0" is + fine, "01" is not). An entry is "a.b.c.d/len" with 0 <= len <= 32, or a bare address (/32); + host bits are ignored ("10.1.2.3/8" is 10.0.0.0/8). Entries after the first match are not + checked. Raises ValueError if ip or a checked entry is malformed. + """ + address = parse_ipv4(ip) + for entry in allowlist: + network, slash, length = entry.partition("/") + if slash and (not length.isdigit() or int(length) > 32): + raise ValueError("bad prefix") + bits = int(length) if slash else 32 + mask = 0xFFFFFFFF ^ (0xFFFFFFFF >> bits) + if (address & mask) == (parse_ipv4(network) & mask): + return entry + return None + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["10.1.2.3", ["10.0.0.0/8"]], ["11.0.0.1", ["10.0.0.0/8"]], ["192.168.1.7", ["192.168.1.7"]], + ["192.168.1.8", ["192.168.1.7"]], ["192.168.1.8", ["192.168.1.7/31"]], + ["192.168.1.6", ["192.168.1.7/31"]], ["8.8.8.8", ["0.0.0.0/0"]], ["8.8.8.8", ["0.0.0.0/1"]], + ["200.1.1.1", ["0.0.0.0/1"]], ["10.9.9.9", ["10.1.2.3/8"]], ["172.16.5.4", ["172.16.0.0/12"]], + ["172.32.0.1", ["172.16.0.0/12"]], ["1.2.3.4", ["9.9.9.9", "1.2.3.0/24", "1.2.0.0/16"]], + ["1.2.3.4", ["1.2.3.0/24", "garbage"]], ["1.2.3.4", ["garbage", "1.2.3.0/24"]], + ["1.2.3.4", ["1.2.3.0/33"]], ["1.2.3.4", ["1.2.3.0/32"]], ["1.2.3.4", ["1.2.3.4/"]], + ["1.2.3.4", ["1.2.3.0/x"]], ["1.2.3.4", ["1.2.3.0/+24"]], ["1.2.3.4", ["1.2.3.0/ 24"]], + ["192.168.1.6", ["192.168.1.7"]], ["1.2.3.4", ["1.2.3.5/32"]], ["1.2.3.4", ["9.2.3.4/32"]], ["1.2.3.4", []], ["01.2.3.4", ["0.0.0.0/0"]], + ["0.0.0.0", ["0.0.0.0/32"]], ["255.255.255.255", ["255.255.255.254/31"]], + ["256.1.1.1", ["0.0.0.0/0"]], ["1.2.3", ["0.0.0.0/0"]], ["1.2.3.4.5", ["0.0.0.0/0"]], + ["1.2.-3.4", ["0.0.0.0/0"]], ["128.0.0.0", ["127.255.255.255/1"]], + ] + while len(cases) < n: + ip = ".".join(str(rng.choice([0, 1, 10, 127, 128, 192, 255, rng.randint(0, 255)])) for _ in range(4)) + allow = [] + for _ in range(rng.randint(1, 4)): + net = ".".join(str(rng.choice([0, 10, 128, 192, rng.randint(0, 255)])) for _ in range(4)) + allow.append(net + "/" + str(rng.randint(0, 32)) if rng.random() < 0.8 else ip) + cases.append([ip, allow]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/is_collection_endpoint.py b/components/qemedia/upstream/qe_arena/corpus/is_collection_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..0436e1be12727dcf8e0d2d66404d7e778efee442 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/is_collection_endpoint.py @@ -0,0 +1,56 @@ +"""Classify an API endpoint as a list/search collection endpoint. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/functional_negative_agent.py (MIT).""" + +META = { + "entry": "is_collection_endpoint", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/functional_negative_agent.py", + "tags": ["api", "classification", "strings"], + "domain": "software-engineering", +} + + +def is_collection_endpoint(path, method, query_param_count): + """Return True if an endpoint looks like a collection (list/search) endpoint. + + path and method are compared case-insensitively. True if any of these holds: + - the method is GET and the path contains none of "{id}", "{uuid}", "/{", "/:"; + - the path contains "search"; + - the path contains "filter"; + - query_param_count is greater than 2. + Otherwise False. + """ + path = path.lower() + method = method.lower() + indicators = [ + method == "get" and not any(marker in path for marker in ("{id}", "{uuid}", "/{", "/:")), + "search" in path, + "filter" in path, + query_param_count > 2, + ] + return any(indicators) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["/users", "GET", 0], + ["/users", "get", 0], + ["/users/{id}", "GET", 0], + ["/users/{userId}", "GET", 0], + ["/users/:id", "GET", 0], + ["/x{uuid}", "GET", 0], + ["/x{id}", "GET", 0], + ["/users", "POST", 0], + ["/users", "POST", 2], + ["/users", "POST", 3], + ["/users/{id}", "GET", 3], + ["/users/{id}/Search", "POST", 0], + ["/orders/{id}/FILTER", "DELETE", 1], + ["/orders/{id}/research", "PUT", 0], + ["/filters/{id}", "PATCH", 2], + ["/items/{id}", "patch", 2], + ] + segments = ["users", "orders", "search", "filter", "{id}", "{uuid}", ":id", "{slug}", "items", "Report"] + while len(cases) < n: + path = "/" + "/".join(rng.choice(segments) for _ in range(rng.randint(1, 3))) + cases.append([path, rng.choice(["GET", "get", "POST", "PUT", "DELETE"]), rng.randint(0, 4)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/latency_percentiles.py b/components/qemedia/upstream/qe_arena/corpus/latency_percentiles.py new file mode 100644 index 0000000000000000000000000000000000000000..235df4a96b5e38174b2e81acbb813170bd340d77 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/latency_percentiles.py @@ -0,0 +1,56 @@ +"""Summarize benchmark latencies with interpolated percentiles. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:scripts/comprehensive_benchmark.py (MIT).""" + +META = { + "entry": "latency_percentiles", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:scripts/comprehensive_benchmark.py", + "tags": ["performance", "statistics"], + "domain": "software-engineering", +} + + +def percentile(sorted_values, p): + """Linear-interpolated percentile p (0-100) of a non-empty ascending list.""" + n = len(sorted_values) + k = (n - 1) * p / 100 + f = int(k) + c = f + 1 if f < n - 1 else f + if f == c: + return sorted_values[f] + return sorted_values[f] + (sorted_values[c] - sorted_values[f]) * (k - f) + + +def latency_percentiles(times): + """Summarize response times (integer ms) as a dict with keys min, max, p25, p50, p75, p95. + + The values are sorted ascending first. Percentile p uses linear interpolation on the + sorted list v of length n: k = (n - 1) * p / 100, f = int(k), c = f + 1 unless f is + the last index (then c = f); result = v[f] + (v[c] - v[f]) * (k - f). + Percentiles are floats rounded to 2 decimals; min and max are returned as-is (ints). + An empty list returns min and max 0 and every percentile 0.0. + """ + if not times: + return {"min": 0, "max": 0, "p25": 0.0, "p50": 0.0, "p75": 0.0, "p95": 0.0} + ordered = sorted(times) + result = {"min": ordered[0], "max": ordered[-1]} + for p in (25, 50, 75, 95): + result["p" + str(p)] = round(float(percentile(ordered, p)), 2) + return result + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[]], + [[7]], + [[10, 20]], + [[30, 10, 20]], + [[1, 2, 3, 4]], + [[5, 1, 4, 2, 3]], + [[100, 100, 100, 100, 100, 100]], + [[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]], + [[3, 9, 27, 81, 243, 729, 2187]], + [[12, 15, 11, 19, 400, 13, 14, 16, 18, 17, 20, 10]], + ] + while len(cases) < n: + cases.append([[rng.randint(1, 500) for _ in range(rng.randint(1, 12))]]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/login_rate_limit.py b/components/qemedia/upstream/qe_arena/corpus/login_rate_limit.py new file mode 100644 index 0000000000000000000000000000000000000000..610f2a44d23e7bf87655808170f8009919b2841b --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/login_rate_limit.py @@ -0,0 +1,57 @@ +"""Sliding-window login rate limiter with lockout. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/auth_service/main.py (MIT).""" + +META = { + "entry": "login_rate_limit", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/auth_service/main.py", + "tags": ["security", "rate-limit", "time-window"], + "domain": "software-engineering", +} + + +def login_rate_limit(request_times, lockout_until, now, limit, lockout_seconds): + """Decide whether a login attempt at time `now` is rate limited. + + All times are integer seconds. Returns [limited, retry_after]: + - If lockout_until is not None and now < lockout_until: [True, lockout_until - now]. + - Otherwise only previous requests with now - t < 60 count (a request exactly + 60 seconds old no longer counts). If the number of counted requests is + >= limit, a new lockout starts: [True, lockout_seconds]. + - Otherwise [False, None]. + Raises ValueError if limit < 1. + """ + if limit < 1: + raise ValueError("limit must be at least 1") + if lockout_until is not None and now < lockout_until: + return [True, lockout_until - now] + recent = [t for t in request_times if now - t < 60] + if len(recent) >= limit: + return [True, lockout_seconds] + return [False, None] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], None, 100, 1, 300], + [[], 150, 100, 5, 300], + [[], 100, 100, 5, 300], + [[], 99, 100, 5, 300], + [[99], 101, 100, 1, 300], + [[40], None, 100, 1, 300], + [[41], None, 100, 1, 300], + [[41, 42], None, 100, 3, 300], + [[41, 42, 43], None, 100, 3, 300], + [[40, 41, 42], None, 100, 3, 300], + [[10, 20, 95, 96], None, 100, 2, 120], + [[10, 20, 95, 96], None, 100, 3, 120], + [[1, 2, 3], 50, 100, 2, 60], + [[1, 2, 3], None, 100, 0, 60], + [[100, 100], None, 100, 2, 30], + [[], None, 0, 1, 10], + ] + while len(cases) < n: + now = rng.randint(60, 200) + times = sorted(rng.randint(now - 90, now) for _ in range(rng.randint(0, 8))) + lockout = rng.choice([None, None, rng.randint(now - 20, now + 20)]) + cases.append([times, lockout, now, rng.randint(1, 6), rng.choice([30, 60, 300])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/loudness_gain.py b/components/qemedia/upstream/qe_arena/corpus/loudness_gain.py new file mode 100644 index 0000000000000000000000000000000000000000..ca966cce9825d7e923dd0b503e116b4a379e6765 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/loudness_gain.py @@ -0,0 +1,59 @@ +"""Compute a loudness-normalisation gain in centi-dB, capped by boost and true-peak limits. Original.""" + +META = { + "entry": "loudness_gain", + "origin": "Original.", + "tags": ["audio", "loudness", "normalization"], + "domain": "media-content-production", +} + + +def loudness_gain(measured_cdb, peak_cdb, target_cdb, ceiling_cdb, max_boost_cdb): + """Loudness-normalisation gain in integer centi-dB (1 dB = 100); return [gain, limited_by]. + + measured_cdb is integrated loudness (LUFS * 100), peak_cdb the true peak (dBTP * 100). + Below -7000 measured is silence: [0, "silence"]. Otherwise gain = target_cdb - + measured_cdb ("target"); if gain > max_boost_cdb it becomes max_boost_cdb ("max_boost"); + then if peak_cdb + gain > ceiling_cdb it becomes ceiling_cdb - peak_cdb ("peak"), which + may be a cut. Raises ValueError first if max_boost_cdb < 0 or ceiling_cdb > 0. + """ + if max_boost_cdb < 0 or ceiling_cdb > 0: + raise ValueError("need max_boost_cdb >= 0 and ceiling_cdb <= 0") + if measured_cdb < -7000: + gain, limited_by = 0, "silence" + else: + gain, limited_by = target_cdb - measured_cdb, "target" + if gain > max_boost_cdb: + gain, limited_by = max_boost_cdb, "max_boost" + if peak_cdb + gain > ceiling_cdb: + gain, limited_by = ceiling_cdb - peak_cdb, "peak" + return [gain, limited_by] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [-2300, -600, -1400, -100, 1200], + [-1000, -50, -1400, -100, 1200], + [-2600, -300, -1400, -100, 1200], + [-2600, -1300, -1400, -100, 1200], + [-2600, -1299, -1400, -100, 1200], + [-2400, -1100, -1400, -100, 1000], + [-2400, -1101, -1400, -100, 999], + [-7000, -4000, -2300, -100, 600], + [-7001, -4000, -2300, -100, 600], + [-900, 150, -1400, 0, 0], + [-1400, -100, -1400, -100, 0], + [-2000, -500, -1600, 0, 1200], + [-2000, -500, -1600, -100, -1], + [-2000, -500, -1600, 1, 1200], + [-9000, 200, -1400, 5, 100], + ] + targets = [-1400, -1600, -2300, -2400] + while len(cases) < n: + measured = rng.choice([rng.randint(-3500, -400), rng.randint(-8000, -6000)]) + peak = rng.randint(measured + 300, max(measured + 400, 300)) + ceiling = rng.choice([-100, -100, -200, -150, 0, 0, -100, 100]) # 100 is an invalid ceiling + boost = rng.choice([0, 300, 600, 1200, rng.randint(0, 2000), rng.randint(0, 2000), rng.randint(0, 2000), -300]) + cases.append([measured, peak, rng.choice(targets), ceiling, boost]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/mail_merge.py b/components/qemedia/upstream/qe_arena/corpus/mail_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1e0afd5cc29241117b95df17583dc6b502146c --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/mail_merge.py @@ -0,0 +1,66 @@ +"""Fill a mail-merge template from one record, applying defaults and reporting missing fields. Original.""" + +META = { + "entry": "mail_merge", + "origin": "Original.", + "tags": ["templating", "mail-merge", "text"], + "domain": "office-white-collar", +} + + +def mail_merge(template, record): + """Fill the {{field}} placeholders of template from record; return [text, missing]. + + Each "{{" opens a placeholder closed by the next "}}", which must come before any later + "{{"; other text is copied. A body is "field" or "field|default"; the field is stripped + of spaces and must be 1 to 32 characters. A missing, None or "" value is replaced by the + default ("" without "|"), and without "|" the field is also missing. Other values go in + as str(value). missing is sorted and distinct. Raises ValueError for an unclosed + placeholder or a bad field length. + """ + pieces = template.split("{{") + out, missing = [pieces[0]], set() + for piece in pieces[1:]: + body, closed, rest = piece.partition("}}") + if not closed: + raise ValueError("unclosed placeholder") + field, bar, default = body.partition("|") + field = field.strip(" ") + if len(field) < 1 or len(field) > 32: + raise ValueError("field name must be 1 to 32 characters") + value = record.get(field) + if value is None or value == "": + if not bar: + missing.add(field) + value = default + out.append(str(value) + rest) + return ["".join(out), sorted(missing)] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["Dear {{name}},", {"name": "Ana"}], + ["Dear {{ title |Sir}},", {"title": None}], + ["Ref {{id}} at {{city|HQ}}", {"id": 42, "city": ""}], + ["{{city}}{{title}}!", {"city": "", "title": None}], + ["no fields", {}], + ["", {"a": 1}], + ["{{a}}{{a}}}}", {"a": "x"}], + ["{{ a|}} {{zip}} {{zip}}", {}], + ["a {b} {{b}", {"b": 2}], + ["{{ |x}} y", {}], + ["{{}} {{a}}", {}], + ["{{ abcdefghijklmnopqrstuvwxyz012345 }}!", {"abcdefghijklmnopqrstuvwxyz012345": "ok"}], + ["{{abcdefghijklmnopqrstuvwxyz0123456}}", {}], + ["{{a|{{b}}", {"a": "A"}], + ["{{a}} {{b|B}} {{c}}", {"a": 0, "b": "", "c": "C"}], + ] + words = ["Hi", "Re:", "-", ",", "{", "}"] + fields = ["name", "zip", "id", " name ", "zip|00", "id|", "city|HQ"] + records = [{}, {"name": "Ana"}, {"name": "", "id": 7}, {"zip": None, "id": 0}, {"city": "Rome"}] + while len(cases) < n: + parts = [rng.choice(words) if rng.random() < 0.4 else "{{" + rng.choice(fields) + "}}" + for _ in range(rng.randint(1, 3))] + cases.append([rng.choice([" ", ""]).join(parts), rng.choice(records)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/maintainability_index.py b/components/qemedia/upstream/qe_arena/corpus/maintainability_index.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ecc27aaecb19ec98bbb69dbe979ebc337f53d5 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/maintainability_index.py @@ -0,0 +1,50 @@ +"""Compute a simplified maintainability index for a module. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:docs/reports/analyze_complexity.py (MIT).""" + +import math + +META = { + "entry": "maintainability_index", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:docs/reports/analyze_complexity.py", + "tags": ["code-metrics", "math"], + "domain": "software-engineering", +} + + +def maintainability_index(lines, avg_complexity, halstead_volume): + """Return a simplified maintainability index in [0, 100], rounded to 2 decimals. + + If lines == 0 or avg_complexity == 0, returns 100.0. Otherwise + mi = 171 - 5.2 * ln(halstead_volume + 1) - 0.23 * avg_complexity - 16.2 * ln(lines) + clamped to [0.0, 100.0] and rounded to 2 decimals (ln is the natural logarithm). + The result is always a float. + Raises ValueError if any argument is negative. + """ + if lines < 0 or avg_complexity < 0 or halstead_volume < 0: + raise ValueError("metrics must be non-negative") + if lines == 0 or avg_complexity == 0: + return 100.0 + mi = 171 - 5.2 * math.log(halstead_volume + 1) - 0.23 * avg_complexity - 16.2 * math.log(lines) + mi = max(0.0, min(100.0, mi)) + return round(mi, 2) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 5, 100], + [10, 0, 100], + [0, 0, 0], + [1, 1, 0], + [10, 2, 50], + [100, 10, 1000], + [500, 20, 5000], + [5000, 80, 100000], + [50, 3, 0], + [3, 1, 2], + [5000, 0, 100000], + [-1, 1, 1], + [10, 1, -1], + ] + while len(cases) < n: + cases.append([rng.randint(0, 3000), rng.randint(0, 40), rng.randint(0, 50000)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/maintenance_status.py b/components/qemedia/upstream/qe_arena/corpus/maintenance_status.py new file mode 100644 index 0000000000000000000000000000000000000000..01387a73c0736bfd67161850f83291f9c6a7aabc --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/maintenance_status.py @@ -0,0 +1,75 @@ +"""Decide a machine's maintenance status from hours, starts and calendar days. Original.""" + +META = { + "entry": "maintenance_status", + "origin": "Original.", + "tags": ["maintenance", "scheduling", "asset-management"], + "domain": "industrial-physical-systems", +} + + +def maintenance_status(hours, starts, days, limits): + """Decide whether a machine is due for service from its usage since the last service. + + hours, starts and days are counters since the last service; limits is [hour_limit, + start_limit, day_limit]. Each counter's usage is counter * 1000 // its limit (per mille). + The driver is the counter with the highest usage, a tie going to the earlier of "hours", + "starts", "days". With the driver's usage u, status is "overdue" if u >= 1100, "due" if + u >= 1000, "soon" if u >= 900, else "ok". + Returns [status, driver, u, remaining], remaining = the driver's limit minus its counter, + or 0 when that is negative. + Raises ValueError if a counter is negative, limits does not have 3 items, or a limit is below 1. + """ + counters = [hours, starts, days] + if min(counters) < 0 or len(limits) != 3 or min(limits) < 1: + raise ValueError + shares = [count * 1000 // limit for count, limit in zip(counters, limits)] + usage = max(shares) + index = shares.index(usage) + if usage >= 1100: + status = "overdue" + elif usage >= 1000: + status = "due" + elif usage >= 900: + status = "soon" + else: + status = "ok" + driver = ("hours", "starts", "days")[index] + return [status, driver, usage, max(0, limits[index] - counters[index])] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + base = [1000, 200, 365] + cases = [ + [0, 0, 0, base], + [899, 0, 0, base], + [900, 0, 0, base], + [999, 0, 0, base], + [1000, 0, 0, base], + [1099, 0, 0, base], + [1100, 0, 0, base], + [500, 100, 0, base], + [500, 101, 0, base], + [500, 100, 183, base], + [100, 50, 400, base], + [2000, 10, 10, base], + [1, 1, 1, [1, 1, 1]], + [950, 190, 0, base], + [950, 191, 0, base], + [0, 0, 0, [1000, 200]], + [0, 0, 0, [1000, 200, 365, 30]], + [0, 0, 0, [1000, 0, 365]], + [10, 0, 0, [0, 200, 365]], + [-1, 0, 0, base], + [0, -1, 5, base], + [0, 0, -1, base], + ] + while len(cases) < n: + limits = [rng.choice([250, 500, 1000, 4000]), rng.choice([50, 100, 200]), rng.choice([30, 90, 180, 365])] + counters = [] + for limit in limits: + percent = rng.choice([0, 50, 85, 90, 95, 100, 105, 110, 120, rng.randint(0, 130)]) + counters.append(max(0, limit * percent // 100 + rng.choice([0, 0, -1, 1]))) + cases.append(counters + [limits]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/merge_intervals.py b/components/qemedia/upstream/qe_arena/corpus/merge_intervals.py new file mode 100644 index 0000000000000000000000000000000000000000..a723880f5754e1757a8a84a5448cce04397b5fb9 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/merge_intervals.py @@ -0,0 +1,53 @@ +"""Merge closed integer intervals into a disjoint cover. Original.""" + +META = { + "entry": "merge_intervals", + "origin": "Original.", + "tags": ["intervals", "invariants", "sorting"], + "domain": "mathematics-or-formal-reasoning", +} + + +def merge_intervals(intervals, touching): + """Merge closed integer intervals [lo, hi] into sorted, disjoint intervals covering the same integers. + + Intervals that overlap or share an endpoint always merge; when touching is True, intervals + with no integer between them ([1, 3] and [4, 6]) merge as well. Returns + {"merged": [[lo, hi], ...], "covered": c}, where c is the number of integers covered. + Invariants, with gap = 1 if touching else 0, proved by induction over the intervals sorted by + (lo, hi): (1) merged is sorted by lo; (2) consecutive a, b satisfy a.hi + gap < b.lo, because a + sorted interval whose lo is at most last.hi + gap is absorbed into last and its hi kept with max, + so no later interval can start further left; (3) the merged set equals the input set, since an + interval is only absorbed into one it overlaps or touches; hence c = sum(hi - lo + 1). + Raises ValueError if an interval does not have exactly two items or has lo > hi. + """ + gap = 1 if touching else 0 + merged = [] + for lo, hi in sorted(intervals): + if lo > hi: + raise ValueError("an interval needs lo <= hi") + if merged and lo <= merged[-1][1] + gap: + merged[-1][1] = max(merged[-1][1], hi) + else: + merged.append([lo, hi]) + covered = sum(hi - lo + 1 for lo, hi in merged) + return {"merged": merged, "covered": covered} + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], False], [[[1, 3]], False], [[[1, 3], [4, 6]], False], [[[1, 3], [4, 6]], True], + [[[1, 3], [5, 6]], True], [[[1, 3], [3, 6]], False], [[[4, 6], [1, 3]], True], + [[[1, 10], [2, 3]], False], [[[2, 3], [1, 10], [11, 12]], True], [[[5, 5], [5, 5]], False], + [[[0, 0], [2, 2], [4, 4]], False], [[[0, 0], [1, 1], [2, 2]], True], [[[3, 1]], False], + [[[1, 2, 3]], False], [[[1]], True], [[[-5, -1], [0, 4]], True], [[[-5, -1], [0, 4]], False], + [[[1, 4], [2, 3], [6, 8], [7, 9]], False], [[[1, 5], [2, 6], [3, 7]], True], + ] + while len(cases) < n: + items = [] + for _ in range(rng.randint(0, 7)): + lo = rng.randint(-20, 30) + items.append([lo, lo + rng.randint(0, 6)]) + cases.append([items, rng.random() < 0.5]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/mod_inverse.py b/components/qemedia/upstream/qe_arena/corpus/mod_inverse.py new file mode 100644 index 0000000000000000000000000000000000000000..f200f9383e3d9f0adcd360076da5742b225ccaa0 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/mod_inverse.py @@ -0,0 +1,47 @@ +"""Modular inverse by the extended Euclidean algorithm. Original.""" + +META = { + "entry": "mod_inverse", + "origin": "Original.", + "tags": ["number-theory", "euclid", "modular-arithmetic"], + "domain": "mathematics-or-formal-reasoning", +} + + +def extended_gcd(a, b): + """Return [g, x, y] with g == gcd(a, b) and a * x + b * y == g, for a, b >= 0.""" + if b == 0: + return [a, 1, 0] + g, x, y = extended_gcd(b, a % b) + return [g, y, x - (a // b) * y] + + +def mod_inverse(a, m): + """Return the inverse of a modulo m: the unique x with 0 <= x < m and (a * x) % m == 1. + + a may be negative or at least m; only its residue a % m matters. Bezout coefficients come + from the extended Euclidean algorithm: gcd(a, 0) == a == a * 1 + 0 * 0, and if + b * x + (a % b) * y == g then a * y + b * (x - (a // b) * y) == g, because + a % b == a - (a // b) * b. So with g == gcd(a % m, m) and (a % m) * x + m * y == g, the + inverse exists exactly when g == 1, and it is x reduced into [0, m). + Raises ValueError if m < 2 or gcd(a, m) != 1 (no inverse exists, including a % m == 0). + """ + if m < 2: + raise ValueError("the modulus must be at least 2") + g, x, _ = extended_gcd(a % m, m) + if g != 1: + raise ValueError("a is not invertible modulo m") + return x % m + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [3, 7], [1, 2], [1, 5], [4, 5], [2, 4], [0, 7], [7, 7], [14, 7], [-3, 7], [10, 7], + [3, 1], [3, 0], [3, -7], [17, 3120], [6, 9], [35, 64], [1, 1000003], [123456, 1000003], + [-1, 10], [9, 10], [7, 26], [2, 3], [5, 12], [11, 12], [0, 1], [1, 3], + ] + while len(cases) < n: + m = rng.randint(2, 5000) + cases.append([rng.randint(-10000, 10000), m]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/mod_pow.py b/components/qemedia/upstream/qe_arena/corpus/mod_pow.py new file mode 100644 index 0000000000000000000000000000000000000000..05ad5cc2f2660a842bc122ce3c9607405397673d --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/mod_pow.py @@ -0,0 +1,40 @@ +"""Modular exponentiation by left-to-right square and multiply. Original.""" + +META = { + "entry": "mod_pow", + "origin": "Original.", + "tags": ["number-theory", "modular-arithmetic", "exponentiation"], + "domain": "mathematics-or-formal-reasoning", +} + + +def mod_pow(base, exponent, modulus): + """Return base ** exponent % modulus, a value in [0, modulus), without building the power. + + Bits of exponent are read from the most significant one; for each bit the running result is + squared modulo modulus, then multiplied by base modulo modulus when the bit is 1. Invariant: + after the bits of the prefix p of exponent have been read, result == base ** p % modulus. + base may be negative or larger than modulus. exponent 0 gives 1 % modulus, so 0 ** 0 is 1, + and every result modulo 1 is 0. + Raises ValueError if modulus < 1 or exponent < 0. + """ + if modulus < 1 or exponent < 0: + raise ValueError("need modulus >= 1 and exponent >= 0") + result = 1 % modulus + for bit in format(exponent, "b"): + result = result * result % modulus + if bit == "1": + result = result * base % modulus + return result + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [2, 10, 1000], [2, 10, 1], [0, 0, 7], [0, 0, 1], [5, 0, 13], [0, 5, 13], [3, 1, 7], + [-2, 3, 7], [-2, 2, 7], [10, 3, 7], [7, 2, 7], [4, 13, 497], [2, 5, 0], [2, -1, 7], + [3, 200, 1000000007], [-1, 9, 10], [-1, 8, 10], [2, 1, 2], [6, 7, 9], [2, 64, 18446744073], + ] + while len(cases) < n: + cases.append([rng.randint(-50, 10 ** 6), rng.randint(0, 300), rng.randint(1, 10 ** 6)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/networkdays.py b/components/qemedia/upstream/qe_arena/corpus/networkdays.py new file mode 100644 index 0000000000000000000000000000000000000000..7a877416a623c3ed285b04e77274070584488bbd --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/networkdays.py @@ -0,0 +1,59 @@ +"""Count working days between two dates, inclusive, excluding weekends and holidays. Original.""" + +META = { + "entry": "networkdays", + "origin": "Original.", + "tags": ["calendar", "working-days", "spreadsheet"], + "domain": "office-white-collar", +} + + +def networkdays(start, end, holidays): + """Count working days from start to end inclusive, like a spreadsheet NETWORKDAYS. + + Dates are int day numbers from 1970-01-01 = 0, a Thursday: (day + 3) % 7 is the weekday + with Monday 0, and weekdays 0-4 are working days. Each distinct holiday that is a working + day in the range is subtracted once. If start > end the range is end..start and the count + is negated. Raises TypeError if start, end or a holiday is not an int (bools rejected). + """ + for value in [start, end] + list(holidays): + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError("dates must be int day numbers") + sign = 1 + if start > end: + start, end, sign = end, start, -1 + weeks, extra = divmod(end - start + 1, 7) + count = weeks * 5 + for offset in range(extra): + if (start + offset + 3) % 7 < 5: + count += 1 + off = {h for h in holidays if start <= h <= end and (h + 3) % 7 < 5} + return sign * (count - len(off)) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + # 20108 is Monday 2025-01-20; 20112 Friday, 20113 Saturday, 20114 Sunday. + cases = [ + [20108, 20112, []], + [20108, 20108, []], + [20113, 20114, []], + [20112, 20115, [20113]], + [20108, 20121, [20108, 20121]], + [20109, 20119, [20109, 20109, 20113, 20199]], + [20121, 20108, [20112]], + [20115, 20112, []], + [20114, 20114, [20114]], + [20111, 20111, [20111]], + [-3, 3, [0, -1]], + [20108, 20472, [20108, 20261, 20472]], + [20108, 20112, [True]], + ["2025-01-20", 20112, []], + ] + while len(cases) < n: + start = rng.randint(19700, 20500) + end = start + rng.randint(-20, 120) + lo, hi = min(start, end), max(start, end) + holidays = [rng.randint(lo - 5, hi + 5) for _ in range(rng.randint(0, 3))] + cases.append([start, end, holidays]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/normalize_rational.py b/components/qemedia/upstream/qe_arena/corpus/normalize_rational.py new file mode 100644 index 0000000000000000000000000000000000000000..a639b55ef82c1c77e92d16d3bdfd9ef3951f7b5b --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/normalize_rational.py @@ -0,0 +1,60 @@ +"""Parse a rational literal and reduce it to lowest terms. Original.""" + +import math +import re + +META = { + "entry": "normalize_rational", + "origin": "Original.", + "tags": ["number-theory", "parsing", "rationals"], + "domain": "mathematics-or-formal-reasoning", +} + + +def normalize_rational(text): + """Parse a rational literal and return it in lowest terms as [numerator, denominator]. + + Surrounding whitespace is ignored. Accepted forms, where a and b are ASCII decimal integers + with an optional "+" or "-" and n, d are unsigned ASCII decimal integers: + "a" (an integer), "a/b" (a fraction; b may be negative) and "a n/d" (a mixed number, one + space between a and n/d, meaning a whole part plus a proper fraction). A mixed number needs + n < d and takes the sign written on a, so "-1 1/2" is -3/2 and "-0 1/2" is -1/2. + The result has a positive denominator and gcd(|numerator|, denominator) == 1; zero is [0, 1]. + Raises ValueError for any other text, a zero denominator, or a mixed number with n >= d. + """ + found = re.fullmatch(r"([+-]?[0-9]+)(?: ([0-9]+)/([0-9]+)|/([+-]?[0-9]+))?", text.strip()) + if found is None: + raise ValueError("invalid rational literal: " + text) + whole, part, part_den, den_text = found.groups() + if part is not None: + num, den = int(part), int(part_den) + if num >= den: + raise ValueError("invalid rational literal: " + text) + num = abs(int(whole)) * den + num + if whole.startswith("-"): + num = -num + else: + num, den = int(whole), int(den_text or "1") + if den < 0: + num, den = -num, -den + if den < 1: + raise ValueError("invalid rational literal: " + text) + g = math.gcd(num, den) + return [num // g, den // g] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["6/8"], ["-6/8"], ["6/-8"], ["-6/-8"], ["+6/8"], ["0/5"], ["0"], ["-0"], ["7"], ["-7"], + ["5/0"], ["1 1/2"], ["-1 1/2"], ["-0 1/2"], ["+2 3/4"], ["2 4/8"], ["2 4/4"], ["2 5/4"], + ["2 0/4"], ["2 1/0"], ["2 -1/2"], [" 3/9 "], ["3 / 9"], ["1.5"], [""], ["a/b"], + ["10/4"], ["5/-1"], ["-5/-1"], ["0/-3"], ["12/-18"], ["0 0/7"], ["3 1/2"], ["-9 2/3"], ["100/25"], + ] + while len(cases) < n: + num, den = rng.randint(-60, 60), rng.choice([rng.randint(-24, 24), rng.randint(1, 24)]) + if rng.random() < 0.3: + cases.append([f"{rng.randint(-5, 5)} {rng.randint(0, 12)}/{rng.randint(0, 12)}"]) + else: + cases.append([f"{num}/{den}"]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/parse_cron_field.py b/components/qemedia/upstream/qe_arena/corpus/parse_cron_field.py new file mode 100644 index 0000000000000000000000000000000000000000..33cb8404eeca3c96d20d2cafa6dc73d1537eccbb --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/parse_cron_field.py @@ -0,0 +1,86 @@ +"""Expand one cron field into the sorted values it matches. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/cli/utils/workflow-parser.ts (MIT).""" + +import re + +META = { + "entry": "parse_cron_field", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/cli/utils/workflow-parser.ts", + "tags": ["parsing", "cron", "time-window"], + "domain": "software-engineering", +} + + +def parse_cron_field(field, minimum, maximum): + """Expand one cron field into the sorted list of values it selects, or None if invalid. + + field is a comma-separated list of items; each item is "*", "a", "a-b", "*/s", + "a-b/s" or "a/s" where a, b, s are decimal integers. "*" means start = minimum; + "*-b" is invalid. The end is b when given, else maximum for "*" or when a step is + given ("a/s" runs from a to maximum), else a. The step defaults to 1. An item is + invalid (the whole result is None) if it does not match that syntax, if step <= 0, + start < minimum, end > maximum or start > end. Values from all items are merged, + deduplicated and sorted ascending. + """ + values = set() + for item in field.split(","): + match = re.fullmatch(r"(\*|\d+)(?:-(\d+))?(?:/(\d+))?", item) + if not match or (match.group(1) == "*" and match.group(2) is not None): + return None + start = minimum if match.group(1) == "*" else int(match.group(1)) + if match.group(2) is not None: + end = int(match.group(2)) + elif match.group(1) == "*" or match.group(3) is not None: + end = maximum + else: + end = start + step = 1 if match.group(3) is None else int(match.group(3)) + if step <= 0 or start < minimum or end > maximum or start > end: + return None + values.update(range(start, end + 1, step)) + return sorted(values) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["*", 1, 12], + ["*", 0, 6], + ["*/5", 0, 23], + ["*/0", 0, 23], + ["5", 0, 23], + ["0", 0, 23], + ["0", 1, 12], + ["12", 1, 12], + ["13", 1, 12], + ["3-5", 1, 12], + ["5-3", 1, 12], + ["5-5", 1, 12], + ["1-12/4", 1, 12], + ["2/3", 1, 12], + ["10/3", 0, 23], + ["*-5", 0, 23], + ["1,3,3,2", 1, 12], + ["1-3,2-4", 1, 12], + ["", 0, 23], + ["1,", 0, 23], + ["a", 0, 23], + ["0-23/23", 0, 23], + ["22-23", 0, 23], + ["22-24", 0, 23], + ] + while len(cases) < n: + low, high = rng.choice([(0, 23), (1, 12), (0, 7), (1, 15)]) + def item(): + kind = rng.randint(0, 4) + a, b = rng.randint(low - 1, high), rng.randint(low, high + 1) + if kind == 0: + return str(a) + if kind == 1: + return f"{a}-{b}" + if kind == 2: + return f"*/{rng.randint(0, 6)}" + if kind == 3: + return f"{a}-{b}/{rng.randint(1, 5)}" + return f"{a}/{rng.randint(2, 8)}" + cases.append([",".join(item() for _ in range(rng.randint(1, 3))), low, high]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/parse_max_age.py b/components/qemedia/upstream/qe_arena/corpus/parse_max_age.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7b9ede0df4ce785b3233c3db1d8390439bb7bd --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/parse_max_age.py @@ -0,0 +1,40 @@ +"""Parse a max-age string such as "15m" into milliseconds. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/handlers/cross-phase-handlers.ts (MIT).""" + +import re + +META = { + "entry": "parse_max_age", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/handlers/cross-phase-handlers.ts", + "tags": ["parsing", "durations"], + "domain": "software-engineering", +} + + +def parse_max_age(max_age): + """Convert "" into milliseconds; return 0 for anything else. + + The whole string must match: one or more decimal digits followed by exactly one + unit, "d" (days), "h" (hours), "m" (minutes) or "s" (seconds). Units are + lowercase only and no whitespace is allowed. "0s" is 0; "90m" is 5400000. + """ + match = re.fullmatch(r"(\d+)([dhms])", max_age) + if not match: + return 0 + num = int(match.group(1)) + unit = match.group(2) + if unit == "d": + return num * 24 * 60 * 60 * 1000 + if unit == "h": + return num * 60 * 60 * 1000 + if unit == "m": + return num * 60 * 1000 + return num * 1000 + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [["0s"], ["1s"], ["1m"], ["1h"], ["1d"], ["90m"], ["2d"], ["36h"], ["7"], ["d"], + ["1w"], ["1D"], [" 1h"], ["1h "], ["1.5h"], ["-1h"], ["10ms"], [""], ["007s"]] + while len(cases) < n: + cases.append([str(rng.randint(0, 120)) + rng.choice("dhmsdhmsx")]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/parse_signature_header.py b/components/qemedia/upstream/qe_arena/corpus/parse_signature_header.py new file mode 100644 index 0000000000000000000000000000000000000000..e64ff43be0ab4674a63e7c6583500ec495e54b99 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/parse_signature_header.py @@ -0,0 +1,66 @@ +"""Parse a webhook signature header like "t=123,v1=abc". Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/adapters/a2a/notifications/signature.ts (MIT).""" + +META = { + "entry": "parse_signature_header", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/adapters/a2a/notifications/signature.ts", + "tags": ["parsing", "security", "webhooks"], + "domain": "software-engineering", +} + + +def parse_signature_header(header): + """Parse "t=,v1=" into {"timestamp": int, "v1": str}, or None. + + The header is split on ","; in each part the key is the text before the first "=" + and the value is everything after it ("" when there is no "="). Keys other than + "t" and "v1" are ignored; if a key repeats, the later value wins. Every "t" value + must be a non-empty string of decimal digits, otherwise the result is None (even + if a later "t" is valid). Returns None if the header is empty, "t" is missing, or + "v1" is missing or empty. + """ + if not header: + return None + timestamp = None + v1 = None + for part in header.split(","): + key, _, value = part.partition("=") + if key == "t": + if not value.isdecimal(): + return None + timestamp = int(value) + elif key == "v1": + v1 = value + if timestamp is None or not v1: + return None + return {"timestamp": timestamp, "v1": v1} + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [""], + ["t=1"], + ["v1=abc"], + ["t=1,v1=abc"], + ["v1=abc,t=0"], + ["t=12,v1="], + ["t=,v1=abc"], + ["t=1a,v1=abc"], + ["t,v1=abc"], + ["t=5,v1=a=b=="], + ["t=5,v1=x,v1=y"], + ["t=5,t=6,v1=x"], + ["t=5,v0=x,v1=z"], + ["T=5,v1=x"], + [" t=5,v1=x"], + ["t=-5,v1=x"], + ["t=5;v1=x"], + ] + while len(cases) < n: + parts = [] + for _ in range(rng.randint(1, 4)): + key = rng.choice(["t", "v1", "v0", "x", "t"]) + value = rng.choice([str(rng.randint(0, 9999)), "ab=c", "", "f00d", "9z"]) + parts.append(key + "=" + value if rng.random() < 0.9 else key) + cases.append([",".join(parts)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/password_violations.py b/components/qemedia/upstream/qe_arena/corpus/password_violations.py new file mode 100644 index 0000000000000000000000000000000000000000..dd26fa9a26ef5112092eb7bb8b9abb834d4125bc --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/password_violations.py @@ -0,0 +1,66 @@ +"""Check a new password against an account password policy. Original.""" + +from string import ascii_lowercase, ascii_uppercase, digits, punctuation + +META = { + "entry": "password_violations", + "origin": "Original.", + "tags": ["security", "authentication", "validation"], + "domain": "cybersecurity", +} + + +def password_violations(password, username, min_length, history): + """Return the codes of the policy rules a new password breaks, in this order, each once: + + "length": fewer than min_length characters. "classes": fewer than 3 of ASCII lowercase, + ASCII uppercase, ASCII digits and string.punctuation occur. "username": username has 3 or + more characters and occurs in password, ignoring case. "repeat": one character 3 or more + times in a row. "reused": password is in history. Raises ValueError if min_length < 8. + """ + if min_length < 8: + raise ValueError("min_length < 8") + found = [] + if len(password) < min_length: + found.append("length") + classes = sum(any(c in group for c in password) + for group in (ascii_lowercase, ascii_uppercase, digits, punctuation)) + if classes < 3: + found.append("classes") + name = username.lower() + if len(name) >= 3 and name in password.lower(): + found.append("username") + run = 1 + for i in range(1, len(password)): + run = run + 1 if password[i] == password[i - 1] else 1 + if run >= 3: + found.append("repeat") + break + if password in history: + found.append("reused") + return found + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["Tr0ub4dor&3x", "alice", 8, []], ["short1A", "bob", 8, []], ["Exactly8", "bob", 8, []], + ["exactly8!", "bob", 8, []], ["Exactly8!", "bob", 9, []], ["alllowercase", "bob", 8, []], + ["ALLUPPER123", "bob", 8, []], ["lower123!!", "bob", 8, []], ["Sup3rAliceX!", "alice", 8, []], + ["Sup3rALICEx!", "Alice", 8, []], ["Sup3rAlX!x!", "al", 8, []], ["Sup3rBobX!", "bob", 8, []], + ["Paaa55word!", "carol", 8, []], ["Paa55word!", "carol", 8, []], ["aaaB1!xyzw", "x", 8, []], + ["xyzwB1!ccc", "q", 8, []], ["xyzB1!cccc", "q", 8, []], ["aaB1!xyza", "q", 8, []], ["Winter2026!", "dave", 8, ["Winter2026!"]], + ["Winter2026!", "dave", 8, ["winter2026!", "Winter2025!"]], ["Pass word1", "eve", 8, []], + ["Pa55word!", "eve", 7, []], ["", "", 8, []], ["aaa", "aaa", 12, ["aaa"]], + ["Ünïcödé123", "bob", 8, []], ["Pa55word!", "eve", 0, []], + ] + names = ["alice", "Bob", "root", "al", "admin"] + pool = "aAbB1!xX9#zzz" + "root" + while len(cases) < n: + name = rng.choice(names) + pw = "".join(rng.choice(pool) for _ in range(rng.randint(4, 14))) + if rng.random() < 0.3: + pw = pw[:3] + name.upper() + pw[3:] + history = [pw] if rng.random() < 0.15 else ["Old1!pass"] + cases.append([pw, name, rng.choice([8, 8, 10, 12]), history]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/pattern_effectiveness.py b/components/qemedia/upstream/qe_arena/corpus/pattern_effectiveness.py new file mode 100644 index 0000000000000000000000000000000000000000..e998c37d117e701e384fdefc673fc66846583cce --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/pattern_effectiveness.py @@ -0,0 +1,58 @@ +"""Score how effective a reusable test-generation pattern has been. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/services/pattern_analytics.py (MIT).""" + +META = { + "entry": "pattern_effectiveness", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/services/pattern_analytics.py", + "tags": ["scoring", "analytics"], + "domain": "software-engineering", +} + + +def pattern_effectiveness(successful_generation, successful_tests, total_usage, avg_generation_ms): + """Return a 0-100 effectiveness score rounded to 2 decimals. + + Raises ValueError if total_usage is negative, or if successful_generation or + successful_tests is negative or greater than total_usage. Returns 0.0 when + total_usage is 0. Otherwise: + generation = successful_generation / total_usage * 40 + tests = successful_tests / total_usage * 40 + speed = min(20, 20 * 1000 / max(avg_generation_ms, 1)) + and the result is round(generation + tests + speed, 2). + """ + if total_usage < 0: + raise ValueError("total_usage must be non-negative") + for count in (successful_generation, successful_tests): + if count < 0 or count > total_usage: + raise ValueError("success counts must be within [0, total_usage]") + if total_usage == 0: + return 0.0 + generation = successful_generation / total_usage * 40 + tests = successful_tests / total_usage * 40 + speed = min(20, 20 * 1000 / max(avg_generation_ms, 1)) + return round(generation + tests + speed, 2) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [0, 0, 0, 500], + [1, 0, 0, 500], + [0, 0, -1, 500], + [-1, 0, 4, 500], + [0, 5, 4, 500], + [4, 4, 4, 1000], + [4, 4, 4, 999], + [4, 4, 4, 1001], + [2, 1, 4, 2000], + [3, 1, 4, 4000], + [1, 3, 8, 0], + [1, 1, 3, 1], + [0, 0, 5, 2500], + [5, 0, 5, 3000], + [0, 5, 5, 1500], + [1, 2, 3, -50], + ] + while len(cases) < n: + total = rng.randint(1, 50) + cases.append([rng.randint(0, total), rng.randint(0, total), total, rng.randint(0, 5000)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/pressure_check.py b/components/qemedia/upstream/qe_arena/corpus/pressure_check.py new file mode 100644 index 0000000000000000000000000000000000000000..1be71f0be35cfaa49bd15fb67218c1b597865345 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/pressure_check.py @@ -0,0 +1,73 @@ +"""Convert a pressure reading to the nominal's unit and check it against a tolerance. Original.""" + +import math +from fractions import Fraction + +META = { + "entry": "pressure_check", + "origin": "Original.", + "tags": ["units", "tolerance", "instrumentation"], + "domain": "industrial-physical-systems", +} + + +def pressure_check(reading_milli, reading_unit, nominal_milli, nominal_unit, tolerance_bp): + """Check a pressure reading against a nominal value that may be in another unit. + + Values are ints in thousandths of their unit (2500 "bar" is 2.5 bar). Units in pascals, exact: + "Pa" 1, "kPa" 1000, "bar" 100000, "psi" 6894.757293168, "mmHg" 133.322387415. + converted is the reading in thousandths of nominal_unit, rounded half up. deviation_bp is + (reading - nominal) / nominal * 10000, exact, truncated toward zero. verdict is "ok" if + abs(deviation_bp) <= tolerance_bp, else "low" or "high" by the sign of deviation_bp. + Returns [converted, deviation_bp, verdict]. + Raises ValueError if nominal_milli < 1, reading_milli < 0 or tolerance_bp < 0 (checked + first), and KeyError for an unknown unit. + """ + pascals = {"Pa": Fraction(1), "kPa": Fraction(1000), "bar": Fraction(100000), + "psi": Fraction(6894757293168, 10**9), "mmHg": Fraction(133322387415, 10**9)} + if nominal_milli < 1 or reading_milli < 0 or tolerance_bp < 0: + raise ValueError("invalid pressure check") + reading = reading_milli * pascals[reading_unit] + nominal = nominal_milli * pascals[nominal_unit] + converted = math.floor(reading / pascals[nominal_unit] + Fraction(1, 2)) + deviation_bp = math.trunc((reading - nominal) * 10000 / nominal) + if abs(deviation_bp) <= tolerance_bp: + return [converted, deviation_bp, "ok"] + return [converted, deviation_bp, "low" if deviation_bp < 0 else "high"] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [2500, "bar", 2500, "bar", 0], + [2500, "bar", 250000, "kPa", 0], + [36259, "psi", 2500, "bar", 0], + [36259, "psi", 2500, "bar", 1], + [36259, "psi", 2500, "bar", 10], + [36260, "psi", 2500, "bar", 0], + [760000, "mmHg", 101325, "kPa", 0], + [760000, "mmHg", 101325, "kPa", 1], + [1013250, "Pa", 760000, "mmHg", 5], + [2525, "bar", 2500, "bar", 100], + [2526, "bar", 2500, "bar", 100], + [2475, "bar", 2500, "bar", 100], + [2474, "bar", 2500, "bar", 100], + [0, "kPa", 1, "kPa", 9999], + [1, "bar", 1, "Pa", 0], + [1, "Pa", 1, "bar", 0], + [3, "Pa", 2, "kPa", 0], + [2500, "bar", 0, "bar", 0], + [-1, "bar", 2500, "bar", 0], + [2500, "bar", 2500, "bar", -1], + [2500, "atm", 2500, "bar", 0], + [2500, "bar", 2500, "torr", 0], + ] + units = ["Pa", "kPa", "bar", "psi", "mmHg"] + scale = {"Pa": 100000000, "kPa": 100000, "bar": 1000, "psi": 14504, "mmHg": 750062} + while len(cases) < n: + a, b = rng.choice(units), rng.choice(units) + nominal = scale[b] * rng.randint(1, 40) // 10 + rng.randint(0, 9) + drift = rng.choice([0, 1, -1, 5, -5, 50, -50, 300, -300, rng.randint(-2000, 2000)]) + reading = max(0, (nominal * (10000 + drift) // 10000) * scale[a] // scale[b]) + cases.append([reading, a, nominal, b, rng.choice([0, 1, 10, 50, 100, 250])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/quality_gain_reward.py b/components/qemedia/upstream/qe_arena/corpus/quality_gain_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1d506118cf8c15e309cd6392526c5d6d17dd499f --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/quality_gain_reward.py @@ -0,0 +1,51 @@ +"""Reward a quality improvement plus the bugs it uncovered. Adapted from proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/reward_calculator.py (MIT).""" + +META = { + "entry": "quality_gain_reward", + "origin": "proffesor-for-testing/lionagi-qe-fleet@ce1d58750a240a16c3c53abcb8a7c73864e98c99:src/lionagi_qe/learning/reward_calculator.py", + "tags": ["reward", "quality-score"], + "domain": "software-engineering", +} + + +def quality_gain_reward(quality_before, quality_after, bugs_found, critical_bugs): + """Return the integer quality reward for one QE action, capped at 100. + + A missing (None) quality score defaults to 50. + reward = (quality_after - quality_before) * 2 + bugs_found * 5 + critical_bugs * 20, + then min(reward, 100). Negative rewards are not floored. critical_bugs are scored in + addition to bugs_found. Raises ValueError if bugs_found or critical_bugs is negative. + """ + if bugs_found < 0 or critical_bugs < 0: + raise ValueError("bug counts must be non-negative") + before = 50 if quality_before is None else quality_before + after = 50 if quality_after is None else quality_after + reward = (after - before) * 2 + reward += bugs_found * 5 + reward += critical_bugs * 20 + return min(reward, 100) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [None, None, 0, 0], + [None, 60, 0, 0], + [40, None, 0, 0], + [50, 50, 1, 0], + [50, 50, 0, 1], + [70, 60, 1, 1], + [0, 50, 0, 0], + [0, 50, 0, 1], + [0, 50, 1, 0], + [10, 100, 2, 1], + [90, 10, 3, 2], + [50, 50, -1, 0], + [50, 50, 0, -1], + [60, 61, 0, 4], + [60, 61, 0, 5], + ] + while len(cases) < n: + cases.append([rng.choice([None, rng.randint(0, 100)]), rng.choice([None, rng.randint(0, 100)]), + rng.randint(0, 6), rng.randint(0, 3)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/quality_grade.py b/components/qemedia/upstream/qe_arena/corpus/quality_grade.py new file mode 100644 index 0000000000000000000000000000000000000000..7d3620f79649999536697145bbaea5010b176ef8 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/quality_grade.py @@ -0,0 +1,61 @@ +"""Grade a quality score, failing on any critical check failure. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/tools/quality-assessment/evaluate.ts (MIT).""" + +META = { + "entry": "quality_grade", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/mcp/tools/quality-assessment/evaluate.ts", + "tags": ["quality-gate", "thresholds"], + "domain": "software-engineering", +} + + +def quality_grade(score, checks): + """Return a letter grade for a quality assessment. + + checks is a list of {"passed": bool, "severity": str}. If any check has + passed False and severity "critical", the grade is "F" regardless of score. + Otherwise: score >= 90 "A", >= 80 "B", >= 70 "C", >= 60 "D", else "F". + Raises ValueError if score is outside 0..100. + """ + if score < 0 or score > 100: + raise ValueError("score must be within 0..100") + if any(not c["passed"] and c["severity"] == "critical" for c in checks): + return "F" + if score >= 90: + return "A" + if score >= 80: + return "B" + if score >= 70: + return "C" + if score >= 60: + return "D" + return "F" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + def check(passed, severity): + return {"passed": passed, "severity": severity} + + cases = [ + [100, []], + [90, []], + [89, []], + [80, []], + [79, []], + [70, []], + [69, []], + [60, []], + [59, []], + [0, []], + [95, [check(False, "critical")]], + [95, [check(True, "critical")]], + [95, [check(False, "high"), check(True, "critical")]], + [85, [check(True, "low"), check(False, "critical")]], + [101, []], + [-1, []], + ] + while len(cases) < n: + checks = [check(rng.random() < 0.7, rng.choice(["low", "high", "critical"])) + for _ in range(rng.randint(0, 3))] + cases.append([rng.randint(50, 100), checks]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/reconcile_invoices.py b/components/qemedia/upstream/qe_arena/corpus/reconcile_invoices.py new file mode 100644 index 0000000000000000000000000000000000000000..9015dbc590f7192b1c5728fff31661cc4d583564 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/reconcile_invoices.py @@ -0,0 +1,89 @@ +"""Match payments to invoices and classify each invoice's settlement. Original.""" + +META = { + "entry": "reconcile_invoices", + "origin": "Original.", + "tags": ["accounts-receivable", "reconciliation", "money"], + "domain": "finance-economics", +} + + +def reconcile_invoices(invoices, payments, tolerance_cents): + """Reconcile payments against invoices in integer cents. + + invoices and payments list [invoice_id, amount_cents]; a payment for an id with no invoice is + unmatched. Per invoice, with paid = the sum of its payments and diff = paid - amount_cents: + "unpaid" if paid == 0, else "settled" if abs(diff) <= tolerance_cents, else "short" if + diff < 0, else "over". + Returns [labels in invoice order, open_cents = sum of -diff over unpaid and short invoices, + unmatched_cents]. + Raises ValueError if tolerance_cents < 0, an invoice id repeats, or any amount is below 1. + """ + if tolerance_cents < 0: + raise ValueError + paid, unmatched = {}, 0 + for invoice_id, amount in invoices: + if invoice_id in paid or amount < 1: + raise ValueError + paid[invoice_id] = 0 + for invoice_id, amount in payments: + if amount < 1: + raise ValueError + if invoice_id in paid: + paid[invoice_id] += amount + else: + unmatched += amount + labels, open_cents = [], 0 + for invoice_id, amount in invoices: + diff = paid[invoice_id] - amount + if paid[invoice_id] == 0: + label = "unpaid" + elif abs(diff) <= tolerance_cents: + label = "settled" + else: + label = "short" if diff < 0 else "over" + if label in ("unpaid", "short"): + open_cents -= diff + labels.append(label) + return [labels, open_cents, unmatched] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], [], 0], + [[["A1", 500]], [], 0], + [[["A1", 500]], [["A1", 500]], 0], + [[["A1", 500]], [["A1", 499]], 0], + [[["A1", 500]], [["A1", 499]], 1], + [[["A1", 500]], [["A1", 501]], 1], + [[["A1", 500]], [["A1", 502]], 1], + [[["A1", 500]], [["A1", 497]], 2], + [[["A1", 500]], [["A1", 200], ["A1", 300]], 0], + [[["A1", 500]], [["B2", 300]], 0], + [[["A1", 500], ["B2", 300]], [["B2", 300], ["C3", 40]], 0], + [[["A1", 500], ["B2", 300]], [["A1", 450], ["B2", 350]], 5], + [[["A1", 1]], [["A1", 1]], 0], + [[["A1", 1], ["A1", 2]], [], 0], + [[["A1", 0]], [], 0], + [[["A1", 500]], [["A1", 0]], 0], + [[["A1", 500]], [], -1], + [[["A1", 10], ["B2", 20]], [["A1", 5], ["B2", 25]], 4], + [[["", 500]], [["", 500]], 0], + [[["", 500], ["", 20]], [], 0], + [[["", 0]], [], 0], + [[["A1", 500]], [["", 500]], 0], + ] + while len(cases) < n: + ids = rng.sample(["A1", "B2", "C3", "D4", "E5", "F6"], rng.randint(1, 4)) + invoices = [[i, rng.choice([100, 250, 500, 1000, rng.randint(1, 2000)])] for i in ids] + payments = [] + for invoice_id, amount in invoices: + parts = rng.choice([0, 1, 1, 1, 2]) + for _ in range(parts): + payments.append([invoice_id, max(1, amount // parts + rng.choice([0, 0, -1, 1, -3, 3, -50, 50]))]) + if rng.random() < 0.3: + payments.append([rng.choice(["X9", "Y8"]), rng.randint(1, 300)]) + rng.shuffle(payments) + cases.append([invoices, payments, rng.choice([0, 0, 1, 2, 5])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/round_sig_figs.py b/components/qemedia/upstream/qe_arena/corpus/round_sig_figs.py new file mode 100644 index 0000000000000000000000000000000000000000..4a4ab64b5a3cc5667ef83d08f167a36e375348d8 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/round_sig_figs.py @@ -0,0 +1,52 @@ +"""Round a fixed-point measurement to significant figures, ties to even. Original.""" + +META = { + "entry": "round_sig_figs", + "origin": "Original.", + "tags": ["measurement", "rounding", "significant-figures"], + "domain": "natural-science", +} + + +def round_sig_figs(value, scale, sig): + """Round the measurement value * 10 ** (-scale) to sig significant figures. + + value is an integer count of the last recorded digit, so [12345, 3] is 12.345 and + [12, -2] is 1200. Let d be the number of decimal digits of abs(value) (zero has one). + If d <= sig the measurement is returned unchanged as [value, scale]. Otherwise the + d - sig trailing digits of abs(value) are dropped, rounding half to even (12.345 -> 12.34 and + 12.355 -> 12.36 at 4 figures), and the sign of value is kept. When rounding carries into a new + digit one more trailing digit is dropped, so the result still has exactly sig digits: + 999.5 at 3 figures, [9995, 1], becomes [100, -1], which is 1000. Returns + [rounded, scale - dropped]. + Raises ValueError if sig < 1. + """ + if sig < 1: + raise ValueError("at least one significant figure is required") + magnitude = abs(value) + dropped = max(0, len(str(magnitude)) - sig) + unit = 10 ** dropped + kept, rest = divmod(magnitude, unit) + if 2 * rest > unit or (2 * rest == unit and kept % 2 == 1): + kept += 1 + if kept == 10 ** sig: + kept //= 10 + dropped += 1 + return [-kept if value < 0 else kept, scale - dropped] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [12345, 3, 4], [12355, 3, 4], [12346, 3, 4], [12344, 3, 4], [-12345, 3, 4], [-12355, 3, 4], + [9995, 1, 3], [99950, 2, 3], [9994, 1, 3], [-9996, 0, 3], [0, 2, 1], [7, 0, 1], [15, 0, 1], + [25, 0, 1], [35, 0, 1], [45, -2, 1], [123, 0, 3], [123, 0, 5], [123, 0, 0], [1250, 2, 2], + [1350, 2, 2], [1251, 2, 2], [999, 0, 2], [5, 0, 1], [-1, 0, 1], [1, 0, 1], [-1, 4, 3], [96, 0, 1], [1050, 0, 2], + ] + while len(cases) < n: + sig = rng.randint(1, 5) + value = rng.randint(1, 10 ** rng.randint(1, 8)) + if rng.random() < 0.5: + value = value // 10 * 10 + 5 + cases.append([value * rng.choice([1, -1]), rng.randint(-3, 6), sig]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/safe_join.py b/components/qemedia/upstream/qe_arena/corpus/safe_join.py new file mode 100644 index 0000000000000000000000000000000000000000..5bffef216d26990c2fa3bc3f3349e8af1c9e6918 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/safe_join.py @@ -0,0 +1,56 @@ +"""Join an untrusted relative path under a base directory without traversal. Original.""" + +META = { + "entry": "safe_join", + "origin": "Original.", + "tags": ["security", "path-traversal", "paths"], + "domain": "cybersecurity", +} + + +def safe_join(base, user_path): + """Resolve an untrusted relative path under the directory base without escaping it. + + root is base without trailing "/" characters. user_path is split on "/" and on "\\"; + empty and "." segments are skipped and ".." drops the last kept segment. Returns + root + "/" + the kept segments joined by "/", or root ("/" when root is "") if none is kept. + Raises ValueError if base does not start with "/", user_path starts with "/" or "\\", + user_path contains a NUL character, or a ".." has no kept segment to drop. + """ + if not base.startswith("/"): + raise ValueError("bad base") + if user_path.startswith("/") or user_path.startswith("\\") or "\x00" in user_path: + raise ValueError("bad path") + kept = [] + for segment in user_path.replace("\\", "/").split("/"): + if segment in ("", "."): + continue + if segment == "..": + if not kept: + raise ValueError("escapes base") + kept.pop() + else: + kept.append(segment) + root = base.rstrip("/") + if not kept: + return root or "/" + return root + "/" + "/".join(kept) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["/srv/files", "report.pdf"], ["/srv/files/", "a/b/c.txt"], ["/", "etc/passwd"], + ["/srv/files", "../etc/passwd"], ["/srv/files", "a/../../b"], ["/srv/files", "a/b/../c"], + ["/srv/files", "a/./b//c/"], ["/srv/files", ""], ["/srv/files", "."], ["/", ""], + ["/", "a/.."], ["/srv/files", "/etc/passwd"], ["/srv/files", "\\windows\\win.ini"], + ["/srv/files", "a\\..\\..\\b"], ["/srv/files", "a\\b"], ["/srv/files", "ok\x00.png"], + ["srv/files", "a"], ["", "a"], ["/srv//", "x/y"], ["/srv/files", "..."], + ["/srv/files", "..a/b.."], ["/srv/files", "a/b/c/../../.."], ["/srv/files", "a/b/c/../../../.."], + ["/srv/files", "./"], + ] + parts = ["a", "b", "img", "..", ".", "", "x.txt", "\\", "..\\.."] + while len(cases) < n: + path = "/".join(rng.choice(parts) for _ in range(rng.randint(1, 6))) + cases.append([rng.choice(["/srv/files", "/srv/files/", "/", "/data"]), path]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/sample_variance.py b/components/qemedia/upstream/qe_arena/corpus/sample_variance.py new file mode 100644 index 0000000000000000000000000000000000000000..97818320e4e090e0e80eb5dbcdd929b987184e4a --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/sample_variance.py @@ -0,0 +1,44 @@ +"""Exact variance of integer measurements as a reduced fraction. Original.""" + +from fractions import Fraction + +META = { + "entry": "sample_variance", + "origin": "Original.", + "tags": ["statistics", "measurement", "exact-arithmetic"], + "domain": "natural-science", +} + + +def sample_variance(values, population): + """Return the variance of integer measurements as an exact fraction [numerator, denominator]. + + With n = len(values) and mean = sum(values) / n, the sum of squared deviations + S = sum((x - mean) ** 2 for x in values) is divided by n when population is True and by + n - 1 (Bessel's correction, the sample variance) when population is False. The result is in + lowest terms with a positive denominator; a zero variance is [0, 1]. + Raises ValueError if values is empty, or if population is False and there is only one value. + """ + n = len(values) + dof = n if population else n - 1 + if dof < 1: + raise ValueError("not enough measurements for this variance") + mean = Fraction(sum(values), n) + spread = sum((Fraction(x) - mean) ** 2 for x in values) + variance = spread / dof + return [variance.numerator, variance.denominator] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], True], [[], False], [[7], True], [[7], False], [[3, 3], False], [[3, 5], False], + [[3, 5], True], [[1, 2, 3, 4], False], [[1, 2, 3, 4], True], [[-4, 0, 4], False], + [[10, 10, 10, 13], False], [[0, 1], True], [[2, 4, 4, 4, 5, 5, 7, 9], True], + [[2, 4, 4, 4, 5, 5, 7, 9], False], [[-3, 9], False], [[100, 101, 99, 100, 102], False], + ] + while len(cases) < n: + centre = rng.randint(-50, 400) + values = [centre + rng.randint(-9, 9) for _ in range(rng.randint(1, 9))] + cases.append([values, rng.random() < 0.4]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/select_bitrate_rung.py b/components/qemedia/upstream/qe_arena/corpus/select_bitrate_rung.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d59b12537577976462fda12a865171267fcee2 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/select_bitrate_rung.py @@ -0,0 +1,65 @@ +"""Choose the next rung of an adaptive-streaming bitrate ladder from bandwidth and buffer. Original.""" + +META = { + "entry": "select_bitrate_rung", + "origin": "Original.", + "tags": ["streaming", "abr", "video"], + "domain": "media-content-production", +} + + +def select_bitrate_rung(bandwidth_kbps, buffer_ms, current): + """Pick the next rung of the ladder 400, 1200, 3000, 6000 kbps; return [index, reason]. + + current is the rung (0-3) playing now. The sustainable rung is the highest whose + kbps * 100 <= bandwidth_kbps * 80. First match wins: buffer_ms < 4000 gives [0, "panic"]; + no sustainable rung gives [0, "starved"]; sustainable > current gives [current + 1, "up"] + if buffer_ms >= 12000, else [current, "hold"]; sustainable < current gives + [sustainable, "down"]; otherwise [current, "stay"]. Raises ValueError if current is not + 0-3 or bandwidth_kbps or buffer_ms is negative. + """ + ladder = [400, 1200, 3000, 6000] + if not 0 <= current < len(ladder) or bandwidth_kbps < 0 or buffer_ms < 0: + raise ValueError("bad player state") + if buffer_ms < 4000: + return [0, "panic"] + sustainable = None + for index, kbps in enumerate(ladder): + if kbps * 100 <= bandwidth_kbps * 80: + sustainable = index + if sustainable is None: + return [0, "starved"] + if sustainable > current: + return [current + 1, "up"] if buffer_ms >= 12000 else [current, "hold"] + if sustainable < current: + return [sustainable, "down"] + return [current, "stay"] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [500, 20000, 1], + [499, 20000, 1], + [1500, 20000, 0], + [1499, 20000, 0], + [3750, 20000, 1], + [3749, 20000, 1], + [7500, 20000, 2], + [7499, 20000, 2], + [3750, 12000, 1], + [3750, 11999, 1], + [3750, 4000, 3], + [3750, 3999, 3], + [0, 30000, 2], + [5000, 0, 2], + [50000, 30000, 3], + [5000, 20000, 4], + [5000, 20000, -1], + [-1, 20000, 0], + [5000, -1, 0], + ] + while len(cases) < n: + current = rng.randint(0, 3) if rng.random() < 0.95 else rng.choice([-1, 4]) + cases.append([rng.randint(0, 9000), rng.randint(0, 30000), current]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/shift_cue.py b/components/qemedia/upstream/qe_arena/corpus/shift_cue.py new file mode 100644 index 0000000000000000000000000000000000000000..bbc45b0fac2f060cc42dbfc42d1787d32dc79fb4 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/shift_cue.py @@ -0,0 +1,66 @@ +"""Shift one SRT subtitle cue by a timing offset, clamping or dropping it at zero. Original.""" + +import re + +META = { + "entry": "shift_cue", + "origin": "Original.", + "tags": ["subtitles", "srt", "timecode"], + "domain": "media-content-production", +} + + +def shift_cue(start, end, offset_ms): + """Shift an SRT cue by offset_ms (int, may be negative); return [start, end] or None. + + start and end are "HH:MM:SS,mmm" (two-digit hours, minutes and seconds 00-59, three-digit + milliseconds). A cue whose shifted end is at or before 0 ms is dropped (None); a shifted + start below 0 becomes "00:00:00,000". Raises ValueError for a malformed timestamp, an end + not after the start, or a shifted end past 99:59:59,999. + """ + times = [] + for stamp in (start, end): + match = re.fullmatch(r"(\d\d):([0-5]\d):([0-5]\d),(\d\d\d)", stamp) + if not match: + raise ValueError("bad SRT timestamp") + hours, minutes, seconds, millis = (int(part) for part in match.groups()) + times.append(((hours * 60 + minutes) * 60 + seconds) * 1000 + millis + offset_ms) + first, last = times + if last <= first: + raise ValueError("cue must end after it starts") + if last <= 0: + return None + if last > 359999999: + raise ValueError("shifted past 99:59:59,999") + shifted = [] + for ms in (max(0, first), last): + seconds, millis = divmod(ms, 1000) + hours, seconds = divmod(seconds, 3600) + shifted.append("%02d:%02d:%02d,%03d" % (hours, seconds // 60, seconds % 60, millis)) + return shifted + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["00:00:01,000", "00:00:02,500", 0], + ["00:00:01,000", "00:00:02,500", 250], + ["00:00:01,000", "00:00:02,000", -2000], + ["00:00:01,000", "00:00:02,000", -1999], + ["00:00:00,500", "00:00:01,200", -600], + ["01:59:59,999", "02:00:00,000", 1], + ["99:59:58,000", "99:59:59,000", 999], + ["99:59:58,000", "99:59:59,000", 1000], + ["00:00:05,000", "00:00:05,000", 0], + ["00:00:05,000", "00:00:04,999", 0], + ["0:00:05,000", "00:00:06,000", 0], + ["00:60:05,000", "01:00:06,000", 0], + ["00:00:05.000", "00:00:06,000", 0], + ["00:59:59,500", "01:00:01,000", 600], + ] + while len(cases) < n: + t = rng.choice([rng.randint(0, 20000), rng.randint(0, 3 * 3600000)]) + length = rng.randint(1, 6000) if rng.random() < 0.92 else -rng.randint(0, 500) + start, end = [shift_cue("00:00:00,000", "00:00:00,001", ms) for ms in (t, max(0, t + length))] + cases.append([start[0], end[0], rng.choice([0, rng.randint(-5000, 5000), rng.randint(-4000000, 4000000)])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/slew_limit.py b/components/qemedia/upstream/qe_arena/corpus/slew_limit.py new file mode 100644 index 0000000000000000000000000000000000000000..1243054360ab465e1efae5a6451d4abdfa0d3680 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/slew_limit.py @@ -0,0 +1,72 @@ +"""Ramp-limit an actuator setpoint once per control tick. Original.""" + +META = { + "entry": "slew_limit", + "origin": "Original.", + "tags": ["control", "rate-limiter", "actuator"], + "domain": "industrial-physical-systems", +} + + +def slew_limit(targets, start, max_rise, max_fall, deadband, low, high): + """Ramp-limit an actuator setpoint, one output per control tick. + + Each target is clamped to [low, high]. If the clamped target is within deadband of the previous + output (start before the first tick), abs(goal - previous) <= deadband, the output holds. + Otherwise it moves toward the clamped target by at most max_rise per tick when rising and + max_fall when falling, stopping exactly on the target when it is within reach. + Returns the list of outputs, one per target. + Raises ValueError if max_rise < 1, max_fall < 1, deadband < 0, or start is outside + [low, high] (so also whenever low > high). + """ + if max_rise < 1 or max_fall < 1 or deadband < 0 or not low <= start <= high: + raise ValueError("invalid limiter settings") + outputs, current = [], start + for target in targets: + goal = min(max(target, low), high) + if abs(goal - current) <= deadband: + pass + elif goal > current: + current = min(goal, current + max_rise) + else: + current = max(goal, current - max_fall) + outputs.append(current) + return outputs + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[], 0, 5, 5, 0, 0, 100], + [[10], 0, 5, 5, 0, 0, 100], + [[10, 10, 10], 0, 5, 3, 0, 0, 100], + [[0, 0, 0], 10, 5, 3, 0, 0, 100], + [[4], 0, 5, 5, 0, 0, 100], + [[5], 0, 5, 5, 0, 0, 100], + [[6], 0, 5, 5, 0, 0, 100], + [[3, 2], 0, 5, 5, 2, 0, 100], + [[3, 2], 0, 5, 5, 3, 0, 100], + [[150, 150, 150], 90, 7, 7, 0, 0, 100], + [[-50, -50], 10, 7, 4, 0, 0, 100], + [[50, 0, 50], 20, 10, 20, 1, 0, 100], + [[7, 8, 9], 7, 1, 1, 0, 7, 9], + [[10], 0, 0, 5, 0, 0, 100], + [[10], 0, 5, 0, 0, 0, 100], + [[10], 0, 5, 5, -1, 0, 100], + [[10], 0, 5, 5, 0, 100, 0], + [[10], 101, 5, 5, 0, 0, 100], + [[10], -1, 5, 5, 0, 0, 100], + [[5, 5], 5, 1, 1, 0, 5, 5], + [[10], 0, 0, 5, 0, -10, 0], + [[10], 0, 5, 5, 0, 1, 100], + [[1], 5, 5, 5, 0, -10, 0], + [[0], 1, 5, 5, 2, 0, 100], + [[0], -5, 3, 3, 0, -10, 10], + ] + while len(cases) < n: + low = rng.randint(-50, 50) + high = low + rng.randint(0, 200) + start = rng.randint(low, high) + targets = [rng.randint(low - 30, high + 30) for _ in range(rng.randint(1, 8))] + cases.append([targets, start, rng.randint(1, 40), rng.randint(1, 40), rng.choice([0, 0, 1, 3]), low, high]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/spec_readiness_score.py b/components/qemedia/upstream/qe_arena/corpus/spec_readiness_score.py new file mode 100644 index 0000000000000000000000000000000000000000..34b6ffabd096733a96df35e69bec7f8522cb5ad2 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/spec_readiness_score.py @@ -0,0 +1,97 @@ +"""Score how well an OpenAPI spec is documented for LLM test generation. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/spec_service/app_factory.py (MIT).""" + +META = { + "entry": "spec_readiness_score", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/spec_service/app_factory.py", + "tags": ["api", "openapi", "scoring"], + "domain": "software-engineering", +} + + +def spec_readiness_score(spec): + """Return an integer readiness score from 0 to 100 for an OpenAPI-like dict. + + Points: "info" present +10, and +5 more if spec["info"] has "description". + "paths" present +20. For each operation under spec["paths"][path][method] whose + method is get/post/put/delete/patch (other methods are ignored): +1 if it has + "parameters" and +1 if it has "responses". An operation is documented if it has + "summary" or "description"; the documentation bonus is documented * 30 // total + (integer division; no bonus when there are no counted operations). + +20 if spec["components"] has "schemas", otherwise +20 if "definitions" is present. + +15 if "security" or "securityDefinitions" is present. The total is capped at 100. + """ + score = 0 + if "info" in spec: + score += 10 + if "description" in spec["info"]: + score += 5 + if "paths" in spec: + score += 20 + total = documented = 0 + for methods in spec["paths"].values(): + for method, operation in methods.items(): + if method in ("get", "post", "put", "delete", "patch"): + total += 1 + if "summary" in operation or "description" in operation: + documented += 1 + if "parameters" in operation: + score += 1 + if "responses" in operation: + score += 1 + if total > 0: + score += documented * 30 // total + if "components" in spec and "schemas" in spec["components"]: + score += 20 + elif "definitions" in spec: + score += 20 + if "security" in spec or "securityDefinitions" in spec: + score += 15 + return min(score, 100) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + def _operation(rng): + keys = ["summary", "description", "parameters", "responses"] + return {k: 1 for k in keys if rng.random() < 0.5} + + doc = {"summary": 1, "responses": 1} + bare = {"responses": 1} + cases = [ + [{}], + [{"info": {}}], + [{"info": {"description": "d"}}], + [{"paths": {}}], + [{"paths": {"/a": {"head": doc, "options": doc}}}], + [{"paths": {"/a": {"get": {"description": 1}}}}], + [{"paths": {"/a": {"get": doc, "post": bare, "put": bare}}}], + [{"paths": {"/a": {"get": doc, "post": doc, "put": bare}}}], + [{"paths": {"/a": {"get": doc, "delete": bare}, "/b": {"patch": {"parameters": 1}, "post": bare}}}], + [{"paths": {"/a": {"get": doc, "post": doc, "put": doc}, "/b": {"patch": bare, "delete": bare}, "/c": {"get": bare, "post": bare}}}], + [{"components": {}}], + [{"components": {"schemas": {}}}], + [{"components": {}, "definitions": {}}], + [{"definitions": {}}], + [{"security": []}], + [{"securityDefinitions": {}}], + [{"info": {"description": "d"}, "paths": {"/a": {m: {"summary": 1, "parameters": 1, "responses": 1} for m in ("get", "post", "put", "delete", "patch")}}, "components": {"schemas": {}}, "security": []}], + [{"info": {"description": "d"}, "paths": {"/a": {"get": doc}}, "components": {"schemas": {}}, "security": []}], + ] + while len(cases) < n: + spec = {} + if rng.random() < 0.7: + spec["info"] = {"description": "d"} if rng.random() < 0.5 else {} + if rng.random() < 0.8: + methods = ["get", "post", "put", "delete", "patch", "head"] + spec["paths"] = { + f"/r{i}": {m: _operation(rng) for m in rng.sample(methods, rng.randint(1, 3))} + for i in range(rng.randint(0, 3)) + } + if rng.random() < 0.5: + spec["components"] = {"schemas": {}} if rng.random() < 0.6 else {} + if rng.random() < 0.3: + spec["definitions"] = {} + if rng.random() < 0.5: + spec[rng.choice(["security", "securityDefinitions"])] = [] + cases.append([spec]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/split_generic_params.py b/components/qemedia/upstream/qe_arena/corpus/split_generic_params.py new file mode 100644 index 0000000000000000000000000000000000000000..691f7000f53e51f7c27a6271eaf3d2a94d704c19 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/split_generic_params.py @@ -0,0 +1,59 @@ +"""Split a parameter list on top-level commas, respecting generics. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/parsers/multi-language-parser.ts (MIT).""" + +META = { + "entry": "split_generic_params", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/shared/parsers/multi-language-parser.ts", + "tags": ["parsing", "brackets"], + "domain": "software-engineering", +} + + +def split_generic_params(params): + """Split a function parameter list on commas that are not nested in <> or (). + + Depth starts at 0, increases on "<" or "(" and decreases on ">" or ")" with no + clamping, so an unmatched ">" (as in "=>") or ")" makes it negative. Only a comma + at depth exactly 0 ends the current parameter; all other characters (including + commas at any other depth) are kept. Each parameter is stripped of surrounding + whitespace before it is added. The trailing parameter is added only if it is + non-empty after stripping; every parameter ended by a comma is kept, even "". + """ + result = [] + depth = 0 + current = "" + for ch in params: + if ch == "<" or ch == "(": + depth += 1 + elif ch == ">" or ch == ")": + depth -= 1 + if ch == "," and depth == 0: + result.append(current.strip()) + current = "" + else: + current += ch + if current.strip(): + result.append(current.strip()) + return result + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [""], + [" "], + ["a"], + ["a, b"], + ["a,b,"], + [",a"], + ["a,,b"], + ["Map m, int n"], + ["f: (a, b) => c, d"], + ["List> x,y"], + ["a>b, c"], + ["x: Pair<(u, v), w>, y: T"], + ["a , b , c"], + ] + pieces = ["a", "b", "Map", "(x, y)", "List", ",", ", ", " ", "<", ">", "(", ")", "n: int"] + while len(cases) < n: + cases.append(["".join(rng.choice(pieces) for _ in range(rng.randint(1, 7)))[:40]]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/streamable_len.py b/components/qemedia/upstream/qe_arena/corpus/streamable_len.py new file mode 100644 index 0000000000000000000000000000000000000000..cf005ffcf80267411f9300deae3d1e3ab17dae7c --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/streamable_len.py @@ -0,0 +1,69 @@ +"""Measure how much generated text is safe to stream before a stop sequence. Ported from Rust; adapted from ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs (MIT).""" + +PRE_FIX = "ruvnet/RuVector@3e1d1886c50f2db817664648b95fab18e3e4c34b:crates/ruvllm/src/backends/candle_backend.rs" +META = { + "entry": "streamable_len", + "origin": "ruvnet/RuVector@32033a8bc0d4d92e0ea644fce98eef4bb5c6bfef:crates/ruvllm/src/backends/gguf_arch/mod.rs", + "tags": ["llm", "streaming", "utf-8"], + "domain": "software-engineering", + "real_faults": [ + {"id": "streamable_len/no-holdback", "kind": "missing-logic", "origin": PRE_FIX, + "summary": "streams everything settled, so the start of a stop sequence reaches the client", + "note": "reconstructed from the pre-fix streaming behaviour; the pre-fix code had no streamable_len", + "find": " end = max(settled - holdback, 0)\n", "replace": " end = settled\n"}, + {"id": "streamable_len/streams-pending-bytes", "kind": "missing-logic", "origin": PRE_FIX, + "summary": "a trailing incomplete UTF-8 sequence (U+FFFD) is streamed instead of held", + "note": "reconstructed from the pre-fix streaming behaviour; the pre-fix code had no streamable_len", + "find": " settled = len(text.rstrip(\"\\ufffd\").encode(\"utf-8\"))\n", + "replace": " settled = len(data)\n"}, + ], +} + + +def streamable_len(text, holdback): + """Return how many UTF-8 bytes at the start of text can be streamed now. + + A run of U+FFFD characters at the end of text is an incomplete UTF-8 sequence that + the next token may complete, so it is never streamed. Of the bytes before that run, + the last `holdback` bytes are also withheld, because they may start a stop sequence; + the pending U+FFFD bytes do not count toward the holdback. The cut never splits a + multi-byte character: it moves back to the start of that character. The result + counts UTF-8 bytes and is never negative. Raises ValueError if holdback < 0. + """ + if holdback < 0: + raise ValueError("holdback must be non-negative") + data = text.encode("utf-8") + settled = len(text.rstrip("\ufffd").encode("utf-8")) + end = max(settled - holdback, 0) + while end < len(data) and (data[end] & 0xC0) == 0x80: + end -= 1 + return end + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["", 0], + ["", 3], + ["ab\ufffd", 0], + ["abc", 2], + ["a\u00e9", 1], + ["ab\ufffd", 3], + ["abcd\ufffd", 3], + ["abc", 0], + ["abc", 3], + ["abc", 4], + ["\u20ac\u20ac", 1], + ["\u20ac\u20ac", 2], + ["x\ufffd\ufffd", 0], + ["\ufffd", 1], + ["abc", -1], + ] + alphabet = ["a", "b", " ", "\u00e9", "\u20ac", "\U0001f600", "z"] + while len(cases) < n: + text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 8))) + if rng.random() < 0.3: + text += "\ufffd" * rng.randint(1, 2) + holdback = 0 if rng.random() < 0.4 else rng.randint(1, 5) + cases.append([text, holdback]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/string_length_boundaries.py b/components/qemedia/upstream/qe_arena/corpus/string_length_boundaries.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd2eb7d833b5e395c2ed6db82fe3949acbd74cf --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/string_length_boundaries.py @@ -0,0 +1,57 @@ +"""List the invalid string lengths for a negative boundary test. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/functional_negative_agent.py (MIT).""" + +META = { + "entry": "string_length_boundaries", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/functional_negative_agent.py", + "tags": ["negative-testing", "boundary-values"], + "domain": "software-engineering", +} + + +def string_length_boundaries(min_length, max_length): + """Return the string lengths a negative test should send for a constrained parameter. + + Either bound may be None (unconstrained). If min_length is not None and > 0, add 0 + and then min_length - 1 (min_length - 1 is not added again when it equals 0). If + max_length is not None, add max_length + 1 and max_length + 100. Lengths are + returned in that order. Raises ValueError if a given bound is negative, or if both + are given and min_length > max_length. + """ + for bound in (min_length, max_length): + if bound is not None and bound < 0: + raise ValueError("bounds must be non-negative") + if min_length is not None and max_length is not None and min_length > max_length: + raise ValueError("min_length exceeds max_length") + lengths = [] + if min_length is not None and min_length > 0: + lengths.append(0) + if min_length - 1 > 0: + lengths.append(min_length - 1) + if max_length is not None: + lengths.append(max_length + 1) + lengths.append(max_length + 100) + return lengths + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [None, None], + [0, None], + [1, None], + [2, None], + [None, 0], + [None, 5], + [3, 3], + [3, 2], + [1, 1], + [0, 0], + [-1, None], + [None, -1], + [5, 40], + ] + while len(cases) < n: + low = rng.choice([None, rng.randint(0, 10)]) + high = rng.choice([None, rng.randint(0, 20)]) + cases.append([low, high]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/threshold_compliance.py b/components/qemedia/upstream/qe_arena/corpus/threshold_compliance.py new file mode 100644 index 0000000000000000000000000000000000000000..dd468da09321acc37a723b095f0cca0a5b803ad8 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/threshold_compliance.py @@ -0,0 +1,72 @@ +"""Check load-test metrics against configured performance thresholds. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/performance_agent.py (MIT).""" + +META = { + "entry": "threshold_compliance", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/orchestration_service/agents/performance_agent.py", + "tags": ["performance", "quality-gate"], + "domain": "software-engineering", +} + + +def threshold_compliance(metrics, thresholds): + """Check performance metrics against whichever thresholds are configured. + + metrics has integer keys: avg_ms, p95_ms, throughput_rps, success_pct, + failed_requests, total_requests. thresholds may contain any of + "avg_response_time_ms", "p95_response_time_ms", "throughput_rps", + "success_rate_percent", "error_rate_percent"; absent keys are not checked and do + not appear in the result. Result keys: "avg_response_time", "p95_response_time", + "throughput", "success_rate", "error_rate" mapped to bool. Latencies and the error + rate pass when <= their threshold; throughput and success rate pass when >= theirs. + error rate = failed_requests * 100 / total_requests, or 0 when total_requests is 0. + """ + compliance = {} + if "avg_response_time_ms" in thresholds: + compliance["avg_response_time"] = metrics["avg_ms"] <= thresholds["avg_response_time_ms"] + if "p95_response_time_ms" in thresholds: + compliance["p95_response_time"] = metrics["p95_ms"] <= thresholds["p95_response_time_ms"] + if "throughput_rps" in thresholds: + compliance["throughput"] = metrics["throughput_rps"] >= thresholds["throughput_rps"] + if "success_rate_percent" in thresholds: + compliance["success_rate"] = metrics["success_pct"] >= thresholds["success_rate_percent"] + if "error_rate_percent" in thresholds: + total = metrics["total_requests"] + error_rate = metrics["failed_requests"] * 100 / total if total > 0 else 0 + compliance["error_rate"] = error_rate <= thresholds["error_rate_percent"] + return compliance + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + def _metrics(avg, p95, rps, success, failed, total): + return {"avg_ms": avg, "p95_ms": p95, "throughput_rps": rps, + "success_pct": success, "failed_requests": failed, "total_requests": total} + + all_keys = {"avg_response_time_ms": 200, "p95_response_time_ms": 500, "throughput_rps": 50, + "success_rate_percent": 99, "error_rate_percent": 1} + cases = [ + [_metrics(100, 300, 60, 100, 0, 100), {}], + [_metrics(200, 500, 50, 99, 1, 100), all_keys], + [_metrics(201, 501, 49, 98, 2, 100), all_keys], + [_metrics(199, 499, 51, 100, 0, 100), all_keys], + [_metrics(0, 0, 0, 0, 0, 0), {"error_rate_percent": 0}], + [_metrics(0, 0, 0, 0, 1, 50), {"error_rate_percent": 2}], + [_metrics(0, 0, 0, 0, 3, 200), {"error_rate_percent": 1}], + [_metrics(0, 0, 0, 0, 1, 200), {"error_rate_percent": 0}], + [_metrics(0, 0, 0, 0, 1, 1), {"error_rate_percent": 50}], + [_metrics(150, 900, 10, 95, 5, 100), {"avg_response_time_ms": 150}], + [_metrics(150, 900, 10, 95, 5, 100), {"p95_response_time_ms": 900, "throughput_rps": 11}], + [_metrics(150, 900, 10, 95, 5, 100), {"success_rate_percent": 95, "error_rate_percent": 5}], + [_metrics(150, 900, 10, 95, 5, 100), {"success_rate_percent": 96, "error_rate_percent": 4}], + ] + keys = list(all_keys) + while len(cases) < n: + total = rng.randint(0, 200) + failed = rng.randint(0, total) if total else 0 + metrics = _metrics(rng.randint(50, 400), rng.randint(100, 900), rng.randint(0, 100), + rng.randint(80, 100), failed, total) + chosen = rng.sample(keys, rng.randint(1, 5)) + bounds = {"avg_response_time_ms": (50, 400), "p95_response_time_ms": (100, 900), + "throughput_rps": (0, 100), "success_rate_percent": (80, 100), "error_rate_percent": (0, 20)} + cases.append([metrics, {k: rng.randint(*bounds[k]) for k in chosen}]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/token_claims_check.py b/components/qemedia/upstream/qe_arena/corpus/token_claims_check.py new file mode 100644 index 0000000000000000000000000000000000000000..772546feafb527be12140a3d46be800db171a0a2 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/token_claims_check.py @@ -0,0 +1,67 @@ +"""Validate the time and audience claims of a decoded bearer token. Original.""" + +META = { + "entry": "token_claims_check", + "origin": "Original.", + "tags": ["security", "authentication", "tokens", "time-window"], + "domain": "cybersecurity", +} + + +def token_claims_check(claims, now, audience, leeway): + """Check a decoded token's time and audience claims (the signature was checked elsewhere). + + now and leeway are int seconds. Returns "ok" or the first failing reason in this order: + "malformed": "exp" is missing, or "exp", "nbf" or "iat" is present but not an int (a bool + is not an int); "expired": now >= exp + leeway; "not_yet_valid": "nbf" is present and + now + leeway < nbf; "issued_in_future": "iat" is present and iat > now + leeway; "audience": + "aud" is neither audience itself nor a list containing it. Raises ValueError if leeway < 0. + """ + if leeway < 0: + raise ValueError("leeway < 0") + if "exp" not in claims: + return "malformed" + for key in ("exp", "nbf", "iat"): + if key in claims and (isinstance(claims[key], bool) or not isinstance(claims[key], int)): + return "malformed" + if now >= claims["exp"] + leeway: + return "expired" + if "nbf" in claims and now + leeway < claims["nbf"]: + return "not_yet_valid" + if claims.get("iat", now) > now + leeway: + return "issued_in_future" + aud = claims.get("aud") + accepted = [aud] if isinstance(aud, str) else aud if isinstance(aud, list) else [] + if audience not in accepted: + return "audience" + return "ok" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + api = "api" + cases = [ + [{"exp": 200, "aud": api}, 100, api, 0], [{"aud": api}, 100, api, 0], + [{"exp": "200", "aud": api}, 100, api, 0], [{"exp": True, "aud": api}, 100, api, 0], + [{"exp": 200, "nbf": 1.5, "aud": api}, 100, api, 0], [{"exp": 200, "iat": None, "aud": api}, 100, api, 0], + [{"exp": 100, "aud": api}, 100, api, 0], [{"exp": 100, "aud": api}, 100, api, 1], + [{"exp": 99, "aud": api}, 100, api, 1], [{"exp": 200, "nbf": 101, "aud": api}, 100, api, 0], + [{"exp": 200, "nbf": 101, "aud": api}, 100, api, 1], [{"exp": 200, "nbf": 100, "aud": api}, 100, api, 0], + [{"exp": 200, "iat": 101, "aud": api}, 100, api, 0], [{"exp": 200, "iat": 101, "aud": api}, 100, api, 1], + [{"exp": 200, "iat": 100, "aud": api}, 100, api, 0], [{"exp": 200, "aud": "web"}, 100, api, 0], + [{"exp": 200, "aud": ["web", api]}, 100, api, 0], [{"exp": 200, "aud": ["web"]}, 100, api, 0], + [{"exp": 200}, 100, api, 0], [{"exp": 200, "aud": {"api": 1}}, 100, api, 0], + [{"exp": 200, "aud": "apis"}, 100, api, 0], [{"exp": 200, "aud": api}, 100, api, -1], + [{"exp": 50, "nbf": 300, "aud": "x"}, 100, api, 0], [{"exp": 200, "nbf": 300, "iat": 300}, 100, api, 0], + [{"exp": 200, "nbf": 0, "iat": 0, "aud": [api]}, 100, api, 0], + ] + while len(cases) < n: + now = rng.randint(100, 199) + claims = {"exp": now + rng.randint(-30, 60)} + for key in rng.sample(["nbf", "iat", "aud", "aud"], rng.randint(1, 3)): + if key == "aud": + claims[key] = rng.choice([api, "web", [api], ["web", api], ["web"], []]) + else: + claims[key] = now + rng.randint(-30, 30) + cases.append([claims, now, api, rng.choice([0, 0, 5, 30])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/token_jaccard.py b/components/qemedia/upstream/qe_arena/corpus/token_jaccard.py new file mode 100644 index 0000000000000000000000000000000000000000..c99834106d0b8c8df7af3494354bf9e646f98285 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/token_jaccard.py @@ -0,0 +1,51 @@ +"""Jaccard similarity of two texts over normalized word tokens. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/learning/qe-flywheel/corpus-scorer.ts (MIT).""" + +import re + +META = { + "entry": "token_jaccard", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/learning/qe-flywheel/corpus-scorer.ts", + "tags": ["similarity", "strings", "sets"], + "domain": "software-engineering", +} + + +def tokenize(text): + """Lowercase text and return the set of alphanumeric tokens of length >= 2.""" + return {tok for tok in re.split(r"[^a-z0-9]+", text.lower()) if len(tok) >= 2} + + +def token_jaccard(a, b): + """Return |A & B| / |A | B| over the token sets of a and b, rounded to 4 decimals. + + Tokens are maximal runs of [a-z0-9] after lowercasing; tokens shorter than 2 + characters are dropped. If both token sets are empty the result is 0.0. + """ + ta, tb = tokenize(a), tokenize(b) + if not ta and not tb: + return 0.0 + inter = len(ta & tb) + union = len(ta) + len(tb) - inter + return round(inter / union, 4) + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["", ""], + ["a b", "c"], + ["login", ""], + ["login", "LOGIN"], + ["login page", "login form"], + ["a login", "b login"], + ["test_user-42", "TEST user 42"], + ["x y z", "x"], + ["api timeout retry", "retry api timeout"], + ["flaky test in ci", "ci flaky"], + ["ab", "ab ab ab"], + ] + words = ["login", "api", "Timeout", "retry", "ci", "x", "test", "flaky", "db-01", "Error", "a"] + while len(cases) < n: + cases.append([" ".join(rng.choice(words) for _ in range(rng.randint(0, 5))), + " ".join(rng.choice(words) for _ in range(rng.randint(0, 5)))]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/trace_sampling_decision.py b/components/qemedia/upstream/qe_arena/corpus/trace_sampling_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..7c883e93c0da5f0d376eca37885e7ac8133a5849 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/trace_sampling_decision.py @@ -0,0 +1,60 @@ +"""Decide whether a tracing span is sampled. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/config/enhanced_tracing_config.py (MIT).""" + +META = { + "entry": "trace_sampling_decision", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/config/enhanced_tracing_config.py", + "tags": ["observability", "sampling"], + "domain": "software-engineering", +} + + +def trace_sampling_decision(span_name, trace_id, has_error, base_rate_pct, parent_sampled): + """Return True if the span should be recorded. Rules are applied in order: + + 1. has_error is True -> True. + 2. span_name is exactly "/health", "/metrics" or "health_check" -> False. + 3. span_name contains any critical operation ("generate_tests", "execute_agent", + "analyze_spec", "authenticate") -> trace_id % 100 < min(base_rate_pct * 5, 100). + 4. parent_sampled is True or False -> that value. + 5. Otherwise (parent_sampled is None) -> trace_id % 100 < base_rate_pct. + trace_id is a non-negative int and base_rate_pct an int percentage. + """ + if has_error: + return True + if span_name in ("/health", "/metrics", "health_check"): + return False + critical = ("generate_tests", "execute_agent", "analyze_spec", "authenticate") + if any(op in span_name for op in critical): + return trace_id % 100 < min(base_rate_pct * 5, 100) + if parent_sampled is not None: + return parent_sampled + return trace_id % 100 < base_rate_pct + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + ["/health", 0, True, 10, False], + ["/health", 0, False, 10, True], + ["/metrics", 5, False, 100, None], + ["health_check", 1, False, 50, None], + ["/healthz", 1, False, 50, None], + ["generate_tests", 49, False, 10, False], + ["generate_tests", 50, False, 10, True], + ["run:execute_agent", 149, False, 10, None], + ["analyze_spec", 199, False, 30, None], + ["authenticate_user", 99, False, 20, None], + ["authenticate_user", 100, False, 0, True], + ["list_users", 5, False, 10, True], + ["list_users", 5, False, 10, False], + ["list_users", 9, False, 10, None], + ["list_users", 10, False, 10, None], + ["list_users", 110, False, 10, None], + ["list_users", 299, False, 100, None], + ] + names = ["generate_tests", "execute_agent", "analyze_spec", "authenticate", "/health", + "/metrics", "list_users", "get_spec", "health_check", "db.query"] + while len(cases) < n: + cases.append([rng.choice(names), rng.randint(0, 999), rng.random() < 0.15, + rng.randint(0, 30), rng.choice([None, True, False])]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/truncate_to_token_budget.py b/components/qemedia/upstream/qe_arena/corpus/truncate_to_token_budget.py new file mode 100644 index 0000000000000000000000000000000000000000..7589124c49ca8d41e5bd67c4e01bedf82a8afb2f --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/truncate_to_token_budget.py @@ -0,0 +1,68 @@ +"""Truncate a prompt to fit a token budget with a binary search. Adapted from proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/llm_providers/utils/token_counter.py (MIT).""" + +META = { + "entry": "truncate_to_token_budget", + "origin": "proffesor-for-testing/sentinel-api-testing@704f47fbc4d2d75ed9261f9a602d76aea930d01b:sentinel_backend/llm_providers/utils/token_counter.py", + "tags": ["llm", "strings", "binary-search"], + "domain": "software-engineering", +} + + +def estimate_tokens(text): + """Approximate token count: one token per 4 characters, rounded up.""" + return (len(text) + 3) // 4 + + +def truncate_to_token_budget(text, max_tokens): + """Return text truncated so that its estimated token count fits max_tokens. + + estimate_tokens(s) is ceil(len(s) / 4). If estimate_tokens(text) <= max_tokens the + text is returned unchanged. Otherwise the longest prefix p with + estimate_tokens(p) <= max_tokens is found and p + "..." is returned. If that prefix + is empty (max_tokens == 0), the result is text[:10] + "...". + Raises ValueError if max_tokens is negative. + """ + if max_tokens < 0: + raise ValueError("max_tokens must be non-negative") + if estimate_tokens(text) <= max_tokens: + return text + left, right = 0, len(text) + result = "" + while left < right: + mid = (left + right + 1) // 2 + if estimate_tokens(text[:mid]) <= max_tokens: + result = text[:mid] + left = mid + else: + right = mid - 1 + return result + "..." if result else text[:10] + "..." + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" + sample = "abcdefghijklmnopqrstuvwxyz0123456789ABCD" + cases = [ + ["", 0], + ["", 3], + ["abc", 0], + ["abcd", 1], + ["abcde", 1], + ["abcdefgh", 1], + ["abcdefgh", 2], + ["abcdefghi", 2], + [sample[:12], 2], + [sample[:13], 3], + [sample[:16], 3], + [sample[:17], 4], + [sample, 9], + [sample, 10], + [sample, 1], + [sample[:11], 0], + ["abc", -1], + ] + while len(cases) < n: + length = rng.randint(0, 40) + text = "".join(rng.choice(alphabet) for _ in range(length)) + cases.append([text, rng.randint(0, 11)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/uncovered_line_ranges.py b/components/qemedia/upstream/qe_arena/corpus/uncovered_line_ranges.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1154d344bac801231743bdebf327219ab6b2fc --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/uncovered_line_ranges.py @@ -0,0 +1,53 @@ +"""Collapse uncovered line numbers into contiguous ranges. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/coverage-analysis/services/coverage-parser.ts (MIT).""" + +META = { + "entry": "uncovered_line_ranges", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/coverage-analysis/services/coverage-parser.ts", + "tags": ["coverage", "ranges"], + "domain": "software-engineering", +} + + +def uncovered_line_ranges(lines): + """Group uncovered line numbers into inclusive [start, end] ranges. + + The input may be unsorted and contain duplicates; it is deduplicated and sorted + first. Consecutive numbers (each exactly one more than the previous) form one range. + A single isolated line n becomes [n, n]. An empty list returns []. + Raises ValueError if any line number is less than 1. + """ + if any(line < 1 for line in lines): + raise ValueError("line numbers start at 1") + ordered = sorted(set(lines)) + if not ordered: + return [] + ranges = [] + start = prev = ordered[0] + for line in ordered[1:]: + if line == prev + 1: + prev = line + else: + ranges.append([start, prev]) + start = prev = line + ranges.append([start, prev]) + return ranges + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [[]], + [[1]], + [[1, 2]], + [[1, 3]], + [[3, 2, 1]], + [[5, 5, 6]], + [[1, 2, 4, 5, 7]], + [[10, 12, 11, 20, 21, 30]], + [[2, 4, 6, 8]], + [[0, 1]], + [[1, 2, 3, 5, 6, 7, 9]], + ] + while len(cases) < n: + cases.append([[rng.randint(1, 25) for _ in range(rng.randint(1, 12))]]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/validate_csv_row.py b/components/qemedia/upstream/qe_arena/corpus/validate_csv_row.py new file mode 100644 index 0000000000000000000000000000000000000000..8693043436409df4d8ad9bd4192a5c9c9bf98fe4 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/validate_csv_row.py @@ -0,0 +1,70 @@ +"""Validate one invoice-line CSV row against its column schema and list the problems. Original.""" + +META = { + "entry": "validate_csv_row", + "origin": "Original.", + "tags": ["csv", "validation", "data-entry"], + "domain": "office-white-collar", +} + + +def validate_csv_row(row): + """Check a CSV row of str cells [ref, qty, note]; return its problems in column order. + + A row without exactly 3 cells gives ["bad width"]. Each cell is stripped of " " first. + ref (required text, 3-8 chars), qty (required int, 1-500), note (optional text, 2-12 + chars). Per cell at most one problem: blank required cell: ": required"; qty that + is not an optional "-" plus digits 0-9: "qty: not int", else outside 1-500: "qty: range"; + text length outside its range: ": length". Raises TypeError for a non-str cell. + """ + if len(row) != 3: + return ["bad width"] + problems = [] + for cell, (name, low, high) in zip(row, [("ref", 3, 8), ("qty", 1, 500), ("note", 2, 12)]): + if not isinstance(cell, str): + raise TypeError("cells must be str") + value = cell.strip(" ") + if not value: + if name != "note": + problems.append(name + ": required") + elif name != "qty": + if not low <= len(value) <= high: + problems.append(name + ": length") + else: + digits = value[1:] if value[:1] == "-" else value + if not digits or any(c not in "0123456789" for c in digits): + problems.append("qty: not int") + elif not low <= int(value) <= high: + problems.append("qty: range") + return problems + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [ + [["INV-1", "12", "rush"]], + [["INV", "1", "ok"]], + [["INVOICE1", "500", "twelve chars"]], + [["IN", "0", "thirteen char"]], + [["INVOICE12", "501", "x"]], + [[" INV-2 ", " 7 ", " "]], + [["", "", ""]], + [["INV-3", "-", "ab"]], + [["INV-4", "1.5", "ab"]], + [["INV-5", "+3", "ab"]], + [["INV-6", "-5", "ab"]], + [["INV-7", "--2", "ab"]], + [["INV-8", "3"]], + [["INV-9", 12, ""]], + [[]], + [["A", "2", "", "x"]], + ] + refs = ["", " ", "AB", "ABC", "INV-77", "INVOICE9", "INVOICE10"] + qtys = ["", "-", "0", "1", "7", "250", "500", "501", "-3", "1x", " 42 "] + notes = ["", "x", "ok", "rush", "call first", "twelve chars", "thirteen char"] + while len(cases) < n: + row = [rng.choice(refs), rng.choice(qtys), rng.choice(notes)] + if rng.random() < 0.08: + row = row[:rng.randint(0, 2)] + cases.append([row]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/vuln_priority_bucket.py b/components/qemedia/upstream/qe_arena/corpus/vuln_priority_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..cd2aa254ca8e3805aa9f298b98705f55f716b8dd --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/vuln_priority_bucket.py @@ -0,0 +1,40 @@ +"""Triage a vulnerability into a remediation time bucket. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/security-compliance/services/security-auditor-reports.ts (MIT).""" + +META = { + "entry": "vuln_priority_bucket", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/security-compliance/services/security-auditor-reports.ts", + "tags": ["security", "triage"], + "domain": "software-engineering", +} + + +def vuln_priority_bucket(severity, effort): + """Return the remediation bucket for a vulnerability. + + severity is case-sensitive; effort is one of "trivial", "minor", "moderate", "major". + - "critical" -> "immediate" + - "high" -> "immediate" if effort is "trivial" or "minor", else "short_term" + - "medium" -> "long_term" if effort is "major", else "medium_term" + - "low" or "informational" -> "long_term" + - any other severity -> "accepted" + """ + if severity == "critical": + return "immediate" + if severity == "high": + return "immediate" if effort == "trivial" or effort == "minor" else "short_term" + if severity == "medium": + return "long_term" if effort == "major" else "medium_term" + if severity == "low" or severity == "informational": + return "long_term" + return "accepted" + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + severities = ["critical", "high", "medium", "low", "informational", "unknown", "High"] + efforts = ["trivial", "minor", "moderate", "major"] + cases = [[s, e] for s in severities[:5] for e in efforts] + cases += [["unknown", "major"], ["High", "trivial"], ["", "minor"]] + while len(cases) < n: + cases.append([rng.choice(severities), rng.choice(efforts)]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/corpus/wilson_interval.py b/components/qemedia/upstream/qe_arena/corpus/wilson_interval.py new file mode 100644 index 0000000000000000000000000000000000000000..bba750bee3975ea294f6a58b596508468e070f4a --- /dev/null +++ b/components/qemedia/upstream/qe_arena/corpus/wilson_interval.py @@ -0,0 +1,43 @@ +"""Compute a 95% Wilson score interval for a pass rate. Ported from TypeScript; adapted from proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/chaos-resilience/diagnosis/scorer.ts (MIT).""" + +import math + +META = { + "entry": "wilson_interval", + "origin": "proffesor-for-testing/agentic-qe@214a5bc881fe4ad6324e243c9d9c2c24baae5295:src/domains/chaos-resilience/diagnosis/scorer.ts", + "tags": ["statistics", "confidence-interval"], + "domain": "software-engineering", +} + + +def wilson_interval(successes, total): + """Return the 95% Wilson score interval [low, high] for successes out of total. + + With z = 1.96 and p = successes / total: + denominator = 1 + z*z / total + center = (p + z*z / (2 * total)) / denominator + margin = (z / denominator) * sqrt(p * (1 - p) / total + z*z / (4 * total * total)) + low = max(0.0, center - margin), high = min(1.0, center + margin), each a float + rounded to 4 decimals. total == 0 returns [0.0, 0.0]. + Raises ValueError if successes < 0 or successes > total. + """ + if successes < 0 or successes > total: + raise ValueError("successes must be within 0..total") + if total == 0: + return [0.0, 0.0] + z = 1.96 + p = successes / total + denominator = 1 + z * z / total + center = (p + z * z / (2 * total)) / denominator + margin = (z / denominator) * math.sqrt(p * (1 - p) / total + z * z / (4 * total * total)) + return [round(max(0.0, center - margin), 4), round(min(1.0, center + margin), 4)] + + +def gen_inputs(rng, n): + """Return exactly n argument lists: boundary cases first, then rng-driven cases.""" + cases = [[0, 0], [0, 1], [1, 1], [0, 10], [10, 10], [5, 10], [1, 2], [9, 10], + [50, 100], [99, 100], [3, 7], [-1, 5], [6, 5]] + while len(cases) < n: + total = rng.randint(1, 200) + cases.append([rng.randint(0, total), total]) + return cases[:n] diff --git a/components/qemedia/upstream/qe_arena/domains.py b/components/qemedia/upstream/qe_arena/domains.py new file mode 100644 index 0000000000000000000000000000000000000000..321b47be5fbac6658a1aaf822c8388e38cbbc8f2 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/domains.py @@ -0,0 +1,25 @@ +"""Arena domains and the task-ID slugs that scope a task cell to one of them. + +Dependency-free so tooling outside the image (scripts/qe_flywheel) can read it without the sandbox. + +Every corpus entry names its domain in ``META["domain"]``, spelled as the arena leaderboard spells it. +A task ID without a slug (``qe_mutant_kill-d2``) is the software-engineering cell, exactly as before +domains existed; ``qe_mutant_kill-finance-d2`` draws only finance-economics entries. +""" + +from __future__ import annotations + +SOFTWARE = "software-engineering" +DOMAINS = (SOFTWARE, "industrial-physical-systems", "natural-science", "office-white-collar", + "finance-economics", "mathematics-or-formal-reasoning", "cybersecurity", "media-content-production") +# Task-ID slug per domain. Software engineering has none: its cells keep their original IDs. +SLUGS = { + "industrial-physical-systems": "industrial", + "natural-science": "science", + "office-white-collar": "office", + "finance-economics": "finance", + "mathematics-or-formal-reasoning": "math", + "cybersecurity": "security", + "media-content-production": "media", +} +BY_SLUG = {slug: domain for domain, slug in SLUGS.items()} diff --git a/components/qemedia/upstream/qe_arena/edit_budget.py b/components/qemedia/upstream/qe_arena/edit_budget.py new file mode 100644 index 0000000000000000000000000000000000000000..fab246b5adee01a4b98196945670ae7ca2993c5d --- /dev/null +++ b/components/qemedia/upstream/qe_arena/edit_budget.py @@ -0,0 +1,532 @@ +"""qe_bugfix-d4: an edit budget plus a structural gate, so only a localised repair can pass. + +Budget. BUDGET_SHARE of the shown file's length, rounded up to BUDGET_QUANTUM characters, counted as +len(old) + len(new) over all edits. It depends on the shown file only, so the number says nothing +about the faults. A budget computed from the faults (the 1.5x line-diff prototype) would have told the +model how large the faulty code is. A task is served only if the character-level minimal fix fits. + +Gate. A budget alone does not stop a rewrite: a minified copy of the function appended after the +old one, or placed before it behind an early return, fits in a few hundred characters (review of +dd32587). Every edit, and the graded file, must keep the buggy file's structure: +- the same top-level statements in the same order, and the same function definitions (names, + arguments, decorators), so there is no shadow definition and no new top-level code; +- no lambda beyond those already in the file; +- every statement stays reachable (a static check that proves exits through returns, raises, + if/else, try/finally, with, and loops that must run their body), and no branch or loop tests a + constant or a tautology such as `p == p`, so no wrapper can bypass the old body; +- at most change_allowance(buggy) syntax tokens changed against the buggy file (a sequence diff of + the AST in preorder): CHANGE_SHARE of the file's code tokens, capped at MAX_CHANGE. It depends on + the shown file only, so the gate reveals nothing about the faults. A compact re-implementation of a + function needs more tokens than that, even behind an always-true guard. +""" + +from __future__ import annotations + +import ast +import builtins +import difflib +import math +from collections import Counter + +BUDGET_SHARE = 0.25 +BUDGET_QUANTUM = 25 # characters +MERGE_GAP = 16 # character hunks closer than this become one edit +CHANGE_SHARE = 0.35 # of the shown file's code tokens (docstrings excluded) +MAX_CHANGE = 50 # AST tokens + + +# --------------------------------------------------------------------------- the minimal fix + +def _char_hunks(buggy: str, original: str) -> list[list[int]]: + ops = [op for op in difflib.SequenceMatcher(None, buggy, original, autojunk=False).get_opcodes() + if op[0] != "equal"] + merged: list[list[int]] = [] + for _, i1, i2, j1, j2 in ops: + if merged and i1 - merged[-1][1] < MERGE_GAP: + merged[-1][1], merged[-1][3] = i2, j2 + else: + merged.append([i1, i2, j1, j2]) + return merged + + +def minimal_fix(buggy: str, original: str) -> list[dict]: + """Character-level edits, applied in order, that turn ``buggy`` into ``original``. + + Changes closer than MERGE_GAP characters form one edit. Edits run last to first, and each is + widened one character at a time on both sides until its ``old`` occurs exactly once in the file + as it stands when that edit is applied. + """ + current = buggy + edits = [] + for i1, i2, j1, j2 in reversed(_char_hunks(buggy, original)): + lo, hi = i1, i2 + while not (current[lo:hi] and current.count(current[lo:hi]) == 1): + if lo == 0 and hi == len(current): + break + lo, hi = max(0, lo - 1), min(len(current), hi + 1) + new = current[lo:i1] + original[j1:j2] + current[i2:hi] + edits.append({"old": current[lo:hi], "new": new}) + current = current[:lo] + new + current[hi:] + if current != original: # pragma: no cover - defensive invariant + raise AssertionError("minimal_fix does not restore the original") + return edits + + +def edit_cost(edit: dict) -> int: + return len(edit["old"]) + len(edit["new"]) + + +def fix_cost(buggy: str, original: str) -> int: + return sum(edit_cost(e) for e in minimal_fix(buggy, original)) + + +def budget_for(shown: str) -> int: + """The budget for a file: a function of the shown text only, never of the faults.""" + raw = math.ceil(BUDGET_SHARE * len(shown)) + return -(-raw // BUDGET_QUANTUM) * BUDGET_QUANTUM + + +# --------------------------------------------------------------------------- the structural gate + +def _tokens(node: ast.AST) -> list[str]: + """Preorder AST tokens: node types plus identifiers, constants and operators.""" + out = [type(node).__name__] + for name in ("id", "arg", "attr", "name", "module"): + value = getattr(node, name, None) + if isinstance(value, str): + out.append(f"{name}={value}") + if isinstance(node, ast.Constant): + out.append(f"const={node.value!r}") + for child in ast.iter_child_nodes(node): + out.extend(_tokens(child)) + return out + + +def change_size(buggy: str, candidate: str) -> int: + """Tokens inserted plus tokens deleted between the two files' preorder AST token sequences.""" + a, b = _tokens(ast.parse(buggy)), _tokens(ast.parse(candidate)) + matched = sum(block.size for block in difflib.SequenceMatcher(None, a, b, autojunk=False).get_matching_blocks()) + return len(a) + len(b) - 2 * matched + + +def code_tokens(source: str) -> int: + """Preorder AST tokens of ``source`` with docstrings left out.""" + tree = ast.parse(source) + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and ast.get_docstring(node) is not None: + node.body = node.body[1:] or [ast.Pass()] + return len(_tokens(tree)) + + +def change_allowance(shown: str) -> int: + return min(MAX_CHANGE, int(CHANGE_SHARE * code_tokens(shown))) + + +def _top_level(tree: ast.Module) -> list[tuple]: + return [(type(n).__name__, getattr(n, "name", None), ast.dump(n) if isinstance(n, (ast.Import, ast.ImportFrom)) else None) + for n in tree.body] + + +def _definitions(tree: ast.AST) -> list[tuple]: + return [(n.name, ast.dump(n.args), [ast.dump(d) for d in n.decorator_list]) + for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))] + + +FIXED = "fixed" # a test whose value cannot depend on the input, but which we do not evaluate + + +def _truth(test: ast.AST, bound: frozenset = frozenset()) -> bool | str | None: + """The truth value of ``test`` when it cannot depend on the input, FIXED when it cannot depend on + the input but its value is not computed here, else None. + + Tautologies are open-ended: this catches the shapes a rewrite needs to hide behind, and the + token allowance bounds the rest. Caught: literals and displays (`{0}`, `()`, f-strings), + anything with no variable in it (builtins and module dunders such as `__name__` are not + variables), a bare builtin such as `zip` (when no name in the file shadows it), a walrus by its + value, `x OP x`, `x or not x`, `x in (x,)`, `x in ()`, `x is []`, `x or ` / + `x and `, `isinstance(_, object)`, `len(...) >= 0`, a call to a builtin whose result is + truthy whatever the argument (`type(x)`, `repr(x)`, `ValueError(x)`, see _TRUTHY_CALLS) or always + None (`print(x)`), a special method such as `x.__eq__`, a generator expression, and + `a if x else b` with a and b of the same truth. ``bound`` is from _bound_names: every name the + file binds as a variable, plus OBJECT + name for a name bound only by def, class or import. + """ + if isinstance(test, ast.NamedExpr): + return _truth(test.value, bound) # (q := re) is as true as re + if isinstance(test, ast.Name) and (OBJECT + test.id in bound or (test.id in _BUILTINS and test.id not in bound)): + return True # a function, class, module or builtin object is always truthy + if isinstance(test, (ast.Set, ast.List, ast.Tuple, ast.Dict)): + items = test.keys if isinstance(test, ast.Dict) else test.elts + if not items or any(i is not None and not isinstance(i, ast.Starred) for i in items): + return bool(items) # `[*x]` and `{**x}` are as empty as x: decided below + # Every item unpacks something: non-empty when an unpacked value is a literal known to have items + # (`[*[a]]`, `{**{a: 0}}`, `[*'ab']`). Never because the value is truthy: an iterator, generator, + # zip, map or filter object is always truthy and may yield nothing. + unpacked = test.values if isinstance(test, ast.Dict) else [i.value for i in items] + if any(_has_items(v, bound) for v in unpacked): + return True + if isinstance(test, ast.JoinedStr): + if any(isinstance(v, ast.Constant) and v.value for v in test.values): + return True + return None if any(isinstance(v, ast.FormattedValue) for v in test.values) else False + if not _reads_input(test, bound): + try: + return bool(ast.literal_eval(test)) + except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError): + return FIXED # no variable in it: fixed, but not evaluated here (never run model code) + if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not): + inner = _truth(test.operand, bound) + return inner if inner is None or inner == FIXED else not inner + if isinstance(test, ast.BoolOp): + values = [_truth(v, bound) for v in test.values] + decisive = True if isinstance(test.op, ast.Or) else False + if decisive in values: + return decisive + dumps = [ast.dump(v) for v in test.values] + negated = {ast.dump(v.operand) for v in test.values if isinstance(v, ast.UnaryOp) and isinstance(v.op, ast.Not)} + if negated & set(dumps): + return decisive # x or not x is always true; x and not x is always false + if decisive is True and FIXED in values: + return FIXED # x or : still refused as constant, as when counted as true + if None in values: + return None + return FIXED if FIXED in values else not decisive + if isinstance(test, ast.Compare) and len(test.ops) == 1: + left, op, right = test.left, test.ops[0], test.comparators[0] + if isinstance(op, (ast.Is, ast.IsNot)) and (isinstance(left, _FRESH) or isinstance(right, _FRESH)): + return isinstance(op, ast.IsNot) # a new list, dict, set or generator is nothing else + if ast.dump(left) == ast.dump(right): + if isinstance(op, (ast.In, ast.NotIn)): + return None # x in x is not fixed for lists + return isinstance(op, (ast.Eq, ast.Is, ast.LtE, ast.GtE)) + if isinstance(op, (ast.In, ast.NotIn)) and isinstance(right, (ast.Tuple, ast.List, ast.Set, ast.Dict)): + items = right.keys if isinstance(right, ast.Dict) else right.elts + if not items: + return isinstance(op, ast.NotIn) # nothing is in an empty display + if any(e is not None and ast.dump(e) == ast.dump(left) for e in items): # None: a `**d` key + return isinstance(op, ast.In) # x in (x,) is always true + if _is_len(left) and _int_value(right) is not None: + limit = _int_value(right) + if (isinstance(op, ast.GtE) and limit <= 0) or (isinstance(op, ast.Gt) and limit < 0): + return True + if _is_len(right) and _int_value(left) is not None: + limit = _int_value(left) + if (isinstance(op, ast.LtE) and limit <= 0) or (isinstance(op, ast.Lt) and limit < 0): + return True + if (isinstance(test, ast.Call) and isinstance(test.func, ast.Name) and test.func.id in ("isinstance", "issubclass") + and len(test.args) == 2 and _is_object(test.args[1])): + return True # everything is an object + if isinstance(test, ast.Call) and isinstance(test.func, ast.Name) and _builtin(test.func.id, bound): + name, args = test.func.id, test.args + if name in _NONE_CALLS: + return False + if name in _TRUTHY_CALLS and not (name in _SCOPE_READERS and not args) and _trusted(name, bound): + return True + if name in _SCOPE_READERS and not args and not test.keywords: + return FIXED # the names bound in this scope: never what a repair tests + if name == "bool" and len(args) == 1: + return _truth(args[0], bound) + if name in ("getattr", "hasattr") and len(args) == 2 and isinstance(args[1], ast.Constant) \ + and args[1].value in (_SPECIAL_METHODS if name == "getattr" else _OBJECT_ATTRIBUTES) \ + and _trusted(args[1].value, bound): + return True # getattr(x, "__class__") is x.__class__; every object has what object has + if isinstance(test, ast.Attribute) and test.attr in _SPECIAL_METHODS and _trusted(test.attr, bound): + return True # x.__class__ is a class and x.__eq__ a bound method, whatever x is + if isinstance(test, ast.GeneratorExp): + return True # a generator object is always truthy + if isinstance(test, ast.IfExp): + body, orelse = _truth(test.body, bound), _truth(test.orelse, bound) + if isinstance(body, bool) and body is orelse: + return body + return None + + +_BUILTINS = frozenset(n for n in dir(builtins) if not n.startswith("_")) +_FRAME_READERS = frozenset({"eval", "exec"}) # read any variable named in a string +_SCOPE_READERS = frozenset({"globals", "locals", "vars", "dir"}) # read the variables in scope when called bare +_OBJECT_ATTRIBUTES = frozenset(dir(object)) +_FRESH = (ast.List, ast.Dict, ast.Set, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) +# Builtin calls whose result is truthy for every argument they accept: a builtin class whose instances +# define neither __bool__ nor __len__ (type, object, zip, ValueError, ...), a positive id, a repr or +# ascii (never empty), an iterator, a non-empty dir(x), and the module globals (never empty). +_TRUTHY_CALLS = frozenset(name for name, value in vars(builtins).items() if isinstance(value, type) + and not hasattr(value, "__bool__") and not hasattr(value, "__len__")) \ + | {"id", "repr", "ascii", "iter", "dir", "globals"} +_NONE_CALLS = frozenset({"print", "setattr", "delattr", "exec"}) # always return None +# Special methods a class in the file could define so that the builtin above returns a falsy value. +_DELEGATES = {"type": ("__bool__", "__len__"), "__class__": ("__bool__", "__len__"), + "repr": ("__repr__",), "ascii": ("__repr__",), "dir": ("__dir__",), + "iter": ("__iter__", "__bool__", "__len__"), "reversed": ("__reversed__", "__bool__", "__len__")} + + +def _special_methods() -> frozenset: + """Special methods callable on every builtin type that has them: looked up on any object, each is a + bound method or (__class__) a class, so always truthy. __hash__ is None on unhashable types, and + data attributes such as __doc__ or __name__ vary, so neither is here.""" + kinds = [v for v in vars(builtins).values() if isinstance(v, type)] + [type(None), type(len), type(_special_methods)] + names = {n for kind in kinds for n in dir(kind) if n.startswith("__") and n.endswith("__")} + owners = {n: [kind for kind in kinds if hasattr(kind, n)] for n in names} + return frozenset(n for n in names if owners[n] and all(callable(getattr(kind, n)) for kind in owners[n])) + + +_SPECIAL_METHODS = _special_methods() + + +def _is_dunder(name: str) -> bool: + return len(name) > 4 and name.startswith("__") and name.endswith("__") + + +def _fixed_name(name: str, bound: frozenset) -> bool: + """A name that cannot carry the input: a def, class or import object, a builtin no name in the file + shadows (except those that read variables by name), or a module dunder such as __name__.""" + if name in bound: + return False + if OBJECT + name in bound: + return True + return (name in vars(builtins) and name not in _FRAME_READERS) or _is_dunder(name) + + +def _reads_input(test: ast.AST, bound: frozenset) -> bool: + """Whether ``test`` can see the input: a name that is not fixed, or a bare `locals()` or `vars()`.""" + for node in ast.walk(test): + if isinstance(node, ast.Name) and not _fixed_name(node.id, bound): + return True + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _SCOPE_READERS \ + and not node.args and not node.keywords and _builtin(node.func.id, bound): + return True + return False + + +def _is_object(node: ast.AST) -> bool: + """`object`, or a tuple display that names it (isinstance(x, (int, object))).""" + if isinstance(node, ast.Tuple): + return any(_is_object(e) for e in node.elts) + return isinstance(node, ast.Name) and node.id == "object" + + +def _builtin(name: str, bound: frozenset) -> bool: + return name in vars(builtins) and name not in bound and OBJECT + name not in bound + + +def _trusted(name: str, bound: frozenset) -> bool: + """No function in the file defines a special method that could make ``name``'s result falsy.""" + return not any(m in bound or OBJECT + m in bound for m in _DELEGATES.get(name, ())) + + +def _has_items(node: ast.AST, bound: frozenset) -> bool: + """A literal that yields at least one item when unpacked: a non-empty display, str or bytes.""" + if isinstance(node, (ast.List, ast.Tuple, ast.Set, ast.Dict)): + return _truth(node, bound) is True + if isinstance(node, ast.Constant) and isinstance(node.value, (str, bytes)): + return bool(node.value) + if isinstance(node, ast.JoinedStr): + return any(isinstance(v, ast.Constant) and v.value for v in node.values) + return False + + +def _is_len(node: ast.AST) -> bool: + return isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "len" + + +def _int_value(node: ast.AST) -> int | None: + try: + value = ast.literal_eval(node) + except (ValueError, TypeError, SyntaxError): + return None + return value if type(value) is int else None + + +def _constant_test(test: ast.AST, bound: frozenset = frozenset()) -> bool: + """A test whose value does not depend on the input (see _truth).""" + return _truth(test, bound) is not None + + +OBJECT = "object:" # prefix in _bound_names for a name that only def, class or import binds + + +def _bound_names(tree: ast.AST) -> frozenset: + """Names the file binds as variables, plus OBJECT + name for each name bound only by def, class or + import: always a truthy object, so `if tokenize:` or `if re:` is as constant as `if {0}:`. A name + that is also assigned, a parameter, a loop or with/except target, deleted, or declared global or + nonlocal anywhere stays a variable.""" + variables, objects = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)): + variables.add(node.id) # assignment, augmented, walrus, for/with/comprehension target, del + elif isinstance(node, ast.arg): + variables.add(node.arg) + elif isinstance(node, (ast.Global, ast.Nonlocal)): + variables.update(node.names) + elif isinstance(node, ast.ExceptHandler) and node.name: + variables.add(node.name) + elif isinstance(node, (ast.MatchAs, ast.MatchStar)) and node.name: + variables.add(node.name) + elif isinstance(node, ast.MatchMapping) and node.rest: + variables.add(node.rest) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + objects.add(node.name) + elif isinstance(node, ast.alias): + objects.add((node.asname or node.name).split(".")[0]) + return frozenset(variables | {OBJECT + name for name in objects - variables}) + + +_RUNS = ("range", "zip", "sorted", "reversed", "list", "tuple", "enumerate", "str", "set", "map", "filter") + + +def _must_iterate(node: ast.AST, bound: frozenset) -> bool: + """A for-loop iterable that is certainly non-empty: a non-empty literal, or a builtin over literals.""" + if _nonempty_literal(node): + return True + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _RUNS + and node.func.id not in bound and OBJECT + node.func.id not in bound and not node.keywords): + try: + args = [ast.literal_eval(a) for a in node.args] + except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError): + return False + try: + if node.func.id == "range": + return all(type(a) is int and abs(a) < 10**9 for a in args) and len(range(*args)) > 0 + if node.func.id in ("map", "filter"): + return False # needs a function; never a plain wrapper + if any(not isinstance(a, (str, bytes, list, tuple, set, dict)) for a in args) or len(str(args)) > 1000: + return False + return len(list(getattr(builtins, node.func.id)(*args))) > 0 + except Exception: # noqa: BLE001 - a call that fails on literals is not a wrapper we can prove + return False + return False + + +def _loop_body_jumps_out(body: list[ast.stmt]) -> bool: + """A break that leaves this loop (not one inside a nested loop or function).""" + stack = list(body) + while stack: + node = stack.pop() + if isinstance(node, ast.Break): + return True + if isinstance(node, (ast.For, ast.AsyncFor, ast.While, ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + continue + stack.extend(ast.iter_child_nodes(node)) + return False + + +def _nonempty_literal(node: ast.AST) -> bool: + if isinstance(node, (ast.List, ast.Tuple, ast.Set)): + return bool(node.elts) + if isinstance(node, ast.Constant) and isinstance(node.value, (str, bytes)): + return bool(node.value) + return False + + +def _ends(block: list[ast.stmt], jumps: bool, bound: frozenset = frozenset()) -> bool: + """True if control can never fall off the end of ``block``. + + ``jumps`` says whether break/continue end it (they do inside a loop body). The analysis is + sound for exits it proves: a return, a raise, an if with every branch ending, a try whose + body and handlers end or whose finally ends, a with whose body ends, and a loop that must run + its body (a constant-true while, a for over a non-empty literal) with a body that ends and + no break. A branch on a test that is not constant may go either way. + """ + return any(_stmt_ends(stmt, jumps, bound) for stmt in block) + + +def _stmt_ends(stmt: ast.stmt, jumps: bool, bound: frozenset = frozenset()) -> bool: + if isinstance(stmt, (ast.Return, ast.Raise)): + return True + if isinstance(stmt, (ast.Break, ast.Continue)): + return jumps + if isinstance(stmt, ast.If): + value = _truth(stmt.test, bound) + if value is True: + return _ends(stmt.body, jumps, bound) + if value is False: + return _ends(stmt.orelse, jumps, bound) # the body never runs: `if x > x:` cannot end the block + if value == FIXED: + return _ends(stmt.body, jumps, bound) or _ends(stmt.orelse, jumps, bound) # either may be live + return bool(stmt.orelse) and _ends(stmt.body, jumps, bound) and _ends(stmt.orelse, jumps, bound) + if isinstance(stmt, (ast.With, ast.AsyncWith)): + return _ends(stmt.body, jumps, bound) + if isinstance(stmt, ast.Try) or type(stmt).__name__ == "TryStar": + # Conservative: a try whose body or finally ends is treated as ending, even if a handler could + # fall through (`try: return X / except: pass`). The corpus never needs that shape, and a + # rewrite hides behind it; the d4 prompt says so. + return _ends(stmt.body, jumps, bound) or _ends(stmt.finalbody, jumps, bound) + if isinstance(stmt, ast.While): + value = _truth(stmt.test, bound) + return value in (True, FIXED) and not _loop_body_jumps_out(stmt.body) # a false while never runs + if isinstance(stmt, (ast.For, ast.AsyncFor)): + return (_must_iterate(stmt.iter, bound) and _ends(stmt.body, False, bound) + and not _loop_body_jumps_out(stmt.body)) + return False + + +def _dead_code(tree: ast.AST, objects: frozenset = frozenset()) -> list[tuple[str, str, str]]: + """Constant or tautological tests (a wrapper such as `if True:`), then unreachable statements. + + ``objects`` are names the buggy file binds only by def, class or import. They stay objects here + even if the candidate also assigns them, so adding `tokenize = 0` somewhere cannot turn + `if tokenize:` back into a variable test. + + Each finding is (key, location, message). The key identifies the code itself, not its line, + so findings the buggy file already has (a fault can create `x > x`) can be told apart from + new ones. + """ + found = [] + bound = (_bound_names(tree) - objects) | {OBJECT + name for name in objects} + for node in ast.walk(tree): + if isinstance(node, (ast.If, ast.While, ast.IfExp)) and _constant_test(node.test, bound): + found.append((f"const:{ast.dump(node.test)}", str(node.lineno), f"a constant condition at line {node.lineno}")) + for node in ast.walk(tree): + blocks = [getattr(node, field, None) for field in ("body", "orelse", "finalbody")] + blocks += [h.body for h in getattr(node, "handlers", None) or []] + for block in blocks: + if not isinstance(block, list) or not all(isinstance(s, ast.stmt) for s in block): + continue + for stmt, nxt in zip(block, block[1:]): + if _stmt_ends(stmt, True, bound): + # Keyed by the statement that ends the block, not by what follows it: the buggy file + # may already end a block early (a fault can make `x <= x`), and repairing the code + # after that statement must not read as new dead code. + found.append((f"dead-after:{ast.dump(stmt)}", str(nxt.lineno), + f"line {nxt.lineno} can never run (after line {stmt.lineno})")) + return found + + +def structure_violation(buggy: str, candidate: str) -> str | None: + """Why ``candidate`` is not a localised repair of ``buggy``, or None if it is.""" + try: + tree = ast.parse(candidate) + except SyntaxError: + return None # a syntax error is the candidate's own failure; grading scores it 0 + base = ast.parse(buggy) + if _top_level(tree) != _top_level(base): + return "top-level code must stay as it is (no new or redefined functions, imports or statements)" + if _definitions(tree) != _definitions(base): + return "function definitions, arguments and decorators must stay as they are" + if sum(isinstance(n, ast.Lambda) for n in ast.walk(tree)) > sum(isinstance(n, ast.Lambda) for n in ast.walk(base)): + return "no new lambda functions" + objects = frozenset(n[len(OBJECT):] for n in _bound_names(base) if n.startswith(OBJECT)) + already = Counter(key for key, _, _ in _dead_code(base)) + for key, _, message in _dead_code(tree, objects): + if already[key] > 0: + already[key] -= 1 # the buggy file has this one too; a fault may have made it + continue + return message + size, allowed = change_size(buggy, candidate), change_allowance(buggy) + if size > allowed: + return f"the change is too large for a localised repair ({size} syntax tokens; at most {allowed})" + return None + + +def plan(buggy: str, original: str) -> tuple[int, list[dict]] | None: + """(budget, minimal fix) when the minimal fix fits the budget and the gate, else None.""" + budget = budget_for(buggy) + fix = minimal_fix(buggy, original) + if sum(edit_cost(e) for e in fix) > budget or len(buggy) + len(original) <= budget: + return None + if structure_violation(buggy, original) is not None: + return None + current = buggy # the oracle applies the fix edit by edit, and every step must pass the gate too + for edit in fix: + current = current.replace(edit["old"], edit["new"], 1) + if structure_violation(buggy, current) is not None: + return None + return budget, fix diff --git a/components/qemedia/upstream/qe_arena/environment.py b/components/qemedia/upstream/qe_arena/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..7323983abf05374c8df52f7e47bf8352f31eb8a5 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/environment.py @@ -0,0 +1,216 @@ +"""OpenEnv environment: virtual files, exact-replacement edits, sandboxed tests.""" + +from __future__ import annotations + +import json +import secrets +from typing import Any, Literal +from uuid import uuid4 + +from openenv.core.env_server.interfaces import Environment +from openenv.core.env_server.types import Action, Observation, State +from pydantic import Field + +from . import edit_budget, flaky, sandbox +from .sandbox import InfraError +from .tasks import (MAX_FREE_REFUSALS, MODULE, TASK_IDS, Task, grade_bugfix, grade_mutant_kill, make_task, + run_visible) + +MAX_STEPS = 12 +MAX_TEST_RUNS = 3 +MAX_EDIT_BYTES = 4096 +MAX_FILE_BYTES = 6000 +MAX_ANSWER_BYTES = 8192 +# Ends every non-terminal step observation: with thinking off the model drifts into prose before its JSON after a +# few steps, and the reset prompt alone is too far back to hold it. Reset leaves it empty, so the reset prompt +# and the exported dataset do not change. +STEP_REMINDER = "Reply with exactly one JSON action object and nothing else." + + +class QEAction(Action): + op: Literal["read", "run_tests", "edit", "submit"] = Field(description=( + "One action per reply. Start with read path * to see every file. " + "read: show a file. run_tests: run the visible tests on your edited code (bug-fix and flaky-test tasks). " + "edit: replace old with new in a file (bug-fix tasks and flaky-test repair). " + "submit: end the episode and get graded.")) + path: str = Field(default="", description="read/edit: the file name, or * with read for all files.") + old: str = Field(default="", description="edit: exact text copied from the file; it must occur exactly once.") + new: str = Field(default="", description="edit: the text that replaces old.") + answer: dict[str, Any] = Field(default_factory=dict, description=( + "submit: {} grades your edited file in a bug-fix task; " + '{"tests": [{"args": [...], "expected": ...}]} in a mutant-kill task; ' + '{"test": "test_name" or null, "cause": ...} in a flaky-test task, where cause is one of ' + + ", ".join(flaky.CAUSES) + ".")) + + +class QEObservation(Observation): + task_id: str = "" + prompt: str = "" + files: list[str] = Field(default_factory=list) + content: str = "" + error: str = "" + remaining_steps: int = 0 + reply_format: str = "" # declared last so it closes the rendered observation + + +class QEEnvironment(Environment[QEAction, QEObservation, State]): + SUPPORTS_CONCURRENT_SESSIONS = True + + def __init__(self, corpus_pool: tuple[str, ...] | None = None, fault_kind: str | None = None): + """``corpus_pool`` and ``fault_kind`` are for calibration only; the server passes nothing.""" + super().__init__() + self._pool = corpus_pool + self._fault_kind = fault_kind + self._state = State(episode_id=str(uuid4()), step_count=0) + self._task: Task | None = None + self._files: dict[str, str] = {} + self._done = False + self._reward = 0.0 + self._test_runs = 0 + self._edit_spent = 0 + self._refusals = 0 + self._sandbox_session = uuid4().hex # fairness key for the shared sandbox worker pool + + def reset(self, seed: int | None = None, episode_id: str | None = None, **kwargs: Any) -> QEObservation: + with sandbox.session(self._sandbox_session): + return self._reset(seed, episode_id, **kwargs) + + def _reset(self, seed: int | None = None, episode_id: str | None = None, **kwargs: Any) -> QEObservation: + task_id = kwargs.get("task_id", TASK_IDS[0]) + if seed is None: + seed = secrets.randbelow(2**63) + kind = self._fault_kind if task_id.startswith("qe_bugfix") else None + self._task = make_task(task_id, seed, pool=self._pool, fault_kind=kind) + self._files = dict(self._task.files) + self._state = State(episode_id=episode_id or str(uuid4()), step_count=0) + self._done, self._reward, self._test_runs = False, 0.0, 0 + self._edit_spent, self._refusals = 0, 0 + return self._observe(remind=False, prompt=self._task.prompt, files=sorted(self._files)) + + def _observe(self, remind: bool = True, **fields: Any) -> QEObservation: + """A step observation carries STEP_REMINDER unless the episode is over (there is no next reply).""" + return QEObservation( + task_id=self._task.task_id if self._task else "", done=self._done, reward=self._reward, + remaining_steps=max(0, MAX_STEPS - self._state.step_count), + reply_format=STEP_REMINDER if remind and not self._done else "", **fields) + + def step(self, action: QEAction, timeout_s: float | None = None, **kwargs: Any) -> QEObservation: + """One action. An InfraError (the sandbox infrastructure failed) propagates unscored: the step, + the test run and the episode stay as they were, so the same action can be sent again.""" + if self._task is None: + raise RuntimeError("reset required") + if self._done: + return self._observe(error="episode is terminal; reset before another attempt") + free = self._free_refusal(action) + if free is not None: + return self._refused(free) + self._state.step_count += 1 + try: + with sandbox.session(self._sandbox_session): + return self._act(action) + except InfraError: + self._state.step_count -= 1 + raise + + def _act(self, action: QEAction) -> QEObservation: + family = self._task.family + if action.op == "submit": + return self._submit(action) + if self._state.step_count >= MAX_STEPS: + self._done = True + return self._observe(error="step budget exhausted; reward 0") + if action.op == "read": + if action.path == "*": + return self._observe(content="\n".join(f"=== {n} ===\n{t}" for n, t in sorted(self._files.items()))) + if action.path not in self._files: + return self._observe(error=f"unknown file; files are {sorted(self._files)}") + return self._observe(content=self._files[action.path]) + if family == "qe_mutant_kill" or (family == "qe_flaky" and action.op == "edit" and self._task.difficulty != 3): + return self._observe(error=f"{action.op} is not available in this task; read the files, then submit") + if action.op == "run_tests": + if self._test_runs >= MAX_TEST_RUNS: + return self._observe(error="no test runs left; submit when ready") + run = run_visible if family == "qe_bugfix" else flaky.run_shown + report = run(self._task, self._files[MODULE]) # before counting: an InfraError uses no test run + self._test_runs += 1 + return self._observe(content=report) + return self._edit(action) + + def _refusal_reason(self, action: QEAction) -> str | None: + """d4: why an otherwise valid edit is refused (over budget, or not a localised repair), else None.""" + budget = self._task.private.get("edit_budget") + if budget is None or action.op != "edit" or action.path != MODULE or not action.old: + return None + cost = len(action.old) + len(action.new) + if self._edit_spent + cost > budget: + return (f"it costs {cost} characters (len(old) + len(new)) and {budget - self._edit_spent} of the " + f"{budget} budget are left") + text = self._files[MODULE] + if text.count(action.old) != 1: + return None # reported as an ordinary edit error + violation = edit_budget.structure_violation(self._task.private["buggy"], text.replace(action.old, action.new, 1)) + return None if violation is None else f"not a localised repair: {violation}" + + def _free_refusal(self, action: QEAction) -> str | None: + """A refusal that does not use a step, for the first MAX_FREE_REFUSALS refusals.""" + reason = self._refusal_reason(action) + if reason is None or self._refusals >= MAX_FREE_REFUSALS: + return None + self._refusals += 1 + return reason + + def _refused(self, reason: str) -> QEObservation: + return self._observe(error=f"edit refused, nothing was changed: {reason}") + + def _edit(self, action: QEAction) -> QEObservation: + if action.path != MODULE: + return self._observe(error=f"only {MODULE} can be edited") + if not action.old or len(action.old) + len(action.new) > MAX_EDIT_BYTES: + return self._observe(error="old must be non-empty and the edit small") + budget = self._task.private.get("edit_budget") + cost = len(action.old) + len(action.new) + reason = self._refusal_reason(action) + if reason is not None: + self._refusals += 1 + return self._refused(reason) + text = self._files[MODULE] + count = text.count(action.old) + if count != 1: + return self._observe(error=f"old occurs {count} times; it must occur exactly once") + updated = text.replace(action.old, action.new, 1) + try: + size = len(updated.encode("utf-8")) + except UnicodeEncodeError: + return self._observe(error="edit text must be valid UTF-8") + if size > MAX_FILE_BYTES: + return self._observe(error="file too large after edit") + self._files[MODULE] = updated + message = f"edited {MODULE}; {len(updated.splitlines())} lines" + if budget is not None: + self._edit_spent += cost + message += f"; edit budget left: {budget - self._edit_spent} of {budget} characters" + return self._observe(content=message) + + def _submit(self, action: QEAction) -> QEObservation: + try: + if self._task.family == "qe_bugfix": + reward = grade_bugfix(self._task, self._files[MODULE]) + else: + encoded = json.dumps(action.answer, allow_nan=False, separators=(",", ":")) + too_big = len(encoded.encode()) > MAX_ANSWER_BYTES + if too_big: + reward = 0.0 + elif self._task.family == "qe_flaky": + reward = flaky.grade(self._task, action.answer, self._files[MODULE]) + else: + reward = grade_mutant_kill(self._task, action.answer) + except InfraError: + raise # not the answer's fault: no reward, the episode stays open + except Exception: # noqa: BLE001 - any other grading failure on a model answer scores 0 + reward = 0.0 + self._done, self._reward = True, reward + return self._observe() + + @property + def state(self) -> State: + return self._state.model_copy(deep=True) diff --git a/components/qemedia/upstream/qe_arena/flaky.py b/components/qemedia/upstream/qe_arena/flaky.py new file mode 100644 index 0000000000000000000000000000000000000000..a04e1427ec051d3b2f73d4d345aab0685926e98f --- /dev/null +++ b/components/qemedia/upstream/qe_arena/flaky.py @@ -0,0 +1,456 @@ +"""qe_flaky: diagnose and repair a simulated flaky test. Harness, region gate, ground truth and grading. + +module.py holds a corpus function, a suite of 3-5 tests (the "region") and a fixed harness +``run_suite(order, seed, t0)``. The sandbox has no clock, no ``random`` and a pinned hash seed, so flakiness is +simulated deterministically: each run builds a fresh ``env`` whose seeded streams (draw, frac), fake clock (now) +and unordered-collection order (pool) derive from (order, seed, t0), and module-level dicts carry state between +tests within a run. Generation lives in ``flaky_gen``. + +Grading never runs the harness text the model can edit. It composes a grader-only module in which the harness +is defined before the region and captures every builtin it uses as a default argument, so nothing the region +defines can shadow it; the region only ever receives an ``env`` instance of a class built for that one run. The +region must also pass ``gate_region``: no harness names, no rebinding of builtins or of the function under test, +no attribute assignment. +""" + +from __future__ import annotations + +import ast +import builtins +import random + +from . import sandbox +from .tasks import MODULE, REPLY_FORMAT, Task, _outputs + +CAUSES = ("shared_state", "cache_leak", "shared_random", "clock_boundary", "unordered_iteration", "float_equality") +CAUSE_TEXT = { + "shared_state": "assigns to an entry of a module-level dict that another test reads directly, so the outcome " + "depends on test order", + "cache_leak": "a memoizing helper hands back a value stored by an earlier call because its key is too coarse", + "shared_random": "the outcome depends on which value env.draw returns", + "clock_boundary": "the outcome depends on env.now crossing a time boundary between two reads", + "unordered_iteration": "the outcome depends on the order env.pool returns", + "float_equality": "exact == on floating-point arithmetic whose rounding depends on the env.frac value", +} +FACILITY = {"shared_state": "state", "cache_leak": "store", "shared_random": "draw", "clock_boundary": "now", + "unordered_iteration": "pool", "float_equality": "frac"} +MASK = {"shared_state": 1, "cache_leak": 2, "shared_random": 3, "float_equality": 4, "clock_boundary": 5, + "unordered_iteration": 6} +SEED_SPLIT = 500_000 # shown runs use seeds below this, graded runs seeds at or above it +TICK = 250 +MAX_GRADED_BYTES = 5600 # leaves room under the sandbox's 6000-byte cap for a repair to grow the test +HARNESS_HEAD = "from collections import namedtuple\n" +HARNESS_NAMES = frozenset({"SUITE", "BOXES", "SNAPSHOT", "RUN", "make_runner", "run_suite", "namedtuple", "probe", + "sweep", "permutations", "Env", "build"}) +BUILTIN_NAMES = frozenset(dir(builtins)) + +CORE = '''def make_runner(namedtuple=namedtuple, list=list, range=range, len=len, zip=zip, Exception=Exception, + isinstance=isinstance, dict=dict{gargs}): + """Builds run(). Every run gets a fresh env: its own Env class, seeded streams and clock.""" + tick = 250 + + def clone(value): + if isinstance(value, list): + return [clone(v) for v in value] + if isinstance(value, dict): + return {{k: clone(v) for k, v in value.items()}} + return value + + def run(suite, boxes, snapshot, order, seed, t0{rargs}): + for box, saved in zip(boxes, snapshot): + box.clear() + box.update(clone(saved)) + fed = [0, 0, 0] #G + cell = [seed % 2147483646 + 1, (seed * 7919 + 17) % 2147483646 + 1, (seed * 104729 + 3) % 2147483646 + 1, t0] + + def step(i): + cell[i] = cell[i] * 48271 % 2147483647 + return cell[i] + + def draw(n): + """An int in range(n) from the run's seeded stream, which every test in the run shares.""" + if stub and stub[0] == "draw": #G + fed[0] += 1 #G + if fed[0] <= len(stub[1]): #G + return stub[1][fed[0] - 1] % n #G + return step(0) % n + + def frac(): + """A number in (0, 1) from a second seeded stream.""" + if stub and stub[0] == "frac": #G + fed[1] += 1 #G + return stub[1][(fed[1] - 1) % len(stub[1])] #G + return step(1) / 2147483647 + + def now(): + """Fake clock in ms: t0 at the first read of the run, then 250 more on every read.""" + cell[3] += tick + return cell[3] - tick + + def pool(items): + """items in the iteration order of an unordered collection, which changes from run to run.""" + items = list(items) + if stub and stub[0] == "pool": #G + fed[2] += 1 #G + pick = list(permutations(range(len(items)))) #G + return [items[i] for i in pick[(stub[1] + fed[2] - 1) % len(pick)]] #G + for i in range(len(items) - 1, 0, -1): + j = step(2) % (i + 1) + items[i], items[j] = items[j], items[i] + return items + + env = namedtuple("Env", "draw frac now pool")(draw, frac, now, pool) + passed = {{}} + for index in order: + for k in reset: #G + boxes[k].clear() #G + boxes[k].update(clone(snapshot[k])) #G + if mask in (3, 4, 6): #G + cell[{{3: 0, 4: 1, 6: 2}}[mask]] = 1 #G + if mask == 5: #G + cell[3] = 0 #G + name, test = suite[index] + try: + test(env) + passed[name] = True + except Exception: + passed[name] = False + return passed + + return run + + +RUN = make_runner() +''' +RUN_SUITE = '''def run_suite(order, seed, t0): + """Run SUITE[i] for each i in order, as one CI run does. Returns {test name: passed}.""" + return RUN(SUITE, BOXES, SNAPSHOT, order, seed, t0) +''' +GRADER_TAIL = ''' + +def run_suite(order, seed, t0): + suite, boxes = build() + return RUN(suite, boxes, [dict(box) for box in boxes], order, seed, t0) + + +def probe(order, seed, t0, mask, reset): + suite, boxes = build() + return RUN(suite, boxes, [dict(box) for box in boxes], order, seed, t0, mask, reset) + + +def sweep(name, kind, value, seed, t0): + suite, boxes = build() + one = [item for item in suite if item[0] == name] + return RUN(one, boxes, [dict(box) for box in boxes], [0], seed, t0, 0, (), [kind, value]) +''' + + +def _core(grader: bool) -> str: + text = CORE.format(gargs=", permutations=permutations" if grader else "", + rargs=", mask=0, reset=(), stub=None" if grader else "") + lines = [] + for line in text.split("\n"): + if line.endswith(" #G"): + if grader: + lines.append(line[:-4]) + elif not (grader and line.strip().startswith('"""')): + lines.append(line) + return "\n".join(lines) + + +def _registry(names: list[str], boxes: list[str]) -> str: + return (f"SUITE = [{', '.join(f'({n!r}, {n})' for n in names)}]\nBOXES = [{', '.join(boxes)}]\n" + "SNAPSHOT = [dict(box) for box in BOXES]\n") + + +def shown_harness(names: list[str], boxes: list[str]) -> str: + return f"{HARNESS_HEAD}\n{_registry(names, boxes)}\n\n{_core(False)}\n\n{RUN_SUITE}" + + +def graded_source(prefix: str, region: str, names: list[str], boxes: list[str]) -> str | None: + """The module the grader runs. The harness is bound first, and the function under test plus the tests are + rebuilt inside build() on every run, so no state (a mutable default, a module-level list, a dict value mutated + in place) survives from one run to the next. None if the code does not parse.""" + try: + user = ast.unparse(ast.parse(prefix + region)) + except (SyntaxError, ValueError, RecursionError, MemoryError): + return None + suite = ", ".join(f"({n!r}, {n})" for n in names) + body = "\n".join(" " + line for line in user.split("\n")) + f"\n return [{suite}], [{', '.join(boxes)}]" + return (f"{HARNESS_HEAD}from itertools import permutations\n\n\n{_core(True)}\n\n\ndef build():\n{body}\n" + + GRADER_TAIL) + + +def top_names(source: str) -> set[str]: + names = set() + for node in ast.parse(source).body: + if isinstance(node, (ast.FunctionDef, ast.ClassDef)): + names.add(node.name) + elif isinstance(node, (ast.Import, ast.ImportFrom)): + names.update((a.asname or a.name).split(".")[0] for a in node.names) + elif isinstance(node, ast.Assign): + names.update(t.id for t in node.targets if isinstance(t, ast.Name)) + return names + + +def gate_region(region: str, protected: set[str]) -> list[str]: + """Reasons the tests region may not run: harness names, rebinding builtins or ``protected`` names (the + function under test and its helpers), or assigning an attribute. Empty means it passed.""" + try: + tree = ast.parse(region) + except (SyntaxError, ValueError, RecursionError, MemoryError): + return ["the tests do not parse"] + reserved = BUILTIN_NAMES | protected | HARNESS_NAMES + problems = [] + + def bound(name: str | None) -> None: + if name and name in reserved: + problems.append(f"the tests may not bind {name!r}") + + for node in ast.walk(tree): + if isinstance(node, ast.Name): + if node.id in HARNESS_NAMES: + problems.append(f"{node.id!r} belongs to the harness") + elif not isinstance(node.ctx, ast.Load): + bound(node.id) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + bound(node.name) + elif isinstance(node, ast.arg): + bound(node.arg) + elif isinstance(node, ast.alias): + bound((node.asname or node.name).split(".")[0]) + elif isinstance(node, ast.ExceptHandler): + bound(node.name) + elif isinstance(node, ast.Attribute) and not isinstance(node.ctx, ast.Load): + problems.append(f"the tests may not assign attribute {node.attr!r}") + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + spec = node.args + if spec.defaults or any(d is not None for d in spec.kw_defaults): + problems.append("functions in the tests may not have default arguments") + if getattr(node, "decorator_list", None): + problems.append("functions in the tests may not be decorated") + if getattr(node, "name", "").startswith("test_") and ( + [a.arg for a in spec.args] != ["env"] or spec.posonlyargs or spec.kwonlyargs + or spec.vararg or spec.kwarg): + problems.append(f"{node.name} must take exactly one parameter, env") + return list(dict.fromkeys(problems)) + + +def run(source: str, calls: list[list], entry: str = "run_suite") -> list[dict] | None: + results = [] + for start in range(0, len(calls), 200): + chunk = _outputs(source, entry, calls[start:start + 200]) + if not all(r.kind == "ok" and isinstance(r.value, dict) for r in chunk): + return None + results.extend(r.value for r in chunk) + return results + + +def run_isolated(source: str, calls: list[list]) -> list[dict] | None: + """One sandbox process per graded run, so nothing in the interpreter carries over between runs either.""" + results = [] + for call in calls: + out = run(source, [call]) + if out is None: + return None + results.extend(out) + return results + + +def combos(rng: random.Random, n_tests: int, count: int, shown: bool) -> list[list]: + lo, hi = (0, SEED_SPLIT) if shown else (SEED_SPLIT, 2 * SEED_SPLIT) + return [[rng.sample(range(n_tests), n_tests), rng.randrange(lo, hi), rng.randrange(10**7)] for _ in range(count)] + + +def reachable(x: float) -> float: + """The value env.frac can actually return that is closest to x.""" + return max(1, min(2147483646, round(x * 2147483647))) / 2147483647 + + +FRAC_SWEEP = [reachable(x) for x in [i / 64 for i in range(1, 64)] + [i / 10 for i in range(1, 10)] + + [i / 97 for i in range(1, 97, 3)]] + + +def sweep_calls(rng: random.Random) -> list[list]: + """[kind, value, seed, t0] for the repaired test alone, with seed and t0 drawn like graded runs from the task's + own secret stream. Each of the first eight draws in turn is forced to each residue 0..7 while the others take + large random values, so no probe draw reveals the sweep and a flaky draw is caught wherever it sits; clocks + start just below powers of ten and calendar periods (and at random); frac walks a grid of reachable values from + every starting point; pool takes every order.""" + def run_at(kind, value, t0=None): + return [kind, value, rng.randrange(SEED_SPLIT, 2 * SEED_SPLIT), rng.randrange(10**7) if t0 is None else t0] + + calls = [] + for r in range(8): + for position in range(8): + values = [rng.randrange(8, 10**9) for _ in range(8)] + values[position] = r + calls.append(run_at("draw", values)) + clocks = [10**k - d for k in range(1, 14) for d in (1, 125, 249, 374, 499, 749, 999) if 10**k > d] + clocks += [p * m - d for p in (60_000, 3_600_000, 86_400_000) for m in (1, 7) for d in (1, 249)] + calls += [run_at("now", 0, t0) for t0 in clocks + [rng.randrange(10**13) for _ in range(32)]] + grid = FRAC_SWEEP + [rng.randrange(1, 2147483647) / 2147483647 for _ in range(16)] + calls += [run_at("frac", grid[i:] + grid[:i]) for i in range(len(grid))] + return calls + [run_at("pool", j) for j in range(6)] + + +def attribute(source: str, graded: list[list], victim: str, idx: dict) -> tuple[list[str], list[dict]] | None: + """Causes whose facility, reset before every test, makes the victim's outcome constant (plus mask-0 runs).""" + calls = [] + for mask in range(7): + reset = idx["state"] if mask == 1 else idx["store"] if mask == 2 else [] + calls += [c + [mask, reset] for c in graded] + outcomes = run(source, calls, entry="probe") + if outcomes is None: + return None + k = len(graded) + stable = [m for m in range(1, 7) if len({o.get(victim) for o in outcomes[m * k:(m + 1) * k]}) == 1] + return [c for c in CAUSES if MASK[c] in stable], outcomes[:k] + + +def victim_block(source: str, name: str) -> str | None: + """The text of the top-level test function ``name`` in ``source``, or None.""" + try: + tree = ast.parse(source) + except (SyntaxError, ValueError, RecursionError, MemoryError): + return None + found = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == name] + return ast.get_source_segment(source, found[0]) if len(found) == 1 else None + + +def spliced_region(task: Task, source: str) -> str | None: + """The original tests with only the flaky test's function taken from ``source`` (the graded repair).""" + p = task.private + edited = victim_block(source, p["victim"]) + if edited is None: + return None + original = victim_block(p["region"], p["victim"]) + return p["region"].replace(original, edited, 1) + + +def repair_ok(task: Task, region: str, mutant: str | None = None, isolated: bool = True) -> bool: + """The suite passes on every graded run, the repaired test passes every sweep value alone, and it fails on + every graded run when the function under test is the reference mutant. Model code gets one process per + graded run; ``isolated=False`` batches them, for the generator's own canonical repair only.""" + runner = run_isolated if isolated else run + p = task.private + if gate_region(region, set(p["protected"])): + return False + source = graded_source(p["prefix"], region, p["tests"], p["boxes"]) + if source is None or len(source.encode()) > 6000: + return False + outcomes = runner(source, p["graded"]) + if outcomes is None or not all(sorted(o) == sorted(p["tests"]) and all(v is True for v in o.values()) + for o in outcomes): + return False + swept = run(source, [[p["victim"]] + s for s in p["sweep"]], entry="sweep") + if swept is None or not all(o.get(p["victim"]) is True for o in swept): + return False + mutant = mutant or p["mutants"][0]["source"] + mutated = graded_source(mutant.rstrip("\n") + "\n\n\n", region, p["tests"], p["boxes"]) + killed = runner(mutated, p["graded"]) if mutated else None + return killed is not None and all(o.get(p["victim"]) is False for o in killed) + + +def _structure(task: Task, source: str) -> str | None: + p = task.private + if not (source.startswith(p["prefix"]) and source.endswith(p["harness"]) + and len(source) >= len(p["prefix"]) + len(p["harness"])): + return None + return source[len(p["prefix"]):len(source) - len(p["harness"])] + + +def run_shown(task: Task, source: str) -> str: + """Run the working copy's tests on the shown runs (the model's run_tests).""" + p = task.private + region = _structure(task, source) + if region is None: + return "the code under test and the harness must stay unchanged; only the tests may be edited" + problems = gate_region(region, set(p["protected"])) + graded = graded_source(p["prefix"], region, p["tests"], p["boxes"]) + problems = problems or (sandbox.static_gate(graded) if graded else ["the tests do not parse"]) + if problems: + return "REJECTED: " + "; ".join(problems)[:400] + results = _outputs(graded, "run_suite", p["shown"]) + lines = [] + for (order, seed, t0), result in zip(p["shown"], results): + head = f"run_suite({order}, {seed}, {t0})" + if result.kind != "ok" or not isinstance(result.value, dict): + lines.append(f"{head}: {result.kind} {result.error[:120]}") + continue + failed = [str(n)[:40] for n, ok in result.value.items() if ok is not True] + lines.append(f"{head}: {len(result.value) - len(failed)}/{len(result.value)} passed" + + (f"; failed: {', '.join(failed)}" if failed else "")) + return "\n".join(lines) + + +def _answer(answer) -> tuple[str | None, str | None] | None: + if not isinstance(answer, dict) or "test" not in answer or set(answer) - {"test", "cause"}: + return None + test, cause = answer["test"], answer.get("cause") + if not (test is None or type(test) is str) or not (cause is None or type(cause) is str): + return None + return test, cause + + +def grade(task: Task, answer, source: str) -> float: + p = task.private + parsed = _answer(answer) + if parsed is None: + return 0.0 + test, cause = parsed + if p["victim"] is None: # clean control: only "no flaky test" is right; d3 edits are discarded + return 1.0 if test is None else 0.0 + if test != p["victim"]: + return 0.0 + if task.difficulty == 1: + return 1.0 + if task.difficulty == 2: + return 1.0 if cause == p["cause"] else 0.5 + region = spliced_region(task, source) + return 1.0 if region is not None and repair_ok(task, region) else 0.5 + + +def prompt(entry: str, level: int, shown: list[list]) -> str: + runs = "; ".join(f"run_suite({o}, {s}, {t})" for o, s, t in shown) + lines = [ + f"{MODULE} holds `{entry}` (the code under test), a test suite that checks it, and a fixed harness " + "`run_suite(order, seed, t0)`. CI runs the suite many times with different orders, seeds and start times. " + "Every test gets `env`: env.draw(n) and env.frac() read seeded pseudo-random streams shared by the whole " + "run, env.now() is a fake millisecond clock, and env.pool(items) returns items in an order that changes " + "between runs. Module-level dicts are reset at the start of each run, not between tests.", + "A test is flaky when its outcome changes between runs although the code under test does not. At most one " + "test in this suite is flaky, and possibly none is. Some flaky tests fail only rarely.", + f"Every test passed on these runs: {runs}.", + ] + if level == 1: + lines.append("Name the flaky test, or answer null when no test is flaky.") + answer = '{"op": "submit", "answer": {"test": "test_name"}} or {"op": "submit", "answer": {"test": null}}' + elif level == 2: + lines.append("Name the flaky test and its root cause, or answer null when no test is flaky. Causes:") + lines.extend(f"- {c}: {CAUSE_TEXT[c]}" for c in CAUSES) + lines.append("The right test earns half the reward; the right test and cause earn all of it.") + answer = ('{"op": "submit", "answer": {"test": "test_name", "cause": "shared_state"}} or ' + '{"op": "submit", "answer": {"test": null}}') + else: + lines.append( + "Repair the flaky test so it passes on every run and still checks " + f"`{entry}`, then submit its name, or null when no test is flaky. Only the flaky test's own function is " + "graded: edit inside it, because every other edit is discarded. Test code may not use the harness's " + "names, rebind built-in names, or assign attributes. Naming the flaky test earns half the reward. Full " + "reward needs a suite that passes on every run, under any value env can produce, and a repaired test " + f"that still fails when `{entry}` is wrong, so deleting or weakening its checks earns no more than half.") + answer = '{"op": "submit", "answer": {"test": "test_name"}} or {"op": "submit", "answer": {"test": null}}' + lines += ["", REPLY_FORMAT, 'First action: {"op": "read", "path": "*"}', + 'Run the suite on the runs above (at most 3 times): {"op": "run_tests"}'] + if level == 3: + lines.append('Edit by exact text replacement (old must occur exactly once): ' + '{"op": "edit", "path": "module.py", "old": " assert x == 1", "new": " assert y == 1"}') + lines.append(f"Final action: {answer}") + return "\n".join(lines) + + +def make_flaky_task(task_id: str, level: int, seed: int, rng: random.Random, pool: tuple[str, ...]) -> Task: + from .flaky_gen import build_task # noqa: PLC0415 - flaky_gen imports this module + + return build_task(task_id, level, seed, rng, pool) diff --git a/components/qemedia/upstream/qe_arena/flaky_gen.py b/components/qemedia/upstream/qe_arena/flaky_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc6aeee08521f2f34c58cd577f2bf818a3e2bed --- /dev/null +++ b/components/qemedia/upstream/qe_arena/flaky_gen.py @@ -0,0 +1,251 @@ +"""qe_flaky generation. Every test is built from templates that each have a faulty and a safe parametrization +(the same text shape with different values), so the flaky test can only be told apart by reading what the +code does. Ground truth, cause attribution and repairability are then established by execution in ``flaky``.""" + +from __future__ import annotations + +import json +import random +from collections import Counter + +from . import corpus, mutation, sandbox +from .flaky import (CAUSES, FACILITY, SEED_SPLIT, MAX_GRADED_BYTES, attribute, combos, gate_region, + graded_source, prompt, repair_ok, run, shown_harness, sweep_calls, top_names, victim_block) +from .flaky_templates import (KEY_NAMES, SINGLE, Plan, choose_store_key, decoy_unit, key_text, + single_check, state_unit, store_unit) +from .tasks import MODULE, Task, _outputs, passes + +CLEAN_RATE = 0.15 +LOW_RATE = 0.25 # share of draw/now/frac flakes that fail only 2-10% of runs +K_GRADE, K_LOW = 24, 96 +N_SHOWN = 2 +N_TESTS = {1: (4,), 2: (4, 5), 3: (4, 5)} +P_MIX = {1: 0.3, 2: 0.4, 3: 0.3} # a test carries a second check on another facility +P_SAME = 0.95 # a decoy reuses the flaky test's facility ... +N_SAME = {1: 2, 2: 2, 3: 2} # at most this many such decoys +P_FILLER = 0.15 # a decoy uses a safe-only form +MAX_FUNCTION_BYTES = 1800 +MAX_LITERAL = 48 +TELLTALE = ("flak", "random", "cache", "memo", "leak", "shared", "unorder", "float", "clock", "boundary", + "order", "victim", "pollut", "culprit", "race", "time") +TEST_WORDS = ("amber", "basalt", "cedar", "delta", "ember", "fjord", "garnet", "harbor", "indigo", "juniper", + "kestrel", "lagoon", "marble", "nectar", "onyx", "prairie", "quartz", "raven", "sierra", "tundra", + "umber", "violet", "willow", "zephyr", "alder", "birch", "comet", "dune", "fern", "glacier") +STATE_NAMES = ("DEFAULTS", "SETTINGS", "FIXTURE", "PARAMS", "PROFILE", "BASELINE") +STORE_NAMES = ("STORE", "TABLE", "LEDGER", "SLOTS", "INDEX", "BANK") +HELPER_NAMES = ("lookup", "fetch", "resolve", "obtain", "evaluate", "answer_for") + +REJECTS: Counter = Counter() # why candidate tasks were regenerated; diagnostics for calibration and tests + + +def _reject(reason: str) -> None: + REJECTS[reason] += 1 + return None + + +def _rows(name: str, source: str, entry: str, rng: random.Random) -> list[tuple[list, object]]: + inputs = corpus.gen_inputs(name, rng.randrange(2**31), 64) + results = _outputs(source, entry, inputs) + rows, seen, size = [], set(), 0 + for args, result in zip(inputs, results): + text, out = json.dumps(args), json.dumps(result.value) + if result.kind != "ok" or not args or text in seen or len(text) > MAX_LITERAL or len(out) > MAX_LITERAL: + continue + if any(word in (text + out).lower() for word in TELLTALE): + continue + seen.add(text) + size += len(repr((args, result.value))) + 2 + if size > 3600: # the check below must stay under the sandbox's source cap + break + rows.append((args, result.value)) + if not rows: + return [] + # The tests compare Python values; keep only rows whose literal equals what the function returns there. + check = source + f"\n\nROWS = {rows!r}\n\n\ndef same(i):\n a, o = ROWS[i]\n return {entry}(*a) == o\n" + verdicts = _outputs(check, "same", [[i] for i in range(len(rows))]) + return [row for row, v in zip(rows, verdicts) if v.kind == "ok" and v.value is True] + + +def _mutant(function: str, entry: str, rows: list, rng: random.Random) -> tuple[str, dict] | None: + """A d3 reference mutant and its zones: the faulty check draws only inputs the mutant returns another value + for (never a raise, which would fail a test that asserts nothing), every other test only unchanged ones.""" + calls = [a for a, _ in rows] + reference = _outputs(function, entry, calls) + sites = mutation.enumerate_sites(function, mutation.CLASSIC_OPERATORS) # realistic operators would shift tasks + rng.shuffle(sites) + for site in sites[:12]: + mutant = mutation.apply(function, [site]) + if mutant.split("\n", 1)[-1] in function: # never a copy of the shown body + continue + outputs = _outputs(mutant, entry, calls) + if not all(o.kind in ("ok", "exc") for o in outputs): + continue + zones = {"kill": set(), "spare": set()} + for args, r, o in zip(calls, reference, outputs): + if sandbox.compare(r, o): + zones["spare"].add(json.dumps(args)) + elif o.kind == "ok": + zones["kill"].add(json.dumps(args)) + if len(zones["kill"]) >= 3 and len(zones["spare"]) >= 12: + return mutant, zones + return None + + +def build_task(task_id: str, level: int, seed: int, rng: random.Random, pool: tuple[str, ...]) -> Task: + clean = rng.random() < CLEAN_RATE + cause = rng.choice(CAUSES) + low = FACILITY[cause] in ("draw", "now", "frac") and not clean and rng.random() < LOW_RATE + eligible = [n for n in sorted(pool) if len(corpus.ENTRIES[n].function_source) <= MAX_FUNCTION_BYTES + and "flak" not in corpus.ENTRIES[n].function_source.lower()] + for _ in range(passes(task_id)): # tasks.passes: the first pass is the original one + for name in rng.sample(eligible, len(eligible)): + item = corpus.ENTRIES[name] + function = mutation.rename_locals(item.function_source, random.Random(rng.random())) + rows = _rows(name, function, item.entry, rng) + if len(rows) < 12 or len({repr(o) for _, o in rows}) < 4: + continue + task = _build(task_id, level, seed, rng, name, item.entry, function, rows, cause, clean, low) + if task is not None: + return task + raise RuntimeError(f"no usable flaky task for {task_id} seed {seed}") + + +def _build(task_id, level, seed, rng, corpus_name, entry, function, rows, cause, clean, low) -> Task | None: + protected = top_names(function) + names = {"state": rng.choice(STATE_NAMES), "state_key": rng.choice(KEY_NAMES), + "store": rng.choice(STORE_NAMES), "helper": rng.choice(HELPER_NAMES)} + words = [w for w in TEST_WORDS if f"test_{w}" not in protected] + if protected & set(names.values()): + return _reject("name_clash") + p = Plan(entry=entry, rows=rows, rng=rng, names=names, low=low) + mutant = None + if level == 3 and not clean: + found = _mutant(function, entry, rows, rng) + if found is None: + return _reject("no_mutant") + mutant, p.zones = found + p.zone = "kill" + facility = FACILITY[cause] + if not choose_store_key(p, facility == "store" and not clean): + return _reject("no_store_pair") + mode = "twin" if clean else "bad" + if facility in ("state", "store"): + p.hint = (facility, "pair") + if facility == "state": + victim_unit = state_unit(p, mode, names["state_key"]) + elif facility == "store": + victim_unit = store_unit(p, mode) + else: + check = single_check(p, facility, mode if not clean else "safe") + victim_unit = [[check]] if check else None + if victim_unit is None: + return _reject("no_culprit_rows") + if mutant is not None: # an order-insensitive repair must not let a mutant that permutes outputs through + culprit = victim_unit[0][0] + changed = _outputs(mutant, entry, culprit.args) + reference = [o for a in culprit.args for r, o in rows if r == a][:len(culprit.args)] + if sorted(map(repr, (c.value for c in changed))) == sorted(map(repr, reference)): + return _reject("mutant_permutes_culprit_outputs") + p.zone = "spare" if p.zones else "" + plan = list(victim_unit) + n_tests = rng.choice(N_TESTS[level]) + want_same = N_SAME[level] if rng.random() < P_SAME else 0 + for _ in range(12): + if len(plan) >= n_tests: + break + target = facility if want_same else rng.choice(SINGLE + ("state", "store")) + want_same = max(0, want_same - 1) + unit = decoy_unit(p, target, "filler" if rng.random() < P_FILLER else "safe", n_tests - len(plan)) + if unit and len(plan) + len(unit) <= n_tests: + plan.extend(unit) + if len(plan) != n_tests: + return _reject("no_decoy_rows") + for checks in plan: + if rng.random() < P_MIX[level]: + kind = rng.choice([f for f in SINGLE if f != facility] + ["state"]) + if kind == "state": # a test that writes and reads its own dict entry, harmless wherever it sits + key = [k for k in KEY_NAMES if k not in p.state and k != names["state_key"]] + unit = state_unit(p, "safe", rng.choice(key), single=True) if key else None + extra = unit[0][0] if unit else None + else: + extra = single_check(p, kind, "safe") + if extra: + checks.append(extra) + test_names = [f"test_{w}" for w in rng.sample(words, len(plan))] + victim = test_names[0] + order = rng.sample(range(len(plan)), len(plan)) + tests = [(test_names[i], plan[i]) for i in order] + region, boxes = _render(p, tests, names) + listed = [n for n, _ in tests] + harness = shown_harness(listed, boxes) + prefix = function.rstrip("\n") + "\n\n\n" + source = prefix + region + harness + graded_src = graded_source(prefix, region, listed, boxes) + if graded_src is None or max(len(source.encode()), len(graded_src.encode())) > MAX_GRADED_BYTES \ + or sandbox.static_gate(graded_src): + return _reject("size_or_gate") + if gate_region(region, protected) or any(w in region.replace(entry, "").lower() for w in TELLTALE): + return _reject("region_gate_or_telltale") + graded = combos(rng, len(listed), K_LOW if low else K_GRADE, shown=False) + outcomes = run(graded_src, graded) + if outcomes is None or run(source, graded) != outcomes: + return _reject("suite_unsettled_or_shown_harness_differs") + vary = [n for n in listed if {o.get(n) for o in outcomes} == {True, False}] + broken = [n for n in listed if n not in vary and {o.get(n) for o in outcomes} != {True}] + if broken or vary != ([] if clean else [victim]): + return _reject("ground_truth") # ground truth by execution disagrees with what was injected + idx = {"state": [i for i, b in enumerate(boxes) if b == names["state"]], + "store": [i for i, b in enumerate(boxes) if b == names["store"]]} + if not clean: + attribution = attribute(graded_src, graded, victim, idx) + if attribution is None or attribution[1] != outcomes or attribution[0] != [cause]: + return _reject("attribution") + sweep = sweep_calls(random.Random(rng.random())) # the task's own secret stream + if not clean and facility in SINGLE: # the sweep must catch every faulty template on its own + swept = run(graded_src, [[victim] + s for s in sweep], entry="sweep") + if swept is None or all(o.get(victim) for o in swept): + return _reject("sweep_blind") + candidates = combos(rng, len(listed), 12, shown=True) + shown_out = run(source, candidates) + if shown_out is None: + return _reject("shown_unsettled") + shown = [c for c, o in zip(candidates, shown_out) if all(o.get(n) is True for n in listed)][:N_SHOWN] + if len(shown) < N_SHOWN: + return _reject("no_passing_shown_runs") + task = Task(task_id=task_id, family="qe_flaky", difficulty=level, seed=seed, + prompt=prompt(entry, level, shown), files={MODULE: source}, + private={"corpus": corpus_name, "entry": entry, "original": source, "prefix": prefix, + "region": region, "harness": harness, "tests": listed, "boxes": boxes, + "protected": sorted(protected), "victim": None if clean else victim, + "cause": None if clean else cause, "band": None if clean else "low" if low else "normal", + "graded": graded, "shown": shown, "sweep": sweep, "mutants": [], "repair": None}) + if level == 3 and not clean: + fixed_region, _ = _render(p, tests, names, repaired=victim) + old, new = victim_block(region, victim), victim_block(fixed_region, victim) + task.private["mutants"] = [{"source": mutant}] + if source.count(old) != 1 or not repair_ok(task, region.replace(old, new, 1), isolated=False): + return _reject("repair") + task.private["repair"] = {"old": old, "new": new} + return task + + +def _render(p: Plan, tests: list, names: dict, repaired: str | None = None) -> tuple[str, list[str]]: + """The tests region (dict, helper, tests) and the names of its module-level dicts.""" + parts, boxes = [], [] + if p.state: + parts.append(f"{names['state']} = {dict(sorted(p.state.items()))!r}") + boxes.append(names["state"]) + if p.store: + S, H = names["store"], names["helper"] + parts.append(f"{S} = {{}}\n\n\ndef {H}(*args):\n key = {key_text(p.key)}\n if key not in {S}:\n" + f" {S}[key] = {p.entry}(*args)\n return {S}[key]") + boxes.append(S) + for name, checks in tests: + body = [] + for check in checks: + body.extend(" " + line for line in (check.repair if repaired == name and check.repair else check.lines)) + parts.append(f"def {name}(env):\n" + "\n".join(body)) + return "\n\n\n".join(parts) + "\n\n\n", boxes + + +__all__ = ["build_task", "REJECTS", "SEED_SPLIT"] diff --git a/components/qemedia/upstream/qe_arena/flaky_templates.py b/components/qemedia/upstream/qe_arena/flaky_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..58600d4791b4917fb23854b890c53a90f35ceac1 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/flaky_templates.py @@ -0,0 +1,369 @@ +"""qe_flaky check templates. Each template has a faulty and a safe parametrization with the same text shape, +and decoys imitate the flaky test's own template, so only reading what the code does tells them apart.""" + +from __future__ import annotations + +import json +import random +from dataclasses import dataclass, field + +from .flaky import FRAC_SWEEP, TICK + +P_TWIN = 0.85 # a decoy on the flaky test's facility uses the very template the flaky test uses +SINGLE = ("draw", "frac", "now", "pool") +KEY_NAMES = ("input", "case", "args", "sample", "probe", "subject", "item", "seed_case", "target", "query") +CONSTS = ("0.1", "0.2", "0.3", "0.5", "0.25", "0.125", "0.7", "1.1", "2", "3", "4", "5", "8", "10", "16", "0.05", + "1.5", "0.75", "6", "7") +FLOAT_FORMS = ( # (setup line or "", asserted expression); {a} {b} are constants, {p} a parts list, {q} its sum + ("", "(w + {a}) - {a} == w"), ("", "w * {a} / {a} == w"), ("", "w / {a} * {a} == w"), + ("", "(w + {a}) + {b} == w + ({a} + {b})"), ("", "w * {a} * {b} == w * ({a} * {b})"), + ("total = w * {a}", "total / {a} == w"), ("total = w / {a}", "total * {a} == w"), + ("total = w + {a}", "total - {a} == w"), ("parts = [{p}]", "sum(parts) == {q}"), + ("", "w * {a} == {a} * w"), ("", "w + {a} == {a} + w"), ("total = w + {a}", "total == {a} + w"), +) +POW2 = frozenset({"0.5", "0.25", "0.125", "2", "4", "8", "16"}) +_r = random.Random(20261012) +FRAC_SAMPLE = [_r.randrange(1, 2147483647) / 2147483647 for _ in range(3000)] +FRAC_GRID = FRAC_SWEEP # values env.frac can actually produce +_FLOAT_CLASS: dict[tuple[str, str], str] = {} + + + +@dataclass +class Check: + lines: list[str] + args: list[list] # every input the check calls the function with + repair: list[str] | None = None # the canonical repair of a faulty check + + +@dataclass +class Plan: + entry: str + rows: list[tuple[list, object]] + rng: random.Random + names: dict + low: bool = False + used: set = field(default_factory=set) + zones: dict | None = None # d3: {"kill": inputs the mutant returns another value for, "spare": same value} + zone: str = "" + state: dict = field(default_factory=dict) # dict key -> initial args + store: list = field(default_factory=list) # (args, output) of every helper call + key: tuple = ("full",) + hint: tuple = ("", "") # (facility, template) of the flaky test, which decoys imitate + form: int | None = None # its float form, when it is a float check + + def call(self, args: list) -> str: + return f"{self.entry}({', '.join(repr(a) for a in args)})" + + def free(self, ok=None) -> list: + out = [r for r in self.rows if json.dumps(r[0]) not in self.used and (ok is None or ok(r)) + and (self.zones is None or not self.zone or json.dumps(r[0]) in self.zones[self.zone])] + self.rng.shuffle(out) + return out + + def distinct(self, count: int, ok=None) -> list | None: + chosen = [] + for row in self.free(ok): + if all(not (row[1] == c[1]) for c in chosen): + chosen.append(row) + if len(chosen) == count: + return self.mark(chosen) + return None + + def same(self, count: int, ok=None) -> list | None: + groups: dict[str, list] = {} + for row in self.free(ok): + group = groups.setdefault(repr(row[1]), []) + if all(row[1] == g[1] for g in group): + group.append(row) + if len(group) == count: + return self.mark(group) + return None + + def mark(self, rows): + self.used.update(json.dumps(r[0]) for r in rows) + return rows + + def keyed(self, args: list): + kind, text = self.key[0], repr(tuple(args)) + if kind == "prefix": + return text[:self.key[1]] + return repr(args[0]) if kind == "first" else len(text) if kind == "length" else text + + def store_ok(self, row) -> bool: + return all(not (self.keyed(a) == self.keyed(row[0])) or o == row[1] for a, o in self.store) + + +def _lit(values: list) -> str: + return ", ".join(repr(v) for v in values) + + +def _float_class(setup: str, expr: str) -> str: + """safe (always holds), normal or low (fails on 8-88% or 2-10% of values, and on the sweep grid), or other.""" + if (setup, expr) not in _FLOAT_CLASS: + name, _, value = setup.partition(" = ") + body = f"(lambda {name}: {expr})({value})" if setup else expr + fn = eval(compile(f"lambda w: {body}", "", "eval"), {"__builtins__": {}, "sum": sum}) # noqa: S307 + rate = sum(map(fn, FRAC_SAMPLE)) / len(FRAC_SAMPLE) + grid_fails = not all(map(fn, FRAC_GRID)) + _FLOAT_CLASS[(setup, expr)] = ("safe" if rate == 1 and not grid_fails else + "normal" if 0.12 <= rate <= 0.92 and grid_fails else + "low" if 0.9 <= rate <= 0.98 and grid_fails else "other") + return _FLOAT_CLASS[(setup, expr)] + + +def _float_expr(rng: random.Random, want: str, form: int | None = None) -> tuple[str, str, int] | None: + pow2 = rng.random() < 0.5 # exact and inexact checks both come with power-of-two and other constants + pool = [c for c in CONSTS if (c in POW2) == pow2] + for attempt in range(300): + index = form if form is not None and attempt < 100 else rng.randrange(len(FLOAT_FORMS)) + setup, expr = FLOAT_FORMS[index] + a, b = rng.sample(pool if attempt < 200 else CONSTS, 2) + terms = ["w", a, b] + rng.shuffle(terms) + fields = {"a": a, "b": b, "p": ", ".join(terms), "q": " + ".join(rng.sample(["w", a, b], 3))} + setup, expr = setup.format(**fields), expr.format(**fields) + if _float_class(setup, expr) == want: + return setup, expr, index + return None + + +def single_check(p: Plan, facility: str, mode: str) -> Check | None: + """A check on draw, frac, now or pool. mode: bad, safe (same template, safe values) or filler.""" + E, rng, bad = p.entry, p.rng, mode == "bad" + tmpl = "filler" if mode == "filler" else "ternary" if bad and p.low and facility == "draw" else \ + p.hint[1] if p.hint[0] == facility and rng.random() < P_TWIN else rng.choice( + {"draw": ("list", "ternary", "table"), "frac": ("expr",), "now": ("stamp", "window", "deadline"), + "pool": ("list", "first")}[facility]) + imitate = not bad and (facility, tmpl) == p.hint # a decoy shaped exactly like the flaky check + if not p.hint[0]: + p.hint = (facility, tmpl) + if facility == "draw": + if tmpl == "filler": + rows = p.distinct(1) + return rows and Check(["count = 1 + env.draw(3)", f"assert [{p.call(rows[0][0])}] * count == " + f"[{rows[0][1]!r}] * count"], [rows[0][0]]) + m = rng.choice((2, 3)) if tmpl == "list" else 2 + rows = p.same(m) if not bad and (imitate or rng.random() < 0.5) else None + same = rows is not None + rows = rows or p.distinct(m) + if rows is None: + return None + (a, oa), (b, ob) = rows[0], rows[1] + want = f"== {oa!r}" if bad or same else f"in ({_lit([r[1] for r in rows])})" + if bad and rng.random() < 0.4: # a faulty check spelled like a safe one: the tuple misses one branch + other = next((o for _, o in p.rows if all(not (o == r[1]) for r in rows)), None) + if other is not None: + want = f"in ({_lit([oa, other] if rng.random() < 0.5 else [other, oa])})" + repair = [f"assert {p.call(a)} == {oa!r}"] if bad else None + if tmpl == "list": + items = [r[0] for r in rows] + rng.shuffle(items) + return Check([f"args = [{_lit(items)}][env.draw({m})]", f"assert {E}(*args) {want}"], items, repair) + if tmpl == "ternary": + k = rng.choice((12, 16, 20, 25, 30, 40)) if bad and p.low else rng.choice((2, 3, 4, 12, 20) if not bad else + (2, 3, 4)) + return Check([f"args = {a!r} if env.draw({k}) else {b!r}", f"assert {E}(*args) {want}"], [a, b], repair) + pairs = [(a, oa), (b, oa if bad else ob)] + rng.shuffle(pairs) + table = ", ".join(f"({x!r}, {y!r})" for x, y in pairs) + return Check([f"args, want = [{table}][env.draw(2)]", f"assert {E}(*args) == want"], [a, b], repair) + if facility == "pool": + if tmpl == "filler": + rows = p.distinct(2) + return rows and Check([f"got = [{E}(*a) for a in env.pool([{_lit([r[0] for r in rows])}])]", + f"assert len(got) == 2 and {rows[0][1]!r} in got and {rows[1][1]!r} in got"], + [r[0] for r in rows]) + rows = p.same(2) if not bad and ((imitate and tmpl == "first") or rng.random() < 0.5) else None + same = rows is not None + rows = rows or p.distinct(2) + if rows is None: + return None + (a, oa), (b, ob) = rows + if tmpl == "list": + listed = f"[{E}(*a) for a in env.pool([{a!r}, {b!r}])]" + if bad or same: + return Check([f"got = {listed}", f"assert got == [{oa!r}, {ob!r}]"], [a, b], + [f"got = [{E}(*a) for a in [{a!r}, {b!r}]]", f"assert got == [{oa!r}, {ob!r}]"] + if bad else None) + ordered = sorted([oa, ob], key=repr) + return Check([f"got = sorted({listed}, key=repr)", f"assert got == [{_lit(ordered)}]"], [a, b]) + index = rng.choice((0, -1)) + target = (a, oa) if index == 0 else (b, ob) + want = f"== {target[1]!r}" if bad or same else f"in ({oa!r}, {ob!r})" + other = next((o for _, o in p.rows if not (o == oa) and not (o == ob)), None) + if bad and other is not None and rng.random() < 0.4: + want = f"in ({_lit([target[1], other] if rng.random() < 0.5 else [other, target[1]])})" + return Check([f"first = env.pool([{a!r}, {b!r}])[{index}]", f"assert {E}(*first) {want}"], [a, b], + [f"assert {p.call(target[0])} == {target[1]!r}"] if bad else None) + rows = p.distinct(1) + if rows is None: + return None + (a, oa), = rows + if facility == "frac": + if tmpl == "filler": + expr = rng.choice(("0 < w < 1", "abs((w + 0.1) - 0.1 - w) < 1e-9")) + return Check(["w = env.frac()", f"assert {p.call(a)} == {oa!r} and {expr}"], [a]) + found = _float_expr(rng, ("low" if p.low else "normal") if bad else "safe", p.form if imitate else None) + if found is None: + return None + setup, expr, form = found + if p.form is None: + p.form = form + lines = ["w = env.frac()"] + ([setup] if setup else []) + [f"assert {p.call(a)} == {oa!r} and {expr}"] + return Check(lines, [a], [f"assert {p.call(a)} == {oa!r}"] if bad else None) + bucket = rng.choice((4000, 5000, 10000) if bad and p.low else (500, 1000, 2000, 2500) if bad else + (500, 1000, 2000, 2500, 4000, 5000, 10000)) + got = [f"got = {p.call(a)}"] + repair = got + [f"assert got == {oa!r}"] if bad else None + if tmpl == "filler": + return Check(["start = env.now()"] + got + [f"assert got == {oa!r} and env.now() - start < {bucket}"], [a]) + B, T = bucket, TICK + # (first line, check): the second read is always the first plus the tick, so each pair is faulty or safe + faulty = {"stamp": [(f"stamp = env.now() // {B}", f"env.now() // {B} == stamp"), + (f"stamp = (env.now() + {T}) // {B}", f"(env.now() - {T}) // {B} == stamp"), + (f"stamp = (env.now() - {T}) // {B}", f"env.now() // {B} == stamp")], + "window": [("start = env.now()", f"env.now() // {B} == start // {B}"), + (f"start = env.now() - {T}", f"env.now() // {B} == start // {B}")], + "deadline": [(f"deadline = (env.now() // {B} + 1) * {B}", "env.now() < deadline"), + (f"deadline = (env.now() - {T}) // {B} * {B} + {B}", "env.now() < deadline")]} + safe = {"stamp": [(f"stamp = (env.now() + {T}) // {B}", f"env.now() // {B} == stamp"), + (f"stamp = env.now() // {B}", f"(env.now() - {T}) // {B} == stamp"), + (f"stamp = env.now() // {B}", f"env.now() // {B} - stamp <= 1"), + (f"stamp = (env.now() - {T}) // {B}", f"env.now() // {B} >= stamp")], + "window": [("start = env.now()", f"(env.now() - {T}) // {B} == start // {B}"), + ("start = env.now()", f"env.now() // {B} - start // {B} <= 1")], + "deadline": [(f"deadline = (env.now() + {T}) // {B} * {B} + {B}", "env.now() < deadline"), + (f"deadline = env.now() + {B}", "env.now() < deadline")]} + options = faulty[tmpl][:1 if p.low and tmpl != "stamp" else None] if bad else safe[tmpl] + if bad and B == 500: # a two-tick window on a 500 ms bucket would fail on every run + options = [o for o in options if f"- {T}" not in o[0]] + if bad and p.low and tmpl == "stamp": + options = options[:2] # keep a low-rate flake's window at one tick + first, check = rng.choice(options) + return Check([first] + got + [f"assert got == {oa!r} and {check}"], [a], repair) + + +def state_unit(p: Plan, mode: str, key: str, single: bool = False) -> list[list[Check]] | None: + """Tests on the module-level dict: [reader, writer] or a single test. mode: bad, twin, safe.""" + E, rng, D = p.entry, p.rng, p.names["state"] + if mode == "safe" and (single or rng.random() < 0.4): + rows = p.distinct(1) + if rows is None: + return None + (c, oc), = rows + p.state[key] = c + if rng.random() < 0.5: + return [[Check([f"{D}[{key!r}] = {c!r}", f"assert {E}(*{D}[{key!r}]) == {oc!r}"], [c])]] + if rng.random() < 0.5: + return [[Check([f"case = {D}[{key!r}]", f"assert {E}(*case) == {oc!r}"], [c])]] + return [[Check([f"assert {E}(*{D}[{key!r}]) == {oc!r}"], [c])]] + reader_zone = p.zone + rows = p.distinct(1) + if rows is None: + return None + (a, oa), = rows + p.zone = "spare" if p.zones else "" + style = "set" if mode == "bad" or (p.hint[0] == "state" and rng.random() < P_TWIN) else \ + rng.choice(("set", "restore", "finally")) + rows = p.same(1, ok=lambda r: r[1] == oa) if style == "set" and mode != "bad" else \ + p.distinct(1, ok=lambda r: not (r[1] == oa)) + p.zone = reader_zone + if rows is None: + return None + (b, ob), = rows + p.state[key] = a + reader = [f"assert {E}(*{D}[{key!r}]) == {oa!r}"] if rng.random() < 0.5 else \ + [f"case = {D}[{key!r}]", f"assert {E}(*case) == {oa!r}"] + write = rng.choice((f"{D}[{key!r}] = {b!r}", f"{D}.update({{{key!r}: {b!r}}})")) + check = f"assert {E}(*{D}[{key!r}]) == {ob!r}" + if style == "set": + writer = [write, check] + elif style == "restore": + writer = [f"saved = {D}[{key!r}]", write, check, f"{D}[{key!r}] = saved"] + else: + writer = [f"saved = {D}[{key!r}]", write, "try:", f" {check}", "finally:", f" {D}[{key!r}] = saved"] + repair = [f"assert {p.call(a)} == {oa!r}"] if mode == "bad" else None + return [[Check(reader, [a], repair)], [Check(writer, [b])]] + + +def store_unit(p: Plan, mode: str, single: bool = False) -> list[list[Check]] | None: + """Tests calling the memoizing helper: [reader, warm-up caller] or a lone reader. mode: bad, twin, safe.""" + rng, H = p.rng, p.names["helper"] + if mode == "bad": + a, b = p.names["pair"] + else: + rows = p.distinct(1, ok=p.store_ok) + if rows is None: + return None + a = rows[0] + p.store.append(a) + b = None + if mode == "twin" or (not single and rng.random() < 0.6): + reader_zone, p.zone = p.zone, "spare" if p.zones else "" + hit = p.same(1, ok=lambda r: r[1] == a[1] and r[1] is not None and p.keyed(r[0]) == p.keyed(a[0])) + rows = [hit[0]] if hit else p.distinct(1, ok=lambda r: r[1] is not None and p.store_ok(r)) + p.zone = reader_zone + if rows is None: + return None + b = rows[0] + p.store.append(b) + call = f"{H}({_lit(a[0])})" + reader = [f"assert {call} == {a[1]!r}"] if rng.random() < 0.5 else [f"got = {call}", f"assert got == {a[1]!r}"] + tests = [[Check(reader, [a[0]], [f"assert {p.call(a[0])} == {a[1]!r}"] if mode == "bad" else None)]] + if b is not None: + warm = f"{H}({_lit(b[0])})" + tests.append([Check([rng.choice((f"assert {warm} is not None", f"assert len(repr({warm})) > 0", warm))], + [b[0]])]) + return tests + + +def choose_store_key(p: Plan, bad: bool) -> bool: + """Choose the helper's key; for a cache-leak culprit, a key under which two inputs collide.""" + kinds = ["prefix", "first", "length"] + p.rng.shuffle(kinds) + if not bad: + kind = p.rng.choice(kinds + ["full"]) + p.key = ("prefix", p.rng.randrange(5, 15)) if kind == "prefix" else (kind,) + return True + kill = p.free(lambda r: r[1] is not None) if not p.zones else \ + [r for r in p.free(lambda r: r[1] is not None) if json.dumps(r[0]) in p.zones["kill"]] + spare = [r for r in p.rows if json.dumps(r[0]) not in p.used and r[1] is not None + and (not p.zones or json.dumps(r[0]) in p.zones["spare"])] + for kind in kinds: + for a in kill: + for b in spare: + if a is b or a[1] == b[1]: + continue + ka, kb = repr(tuple(a[0])), repr(tuple(b[0])) + if kind == "prefix": + common = next((i for i in range(min(len(ka), len(kb))) if ka[i] != kb[i]), None) + if common is None or common < 4: + continue + p.key = ("prefix", common) + elif kind == "first" and not (len(a[0]) > 1 and repr(a[0][0]) == repr(b[0][0])): + continue + elif kind == "length" and len(ka) != len(kb): + continue + else: + p.key = (kind,) + p.mark([a, b]) + p.names["pair"] = (a, b) + p.store += [a, b] + return True + return False + + +def key_text(key: tuple) -> str: + return {"full": "repr(args)", "prefix": f"repr(args)[:{key[-1]}]", "first": "repr(args[0])", + "length": "len(repr(args))"}[key[0]] + + +def decoy_unit(p: Plan, facility: str, mode: str, room: int) -> list[list[Check]] | None: + if facility == "state": + key = p.rng.choice([k for k in KEY_NAMES if k not in p.state and k != p.names.get("state_key")]) + return state_unit(p, "safe", key, single=room < 2) + if facility == "store": + return store_unit(p, "safe", single=room < 2) + check = single_check(p, facility, mode) + return [[check]] if check else None diff --git a/components/qemedia/upstream/qe_arena/guest_harness.py b/components/qemedia/upstream/qe_arena/guest_harness.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4d4ea8b744f7a4151e79b29a2e23c3540389a2 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/guest_harness.py @@ -0,0 +1,292 @@ +# Runs INSIDE python.wasm (CPython 3.14, WASI preview1). The host passes this file with -c and the +# request as argv[1]. It is never imported by the server. +# +# No rlimits, signals or timers: the host meters every call with wasmtime fuel and caps linear +# memory. Protocol on fd 1, one os.write per line so the host sees call boundaries exactly; every +# line carries the per-run nonce the host generated, and the host ignores or rejects anything else: +# \x01B \n a call starts -> host sets fuel to this call's budget +# \x01E \n that call ended -> host records fuel used, refuels the harness +# \x01R \n that call's result row +# +# Frame hygiene: candidate code runs below exactly two frames, the closure returned by _setup() +# and the root module frame, whose globals are cleared before the closure runs. The closure's +# variables are the candidate's own namespace plus opaque objects: the nonce exists only inside +# itertools.cycle objects (no attribute or repr exposes their contents) and the pending inputs only +# inside a list iterator. The request, sys.argv and sys.orig_argv are gone by then. +import builtins, copy, gc, itertools, json, os, sys, types + +MONITOR_TOOL = 4 # sys.monitoring tool id used for the RAISE hook (0-2 and 5 are conventionally taken) + + +def _setup(): + req = json.loads(sys.argv[1]) + sys.argv[:] = ["python"] + sys.orig_argv[:] = [] + nonce = req.pop("nonce").encode("ascii") + begin = itertools.cycle((b"\x01B " + nonce + b"\n",)) + end = itertools.cycle((b"\x01E " + nonce + b"\n",)) + head = itertools.cycle((b"\x01R " + nonce + b" ",)) + del nonce + write, dumps, deepcopy, collect, freeze = os.write, json.dumps, copy.deepcopy, gc.collect, gc.freeze + + def emit(marker, payload=b""): + view = memoryview(next(marker) + payload) + while view: + view = view[write(1, view):] + + def row(obj): + emit(head, dumps(obj, allow_nan=True).encode("utf-8", "surrogatepass") + b"\n") + + real = {name: __import__(name) for name in req["modules"]} + if req.get("probe"): + row(_probe(req["probe"], real, req["modules"])) + return None + proxies = {} + for name, exports in req["modules"].items(): + proxy = types.ModuleType("_arena_safe_" + name) + for attr in exports: + if hasattr(real[name], attr): + setattr(proxy, attr, getattr(real[name], attr)) + proxies[name] = proxy + if "re" in proxies: + # re.DEBUG (128) prints the parse tree. Stdout is discarded and the gate refuses a literal flag; + # the proxy also clears the bit, so no flags value reaching re can ask for debug output. + positions = {"compile": 1, "search": 2, "match": 2, "fullmatch": 2, "findall": 2, "finditer": 2, + "split": 3, "sub": 4, "subn": 4} + wrap_ns = {"__builtins__": {"len": len}, "_re": real["re"], "_KEEP": ~128} + exec("def _strip(a, k, at):\n" + " if 'flags' in k:\n k['flags'] = k['flags'] & _KEEP\n" + " if len(a) > at:\n a = a[:at] + (a[at] & _KEEP,) + a[at + 1:]\n" + " return a, k\n" + + "".join(f"def {name}(*a, **k):\n a, k = _strip(a, k, {at})\n return _re.{name}(*a, **k)\n" + for name, at in positions.items()), wrap_ns) + for name in positions: + if hasattr(proxies["re"], name): + setattr(proxies["re"], name, wrap_ns[name]) + helper_ns = {"__builtins__": {"ImportError": ImportError, "repr": repr, "type": type, "str": str}, + "_M": proxies} + exec("def __import__(name, globals=None, locals=None, fromlist=(), level=0):\n" + " if level == 0 and type(name) is str and name in _M:\n" + " return _M[name]\n" + " raise ImportError('import of ' + repr(name) + ' is not allowed')\n" + "def print(*args, **kwargs):\n" + " return None\n", helper_ns) + safe = {name: getattr(builtins, name) for name in req["builtins"]} + safe["__import__"] = helper_ns["__import__"] + safe["print"] = helper_ns["print"] + del real, proxies, helper_ns + + def describe(exc): + try: + return (type(exc).__name__ + ": " + str(exc))[:200] + except BaseException: + return type(exc).__name__ + + def normalize(value, depth, budget): + budget[0] += 1 + if depth > 100 or budget[0] > 200000: + raise ValueError("too large") + t = type(value) + if value is None or t is bool or t is int or t is float or t is str: + return value + if t is list or t is tuple: + return [normalize(v, depth + 1, budget) for v in value] + if t is dict: + out = {} + for k, v in value.items(): + if type(k) is not str: + raise ValueError("non-str key") + out[k] = normalize(v, depth + 1, budget) + return out + raise ValueError("type " + t.__name__) + + def classify(exc): + # MemoryError comes from the capped linear memory and RecursionError from the depth limit: + # limits of the sandbox, not behaviour. The gate bans the MemoryError name, so candidate code + # cannot raise one on purpose. + if isinstance(exc, (MemoryError, RecursionError)): + return {"k": "resource", "e": describe(exc)} + return {"k": "exc", "v": type(exc).__name__, "e": describe(exc)} + + # Candidate code can catch a MemoryError or RecursionError with `except Exception` and return a + # value the cap chose. A RAISE monitor (a tool id the candidate cannot reach: the gate makes sys + # unreachable) sees every raise, caught or not, so such a call is reported as resource. + hit = [False] + resource_types = (MemoryError, RecursionError) + + def on_raise(code, offset, exc): + if isinstance(exc, resource_types): + hit[0] = True + + # Python-level writes to stdout/stderr (re.DEBUG prints its parse tree, warnings print to stderr) go + # nowhere: only the harness writes to fd 1, with os.write, so nothing else can break the protocol. + class _Discard: + def write(self, text): + return len(text) + + def flush(self): + return None + + sys.stdout = sys.stderr = _Discard() + + monitoring = sys.monitoring + monitoring.use_tool_id(MONITOR_TOOL, "qe-arena") + monitoring.register_callback(MONITOR_TOOL, monitoring.events.RAISE, on_raise) + monitoring.set_events(MONITOR_TOOL, monitoring.events.RAISE) + del monitoring + + source, entry = req["source"], req["entry"] + calls = iter(req["calls"]) + max_value, max_total = req["max_value_bytes"], req["max_total_bytes"] + del req + + def encode(obj): + return dumps(obj, allow_nan=True).encode("utf-8", "surrogatepass") + b"\n" + + def settle(value, err, total): + """Build the call's result row. Runs BEFORE the end marker, on the call's own fuel: str() of an + exception, normalizing and serializing can all run candidate code (an instance's overridden + method, a generator's finally block), which must not spend the harness's refill.""" + if err is not None: + return encode(classify(err)), 0 + try: + value = normalize(value, 0, [0]) + text = dumps(value, allow_nan=True) + except MemoryError: + return encode({"k": "resource", "e": "memory: result"}), 0 + except (ValueError, RecursionError, TypeError): + return encode({"k": "crash", "e": "unserializable"}), 0 + if len(text) > max_value or total + len(text) > max_total: + return encode({"k": "crash", "e": "output too large"}), 0 + # the value is serialized once: splice its JSON text into the row + return b'{"k": "ok", "v": ' + text.encode("utf-8", "surrogatepass") + b"}\n", len(text) + + def run(): + # Everything alive now (interpreter, stdlib, harness) moves to the permanent generation, so the + # per-call collect() scans only what candidate code created: about 6 M fuel per call less. + freeze() + ns = {"__builtins__": safe, "__name__": "candidate"} + hit[0] = False + emit(begin) # the module body is metered with the module budget + try: + exec(compile(source, "", "exec"), ns) + payload = None + except BaseException as exc: + payload = encode({"k": "crash", "e": "module: " + describe(exc)}) + exc = None + if hit[0]: + payload = encode({"k": "resource", "e": "module: memory or recursion limit"}) + fn = ns.get(entry) if payload is None else None + if payload is None and not callable(fn): + payload = encode({"k": "crash", "e": "entry " + repr(entry) + " is not a function"}) + emit(end) + if payload is not None: + emit(head, payload) + return + emit(head, encode({"k": "ok"})) + total = 0 + for call in calls: + args = deepcopy(call) + del call + hit[0] = False + write(1, next(begin)) # one write: the host's fd_write always takes the whole marker + try: + value, err = fn(*args), None + except BaseException as exc: + value, err = None, exc + exc = None + try: + payload, size = settle(value, err, total) + except BaseException: + payload, size = encode({"k": "crash", "e": "result could not be read"}), 0 + # Release everything the call left behind BEFORE the last resource check, on the call's own + # fuel: dropping the value, the exception (whose traceback holds the call's frames) and the + # arguments can run candidate code (a generator's finally block), and a cycle keeps such + # objects alive until a collection, so collect now rather than later in the harness. + value = err = args = None + collect() + if hit[0]: + payload, size = encode({"k": "resource", "e": "memory or recursion limit reached during the call"}), 0 + write(1, next(end)) + total += size + emit(head, payload) + + return run + + +def _probe(kind, real, modules): + """Host-requested self-report (tests only). Candidate source never selects this path.""" + if kind == "surface": + import time + report = {"version": sys.version.split()[0], "path": sys.path, "env": dict(os.environ), "missing": {}} + for label, action in (("cwd", os.getcwd), ("root", lambda: sorted(os.listdir("/"))), + ("lib", lambda: sorted(os.listdir("/lib"))), ("time", time.time), + ("monotonic_ns", lambda: [time.monotonic_ns(), time.monotonic_ns()]), + ("urandom", lambda: os.urandom(8).hex()), + ("stat_lib", lambda: list(os.stat("/lib"))), + ("stat_zip", lambda: list(os.stat("/lib/python314.zip"))), + ("scandir_ino", lambda: [e.inode() for e in os.scandir("/lib")]), + ("sleep", lambda: time.sleep(0.01))): + try: + report[label] = action() + except BaseException as exc: + report[label] = "error: " + type(exc).__name__ + for name, exports in modules.items(): + absent = [attr for attr in exports if not hasattr(real[name], attr)] + if absent: + report["missing"][name] = absent + for label, action in (("write_lib", lambda: open("/lib/x", "w")), ("read_etc", lambda: open("/etc/passwd")), + ("listdir_up", lambda: os.listdir("/lib/..")), ("socket", _socket)): + try: + action() + report[label] = "allowed" + except BaseException as exc: + report[label] = type(exc).__name__ + return report + if kind == "reach": + return _reach(real, modules) + return {"error": "unknown probe"} + + +def _socket(): + import socket + socket.create_connection(("1.1.1.1", 53), timeout=1) + + +def _reach(real, modules): + """Walk every public attribute reachable from the exported names (depth 4) and report modules, + frames, code objects, loaders and import machinery: everything a gated candidate must not reach.""" + seen, found = set(), [] + frontier = [(name + "." + attr, getattr(real[name], attr)) + for name, exports in modules.items() for attr in exports if hasattr(real[name], attr)] + for depth in range(4): + nxt = [] + for path, obj in frontier: + if id(obj) in seen: + continue + seen.add(id(obj)) + bad = (isinstance(obj, (types.ModuleType, types.FrameType, types.CodeType, types.TracebackType)) + or obj is os or obj is sys or obj is builtins or obj is __import__ + or hasattr(obj, "exec_module") or hasattr(obj, "load_module") or hasattr(obj, "find_spec")) + if bad: + found.append(path + ": " + type(obj).__name__) + continue + if len(seen) > 50000: + break + try: + names = [n for n in dir(obj) if not n.startswith("_")] + except BaseException: + continue + for attr in names: + try: + nxt.append((path + "." + attr, getattr(obj, attr))) + except BaseException: + pass + frontier = nxt + return {"visited": len(seen), "found": found} + + +if __name__ == "__main__": + # The root frame is the candidate's outermost ancestor: clear its globals, then run. The closure + # travels as an argument, so nothing in the module namespace survives. + (lambda run: (globals().clear(), run is not None and run()))(_setup()) diff --git a/components/qemedia/upstream/qe_arena/keys/manifest_ed25519.pub b/components/qemedia/upstream/qe_arena/keys/manifest_ed25519.pub new file mode 100644 index 0000000000000000000000000000000000000000..43f10d18d7b4063a4ff633875318356911fd4501 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/keys/manifest_ed25519.pub @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEAPBa4E2mKABjZEx+vbn1VicJdMHtc5jReQUHnColrg0o= +-----END PUBLIC KEY----- diff --git a/components/qemedia/upstream/qe_arena/manifest.py b/components/qemedia/upstream/qe_arena/manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..72279f55059b942b1a819803d18545ad55c6e4cd --- /dev/null +++ b/components/qemedia/upstream/qe_arena/manifest.py @@ -0,0 +1,158 @@ +"""Signed task manifests: a verifiable record of what graded a (task_id, seed). + +Execution is deterministic (see ``sandbox``), so a task's hidden inputs, reference outputs and +their fuel are a pure function of (task_id, seed) plus the exact runtime, harness and corpus file. +A manifest pins all of those by sha256 (hashes only; no hidden value ever appears in one), signs +the canonical JSON with Ed25519, and lets anyone holding the public key recompute it from +(task_id, seed) and check both the signature and the content. + +Offline only: the server never imports this module and never holds the private key. Keys and +signing live in ``scripts/sign_manifest.py``; the public key is ``qe_arena/keys/manifest_ed25519.pub``. +""" + +from __future__ import annotations + +import base64 +import hashlib +import importlib.metadata +import json +from pathlib import Path +from typing import Any + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey + +from . import sandbox, wasi_worker +from .tasks import Task, make_task + +SCHEMA = "qe-arena-task-manifest/1" +DOMAIN = (SCHEMA + "\n").encode() # signatures over manifests can never be replayed as anything else +PACKAGE = Path(__file__).resolve().parent +DEFAULT_PUBLIC_KEY = PACKAGE / "keys" / "manifest_ed25519.pub" + + +def canonical(obj: Any) -> bytes: + """The one byte encoding that is hashed and signed: sorted keys, no whitespace, ASCII.""" + return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=True).encode() + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _file_sha(path: Path) -> str: + return _sha(path.read_bytes()) + + +def _grading_sources(task: Task) -> list[str]: + p = task.private + if task.family == "qe_bugfix": + return [p["original"], p["buggy"]] + if task.family == "qe_flaky": + return [p["original"], p["harness"]] + [m["source"] for m in p["mutants"]] + return [p["original"]] + [m["source"] for m in p["mutants"]] + + +def _hidden(task: Task) -> tuple[int, object, object]: + """(count, hidden inputs, reference outputs) for the family's grader. + + A flaky task has no input list: its grader replays the graded runs and the sweep, and compares + the answer with the flaky test, its cause and the reference repair.""" + p = task.private + if task.family == "qe_flaky": + inputs = {"graded": p["graded"], "shown": p["shown"], "sweep": p["sweep"], "band": p["band"], + "boxes": p["boxes"], "region": p["region"], "prefix": p["prefix"], + "protected": p["protected"], "tests": p["tests"]} + return len(p["graded"]), inputs, {"victim": p["victim"], "cause": p["cause"], "repair": p["repair"]} + return len(p["inputs"]), p["inputs"], [[r.kind, r.value, r.fuel] for r in p["reference"]] + + +def manifest_for(task: Task) -> dict: + p = task.private + root = sandbox.runtime_root() + count, inputs, reference = _hidden(task) + extra = {"edit_budget": p["edit_budget"]} if "edit_budget" in p else {} + return extra | { + "schema": SCHEMA, + "task_id": task.task_id, + "seed": task.seed, + "family": task.family, + "difficulty": task.difficulty, + "corpus": p["corpus"], + "entry": p["entry"], + "runtime": { + "python.wasm": _file_sha(root / "python.wasm"), + "lib/python314.zip": _file_sha(root / "lib" / "python314.zip"), + "guest_harness.py": _file_sha(PACKAGE / "guest_harness.py"), + "wasmtime": importlib.metadata.version("wasmtime"), + }, + "corpus_file_sha256": _file_sha(PACKAGE / "corpus" / f"{p['corpus']}.py"), + "hidden_inputs_count": count, + "hidden_inputs_sha256": _sha(canonical(inputs)), + "reference_outputs_sha256": _sha(canonical(reference)), + "grading_sources_sha256": _sha(canonical(_grading_sources(task))), + "observation_sha256": _sha(canonical([task.prompt, task.files])), + "budgets": { + "fuel_per_call": sandbox.FUEL_PER_CALL, + "module_fuel": sandbox.MODULE_FUEL, + "startup_fuel": wasi_worker.STARTUP_FUEL, + "harness_fuel": wasi_worker.HARNESS_FUEL, + "mem_mb": sandbox.DEFAULT_MEM_MB, + }, + } + + +def build_manifest(task_id: str, seed: int) -> dict: + """Regenerate the task and describe it. Two calls with the same inputs return equal dicts.""" + return manifest_for(make_task(task_id, seed)) + + +def key_id(public_key: Ed25519PublicKey) -> str: + raw = public_key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + return _sha(raw)[:16] + + +def sign(manifest: dict, private_key: Ed25519PrivateKey) -> dict: + signature = private_key.sign(DOMAIN + canonical(manifest)) + return {"manifest": manifest, "key_id": key_id(private_key.public_key()), + "signature": base64.b64encode(signature).decode("ascii")} + + +def verify_signature(envelope: dict, public_key: Ed25519PublicKey) -> bool: + """True only for an envelope signed by this key over exactly this manifest.""" + try: + if set(envelope) != {"manifest", "key_id", "signature"} or envelope["key_id"] != key_id(public_key): + return False + public_key.verify(base64.b64decode(envelope["signature"], validate=True), + DOMAIN + canonical(envelope["manifest"])) + return True + except (InvalidSignature, ValueError, TypeError, KeyError): + return False + + +def verify_task(envelope: dict, public_key: Ed25519PublicKey | None = None) -> tuple[bool, str]: + """Check the signature, then recompute the manifest from its (task_id, seed) and compare.""" + key = public_key if public_key is not None else load_public_key() + if not verify_signature(envelope, key): + return False, "bad signature" + manifest = envelope["manifest"] + if not isinstance(manifest, dict) or manifest.get("schema") != SCHEMA: + return False, "unknown schema" + try: + recomputed = build_manifest(manifest["task_id"], manifest["seed"]) + except (KeyError, ValueError, RuntimeError) as exc: + return False, f"cannot rebuild the task: {exc}" + if recomputed != manifest: + changed = sorted(k for k in set(recomputed) | set(manifest) if recomputed.get(k) != manifest.get(k)) + return False, "recomputed manifest differs in: " + ", ".join(changed) + return True, "ok" + + +def load_public_key(path: Path = DEFAULT_PUBLIC_KEY) -> Ed25519PublicKey: + if not path.exists(): + raise FileNotFoundError(f"{path}: no manifest public key; create one with scripts/sign_manifest.py keygen") + key = serialization.load_pem_public_key(path.read_bytes()) + if not isinstance(key, Ed25519PublicKey): + raise ValueError(f"{path} is not an Ed25519 public key") + return key diff --git a/components/qemedia/upstream/qe_arena/mutation.py b/components/qemedia/upstream/qe_arena/mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..1e59c0ec8c17893baa7d8f87bc4729af22382284 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/mutation.py @@ -0,0 +1,944 @@ +"""Deterministic, formatting-preserving AST mutation of corpus functions. + +Every mutation site is one concrete textual replacement at an exact (line, column) span of the +original source. Columns are 0-based *character* offsets (the AST reports UTF-8 byte offsets; they +are converted here), lines are 1-based. Applying a site splices only its span, so comments, +whitespace and every other character of the source are untouched. +""" + +from __future__ import annotations + +import ast +import builtins +import difflib +import io +import keyword +import re +import tokenize +from dataclasses import dataclass +from typing import Iterator, Sequence + +CLASSIC_OPERATORS = ( + "cmp_boundary", + "cmp_negate", + "arith_swap", + "const_off_by_one", + "bool_swap", + "not_drop", + "slice_shift", + "range_bound", + "return_flip", + "augassign_swap", + "min_max_swap", + "break_continue_swap", +) +# Shapes of real defects (HumanEvalFix/DebugBench taxonomy and RuVector PR #1125), not token flips. +REALISTIC_OPERATORS = ( + "guard_delete", # missing logic: an early-exit guard is gone + "arm_drop", # missing logic: one if/elif arm of a dispatch is gone + "member_drop", # missing logic: an allowlist literal lost one member + "condition_drop", # missing logic: one operand of an and/or is gone + "extra_condition", # excess logic: a branch also requires a variable to be truthy + "call_swap", # function misuse: a sibling call with a compatible signature + "var_swap", # variable misuse: another in-scope variable of the same type + "const_sibling", # value misuse: another literal of the same type from the same function +) +OPERATORS = CLASSIC_OPERATORS + REALISTIC_OPERATORS + + +@dataclass(frozen=True) +class Site: + operator: str + lineno: int + col: int + end_lineno: int + end_col: int + original: str + replacement: str + description: str + + +# --------------------------------------------------------------------------- source geometry + +_LINE_RE = re.compile(r"[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+\Z") + + +class _Text: + """Line table that maps AST/tokenize positions to absolute string offsets.""" + + def __init__(self, source: str) -> None: + self.source = source + self.lines = _LINE_RE.findall(source) + self.starts = [] + pos = 0 + for line in self.lines: + self.starts.append(pos) + pos += len(line) + self.starts.append(pos) + + def line(self, lineno: int) -> str: + return self.lines[lineno - 1] if 0 < lineno <= len(self.lines) else "" + + def char_col(self, lineno: int, byte_col: int) -> int: + return len(self.line(lineno).encode("utf-8")[:byte_col].decode("utf-8", "replace")) + + def offset(self, lineno: int, col: int) -> int: + if lineno == len(self.lines) + 1 and col == 0: + return len(self.source) + if not 0 < lineno <= len(self.lines): + raise ValueError(f"line {lineno} out of range") + return self.starts[lineno - 1] + col + + def node_span(self, node: ast.AST) -> tuple[int, int, int, int]: + return ( + node.lineno, + self.char_col(node.lineno, node.col_offset), + node.end_lineno, + self.char_col(node.end_lineno, node.end_col_offset), + ) + + def segment(self, span: tuple[int, int, int, int]) -> str: + return self.source[self.offset(span[0], span[1]):self.offset(span[2], span[3])] + + +def _tokens(source: str) -> list[tokenize.TokenInfo]: + keep = (tokenize.OP, tokenize.NAME) + return [t for t in tokenize.generate_tokens(io.StringIO(source).readline) if t.type in keep] + + +def _parents(tree: ast.AST) -> dict[ast.AST, ast.AST]: + parents = {} + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + parents[child] = node + return parents + + +def _skipped_subtrees(tree: ast.AST) -> set[ast.AST]: + """Nodes inside f-strings, decorators and annotations: never mutated.""" + roots: list[ast.AST] = [] + for node in ast.walk(tree): + if isinstance(node, ast.JoinedStr): + roots.append(node) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + roots.extend(node.decorator_list) + if getattr(node, "returns", None) is not None: + roots.append(node.returns) + if isinstance(node, ast.arg) and node.annotation is not None: + roots.append(node.annotation) + if isinstance(node, ast.AnnAssign): + roots.append(node.annotation) + skipped: set[ast.AST] = set() + for root in roots: + skipped.update(ast.walk(root)) + return skipped + + +# --------------------------------------------------------------------------- site discovery + +_CMP_TEXT = { + ast.Lt: ("<",), ast.LtE: ("<=",), ast.Gt: (">",), ast.GtE: (">=",), + ast.Eq: ("==",), ast.NotEq: ("!=",), + ast.In: ("in",), ast.NotIn: ("not", "in"), ast.Is: ("is",), ast.IsNot: ("is", "not"), +} +_CMP_SWAP = { + ast.Lt: ("cmp_boundary", "<="), ast.LtE: ("cmp_boundary", "<"), + ast.Gt: ("cmp_boundary", ">="), ast.GtE: ("cmp_boundary", ">"), + ast.Eq: ("cmp_negate", "!="), ast.NotEq: ("cmp_negate", "=="), + ast.In: ("cmp_negate", "not in"), ast.NotIn: ("cmp_negate", "in"), + ast.Is: ("cmp_negate", "is not"), ast.IsNot: ("cmp_negate", "is"), +} +_ARITH_SWAP = {ast.Add: ("+", "-"), ast.Sub: ("-", "+"), ast.Mult: ("*", "//"), ast.FloorDiv: ("//", "*")} +_BOOL_SWAP = {ast.And: ("and", "or"), ast.Or: ("or", "and")} +_AUG_SWAP = {ast.Add: ("+=", "-="), ast.Sub: ("-=", "+=")} +# Expressions that bind at least as tightly as binary "+", so "e + 1" means "(e) + 1". +_TIGHT_BINOPS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.MatMult, ast.Pow) +_TIGHT_EXPRS = (ast.Name, ast.Constant, ast.Attribute, ast.Subscript, ast.Call, ast.List, ast.Tuple, + ast.Dict, ast.Set, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) + + +def _is_int_literal(node: ast.AST) -> bool: + if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)): + node = node.operand + return isinstance(node, ast.Constant) and type(node.value) is int + + +def _is_str_literal(node: ast.AST) -> bool: + return isinstance(node, ast.JoinedStr) or ( + isinstance(node, ast.Constant) and isinstance(node.value, (str, bytes))) + + +def _is_range_call(node: ast.AST) -> bool: + return isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "range" + + +class _Finder: + def __init__(self, source: str) -> None: + self.text = _Text(source) + self.tree = ast.parse(source) + self.tokens = _tokens(source) + self.parents = _parents(self.tree) + self.skipped = _skipped_subtrees(self.tree) + self.sites: list[Site] = [] + + # -- helpers + def _site(self, operator: str, span: tuple[int, int, int, int], replacement: str) -> None: + original = self.text.segment(span) + if original == replacement: + return + description = f"line {span[0]}: {original!r} -> {replacement!r} ({operator})" + self.sites.append(Site(operator, span[0], span[1], span[2], span[3], original, replacement, + description)) + + def _tokens_between(self, start: tuple[int, int], end: tuple[int, int]) -> list[tokenize.TokenInfo]: + return [t for t in self.tokens if t.start >= start and t.end <= end and t.string not in "()"] + + def _op_span(self, left: ast.AST, right: ast.AST, expect: tuple[str, ...]): + """Span of the operator token(s) strictly between two operand nodes.""" + _, _, ll, lc = self.text.node_span(left) + rl, rc, _, _ = self.text.node_span(right) + found = self._tokens_between((ll, lc), (rl, rc)) + if tuple(t.string for t in found) != expect: + return None + return (found[0].start[0], found[0].start[1], found[-1].end[0], found[-1].end[1]) + + def _shifted(self, expr: ast.AST, operator: str) -> None: + span = self.text.node_span(expr) + text = self.text.segment(span) + tight = isinstance(expr, _TIGHT_EXPRS) or ( + isinstance(expr, ast.BinOp) and isinstance(expr.op, _TIGHT_BINOPS)) or ( + isinstance(expr, ast.UnaryOp) and not isinstance(expr.op, ast.Not)) + base = text if tight else f"({text})" + self._site(operator, span, f"{base} + 1") + self._site(operator, span, f"{base} - 1") + + # -- operators + def visit(self) -> None: + for node in ast.walk(self.tree): + if node in self.skipped: + continue + handler = getattr(self, "_" + type(node).__name__, None) + if handler is not None: + handler(node) + + def _Compare(self, node: ast.Compare) -> None: + operands = [node.left, *node.comparators] + for i, op in enumerate(node.ops): + span = self._op_span(operands[i], operands[i + 1], _CMP_TEXT[type(op)]) + if span is not None: + operator, replacement = _CMP_SWAP[type(op)] + self._site(operator, span, replacement) + + def _BinOp(self, node: ast.BinOp) -> None: + swap = _ARITH_SWAP.get(type(node.op)) + if swap is None or _is_str_literal(node.left) or _is_str_literal(node.right): + return + span = self._op_span(node.left, node.right, (swap[0],)) + if span is not None: + self._site("arith_swap", span, swap[1]) + + def _AugAssign(self, node: ast.AugAssign) -> None: + swap = _AUG_SWAP.get(type(node.op)) + if swap is None or _is_str_literal(node.value): + return + span = self._op_span(node.target, node.value, (swap[0],)) + if span is not None: + self._site("augassign_swap", span, swap[1]) + + def _BoolOp(self, node: ast.BoolOp) -> None: + word, other = _BOOL_SWAP[type(node.op)] + for left, right in zip(node.values, node.values[1:]): + span = self._op_span(left, right, (word,)) + if span is not None: + self._site("bool_swap", span, other) + + def _UnaryOp(self, node: ast.UnaryOp) -> None: + if not isinstance(node.op, ast.Not): + return + line, col, _, _ = self.text.node_span(node) + if self.text.line(line)[col:col + 3] != "not": + return + end = col + 3 + rest = self.text.line(line) + while end < len(rest) and rest[end] in " \t": + end += 1 + self._site("not_drop", (line, col, line, end), "") + + def _Constant(self, node: ast.Constant) -> None: + if type(node.value) is not int: + return + parent = self.parents.get(node) + if _is_range_call(parent) and len(parent.args) == 3 and parent.args[2] is node: + return + needs_parens = ( + (isinstance(parent, ast.BinOp) and isinstance(parent.op, ast.Pow) and parent.left is node) + or (isinstance(parent, (ast.Attribute, ast.Subscript)) and parent.value is node) + or (isinstance(parent, ast.Call) and parent.func is node)) + span = self.text.node_span(node) + for value in (node.value + 1, node.value - 1): + text = str(value) + if value < 0 and needs_parens: + text = f"({text})" + self._site("const_off_by_one", span, text) + + def _Subscript(self, node: ast.Subscript) -> None: + if not isinstance(node.slice, ast.Slice): + return + for bound in (node.slice.lower, node.slice.upper): + if bound is not None and not _is_int_literal(bound) and bound not in self.skipped: + self._shifted(bound, "slice_shift") + + def _Call(self, node: ast.Call) -> None: + func = node.func + if isinstance(func, ast.Name) and func.id in ("min", "max"): + self._site("min_max_swap", self.text.node_span(func), "max" if func.id == "min" else "min") + if _is_range_call(node) and 1 <= len(node.args) <= 3 and not node.keywords: + stop = node.args[0] if len(node.args) == 1 else node.args[1] + if not isinstance(stop, ast.Starred) and not _is_int_literal(stop): + self._shifted(stop, "range_bound") + + def _Return(self, node: ast.Return) -> None: + value = node.value + if isinstance(value, ast.Constant) and type(value.value) is bool: + self._site("return_flip", self.text.node_span(value), str(not value.value)) + + def _Break(self, node: ast.Break) -> None: + self._site("break_continue_swap", self.text.node_span(node), "continue") + + def _Continue(self, node: ast.Continue) -> None: + self._site("break_continue_swap", self.text.node_span(node), "break") + + +# --------------------------------------------------------------------------- realistic operators + +_EXITS = (ast.Return, ast.Raise, ast.Continue, ast.Break) +# Sibling calls with a compatible signature. Method siblings are swapped on any receiver. +_NAME_SIBLINGS = {"any": ("all",), "all": ("any",), "round": ("int",)} +_ITER_SIBLINGS = {"sorted": ("reversed",), "reversed": ("sorted",)} # only where the result is iterated +# Method siblings by receiver type. They are used only where the receiver's type is inferred, and only +# swaps that change values are listed: values/keys or remove/discard would mostly kill by raising. +_METHOD_SIBLINGS = { + "str": { + "startswith": ("endswith",), "endswith": ("startswith",), + "lower": ("upper",), "upper": ("lower",), + "strip": ("lstrip", "rstrip"), "lstrip": ("strip", "rstrip"), "rstrip": ("strip", "lstrip"), + "find": ("rfind",), "rfind": ("find",), "index": ("rindex",), "rindex": ("index",), + "split": ("rsplit",), "rsplit": ("split",), + "partition": ("rpartition",), "rpartition": ("partition",), + "isalpha": ("isalnum",), "isalnum": ("isalpha",), "isdigit": ("isalnum",), + "islower": ("isupper",), "isupper": ("islower",), + }, + "list": {"append": ("extend",), "extend": ("append",)}, +} +_MODULE_SIBLINGS = {("math", "floor"): ("ceil",), ("math", "ceil"): ("floor",)} +_STR_METHODS = frozenset({"lower", "upper", "strip", "lstrip", "rstrip", "startswith", "endswith", "split", + "rsplit", "find", "rfind", "replace", "encode", "isdigit", "isalpha", "isalnum", + "partition", "rpartition", "splitlines", "title", "casefold", "zfill"}) +_METHOD_RESULT = { + **{m: "str" for m in ("lower", "upper", "strip", "lstrip", "rstrip", "join", "replace", "title", + "casefold", "zfill")}, + **{m: "int" for m in ("count", "find", "rfind", "index", "rindex")}, + **{m: "list" for m in ("split", "rsplit", "splitlines")}, + **{m: "bool" for m in ("startswith", "endswith", "isdigit", "isalpha", "isalnum", "islower", "isupper")}, +} +_CALL_RESULT = {"len": "int", "ord": "int", "int": "int", "str": "str", "chr": "str", "repr": "str", + "sorted": "list", "list": "list", "dict": "dict", "set": "set", "float": "float", "bool": "bool"} +_SWAP_TYPES = frozenset({"int", "str", "list", "dict", "set", "bool", "float"}) +_LOOSE = (ast.BoolOp, ast.IfExp, ast.NamedExpr, ast.Lambda) +_COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) + + +def _iterable_value(node: ast.AST, function) -> bool: + if isinstance(node, (ast.List, ast.Tuple, ast.ListComp)): + return True + return _expr_type(node, function.types if function is not None else {}) in ("list", "str") + + +def _paren(text: str, node: ast.AST) -> str: + return f"({text})" if isinstance(node, _LOOSE) else text + + +class _Function: + """Scope facts for one function: bindings, dominance between statements, simple types.""" + + def __init__(self, func: ast.FunctionDef, parents: dict) -> None: + self.func = func + self.parents = parents + args = func.args + self.params = [a.arg for a in [*args.posonlyargs, *args.args, *args.kwonlyargs]] + self.params += [a.arg for a in (args.vararg, args.kwarg) if a is not None] + self.stores: dict[str, list[ast.Name]] = {} + self.loads: list[ast.Name] = [] + self.comp_names: set[str] = set() + self.position: dict[ast.stmt, tuple[int, int]] = {} + self._collect(func, in_comp=False) + self.types = self._infer_types() + + def _collect(self, node: ast.AST, in_comp: bool) -> None: + for field, value in ast.iter_fields(node): + if isinstance(value, list) and value and all(isinstance(v, ast.stmt) for v in value): + for i, stmt in enumerate(value): + self.position[stmt] = (id(value), i) + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)): + continue # a nested scope is analysed on its own + comp = in_comp or isinstance(child, _COMPREHENSIONS) + if isinstance(child, ast.Name): + if isinstance(child.ctx, ast.Store): + (self.comp_names.add(child.id) if comp else self.stores.setdefault(child.id, []).append(child)) + elif isinstance(child.ctx, ast.Load): + self.loads.append(child) + self._collect(child, comp) + + def statement(self, node: ast.AST) -> ast.stmt: + while not isinstance(node, ast.stmt): + node = self.parents[node] + return node + + def _ancestors(self, stmt: ast.stmt): + node = stmt + while node is not None and node is not self.func: + if isinstance(node, ast.stmt): + yield node + node = self.parents.get(node) + + def dominates(self, binding: ast.Name, use: ast.Name) -> bool: + """True if ``binding`` has certainly executed whenever ``use`` runs.""" + bound_at = self.statement(binding) + ancestors = list(self._ancestors(self.statement(use))) + if isinstance(bound_at, ast.For) and any(binding is n for n in ast.walk(bound_at.target)): + # A loop variable exists only inside the body: the loop may run zero times. + return any(self._inside(a, bound_at.body) for a in ancestors) + container, index = self.position.get(bound_at, (None, -1)) + return any(self.position.get(a, (None, -1))[0] == container and self.position[a][1] > index + for a in ancestors) + + @staticmethod + def _inside(stmt: ast.stmt, body: list) -> bool: + return any(stmt is s for s in body) + + def bound_names(self) -> set[str]: + return (set(self.stores) | set(self.params)) - self.comp_names + + # -- types + def _infer_types(self) -> dict[str, str]: + types: dict[str, str] = {} + for _ in range(3): + found: dict[str, set] = {} + for name in self.params: + found[name] = self._param_types(name, types) + for name, nodes in self.stores.items(): + found.setdefault(name, set()).update(self._binding_type(n, types) for n in nodes) + types = {n: next(iter(t)) for n, t in found.items() if len(t) == 1 and None not in t} + return {n: t for n, t in types.items() if t in _SWAP_TYPES and n not in self.comp_names} + + def _binding_type(self, node: ast.Name, types: dict) -> str | None: + parent = self.parents[node] + if isinstance(parent, ast.Assign) and node in parent.targets: + return _expr_type(parent.value, types) + if isinstance(parent, ast.AugAssign): + kind = _expr_type(parent.value, types) + return kind if kind == types.get(node.id) or node.id not in types else None + if isinstance(parent, ast.NamedExpr): + return _expr_type(parent.value, types) + if isinstance(parent, ast.For) and parent.target is node: + if _is_range_call(parent.iter): + return "int" + return "str" if _expr_type(parent.iter, types) == "str" else None + return None + + def _param_types(self, name: str, types: dict) -> set: + kinds = set() + for load in self.loads: + if load.id != name: + continue + parent = self.parents[load] + if isinstance(parent, ast.Attribute) and isinstance(self.parents.get(parent), ast.Call): + if parent.attr in _STR_METHODS: + kinds.add("str") + elif parent.attr in ("append", "extend", "sort", "pop"): + kinds.add("list") + elif parent.attr in ("get", "items", "keys", "values"): + kinds.add("dict") + elif _is_range_call(parent): + kinds.add("int") + elif isinstance(parent, (ast.Compare, ast.BinOp)): + others = [parent.left, *parent.comparators] if isinstance(parent, ast.Compare) else [ + parent.left, parent.right] + for other in others: + if other is not load: + kind = _expr_type(other, types) + if kind in ("int", "str") and not (isinstance(parent, ast.BinOp) and kind == "str" + and not isinstance(parent.op, ast.Add)): + kinds.add(kind) + return kinds if len(kinds) == 1 else {None} + + +def _expr_type(node: ast.AST, types: dict) -> str | None: + if isinstance(node, ast.Constant): + return {bool: "bool", int: "int", float: "float", str: "str"}.get(type(node.value)) + if isinstance(node, ast.JoinedStr): + return "str" + simple = {ast.List: "list", ast.ListComp: "list", ast.Dict: "dict", ast.DictComp: "dict", + ast.Set: "set", ast.SetComp: "set", ast.Compare: "bool"} + if type(node) in simple: + return simple[type(node)] + if isinstance(node, ast.Name): + return types.get(node.id) + if isinstance(node, ast.UnaryOp): + return "bool" if isinstance(node.op, ast.Not) else _expr_type(node.operand, types) + if isinstance(node, ast.BinOp): + left, right = _expr_type(node.left, types), _expr_type(node.right, types) + if isinstance(node.op, ast.Div) and {left, right} <= {"int", "float"}: + return "float" + if left == right and left in ("int", "float") and not isinstance(node.op, ast.MatMult): + return left + if left == right == "str" and isinstance(node.op, ast.Add): + return "str" + if isinstance(node.op, ast.Mult) and {left, right} == {"str", "int"}: + return "str" + if left == right == "list" and isinstance(node.op, ast.Add): + return "list" + return None + if isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Slice): + kind = _expr_type(node.value, types) + return kind if kind in ("str", "list") else None + if isinstance(node, ast.IfExp): + a, b = _expr_type(node.body, types), _expr_type(node.orelse, types) + return a if a == b else None + if isinstance(node, ast.Call): + if isinstance(node.func, ast.Name): + if node.func.id == "round" and len(node.args) == 1: + return "int" + return _CALL_RESULT.get(node.func.id) + if isinstance(node.func, ast.Attribute): + return _METHOD_RESULT.get(node.func.attr) + return None + + +class _Realistic: + """Adds the REALISTIC_OPERATORS sites to a _Finder.""" + + def __init__(self, finder: "_Finder") -> None: + self.f = finder + self.text = finder.text + self.module_names = {n.name for n in finder.tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef))} + self.module_names |= {(a.asname or a.name).split(".")[0] for n in finder.tree.body + if isinstance(n, (ast.Import, ast.ImportFrom)) for a in n.names} + self.functions = [_Function(n, finder.parents) for n in ast.walk(finder.tree) + if isinstance(n, ast.FunctionDef)] + self.owner: dict[ast.AST, _Function] = {} # innermost enclosing function of every node + for function in self.functions: # ast.walk order: an inner function overwrites its outer one + for node in ast.walk(function.func): + self.owner[node] = function + + def visit(self) -> None: + for node in ast.walk(self.f.tree): + if node in self.f.skipped: + continue + handler = getattr(self, "_" + type(node).__name__, None) + if handler is not None: + handler(node) + for function in self.functions: + self._var_swap(function) + self._const_sibling(function) + + # -- helpers + def _whole_lines(self, node: ast.AST) -> bool: + line, col, end_line, end_col = self.text.node_span(node) + tail = self.text.line(end_line)[end_col:].strip() + return not self.text.line(line)[:col].strip() and (not tail or tail.startswith("#")) + + def _keyword_at(self, node: ast.AST, word: str) -> bool: + line, col, _, _ = self.text.node_span(node) + return self.text.line(line)[col:col + len(word) + 1] in (word + " ", word + "(") + + def _clause_keyword_after(self, node: ast.AST, word: str): + """First NAME token ``word`` after the end of ``node``: the next if/elif/else clause.""" + end = (node.end_lineno, self.text.node_span(node)[3]) + return next((t for t in self.f.tokens if t.type == tokenize.NAME and t.string == word and t.start >= end), + None) + + def _is_elif(self, node: ast.If) -> bool: + parent = self.f.parents.get(node) + return isinstance(parent, ast.If) and parent.orelse == [node] and self._keyword_at(node, "elif") + + # -- missing logic + def _If(self, node: ast.If) -> None: + self._extra_condition(node.test) + if self._is_elif(node): + self._drop_elif(node) + elif not node.orelse and isinstance(node.body[-1], _EXITS) and self._whole_lines(node): + self.f._site("guard_delete", (node.lineno, 0, node.end_lineno + 1, 0), "") + elif len(node.orelse) == 1 and self._is_elif(node.orelse[0]): + # Drop the leading arm: "if A: x / elif B: y" becomes "if B: y". + nxt = node.orelse[0] + line, col, _, _ = self.text.node_span(node) + if self.text.line(line)[col:col + 3] == "if ": + self.f._site("arm_drop", (line, col, nxt.lineno, self.text.node_span(nxt)[1] + 4), "if") + + def _drop_elif(self, node: ast.If) -> None: + if not self._whole_lines(node.body[-1]) or self.text.line(node.lineno)[:node.col_offset].strip(): + return + if not node.orelse: + end = node.end_lineno + 1 + elif len(node.orelse) == 1 and self._is_elif(node.orelse[0]): + end = node.orelse[0].lineno + else: + token = self._clause_keyword_after(node.body[-1], "else") + if token is None: + return + end = token.start[0] + self.f._site("arm_drop", (node.lineno, 0, end, 0), "") + + def _Compare(self, node: ast.Compare) -> None: + for op, comparator in zip(node.ops, node.comparators): + if not isinstance(op, (ast.In, ast.NotIn)) or not isinstance(comparator, (ast.Tuple, ast.List, ast.Set)): + continue + elts = comparator.elts + span = self.text.node_span(comparator) + literal = self.text.segment(span) + if len(elts) < 2 or span[0] != span[2] or any(isinstance(e, ast.Starred) for e in elts): + continue + if literal[0] + literal[-1] not in ("()", "[]", "{}"): + continue + parts = [self.text.segment(self.text.node_span(e)) for e in elts] + for i in range(len(parts)): + rest = parts[:i] + parts[i + 1:] + comma = "," if isinstance(comparator, ast.Tuple) and len(rest) == 1 else "" + self.f._site("member_drop", span, literal[0] + ", ".join(rest) + comma + literal[-1]) + + def _BoolOp(self, node: ast.BoolOp) -> None: + word = " and " if isinstance(node.op, ast.And) else " or " + span = self.text.node_span(node) + texts = [_paren(self.text.segment(self.text.node_span(v)), v) for v in node.values] + for i in range(len(texts)): + self.f._site("condition_drop", span, word.join(texts[:i] + texts[i + 1:])) + + # -- excess logic + def _extra_condition(self, test: ast.AST) -> None: + if isinstance(test, ast.Name): + return + span = self.text.node_span(test) + body = self.text.segment(span) + if isinstance(test, (ast.IfExp, ast.NamedExpr, ast.Lambda)) or ( + isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or)): + body = f"({body})" + function = self.owner.get(test) + bound = function.bound_names() if function is not None else set() + seen = [] + for node in ast.walk(test): + if not isinstance(node, ast.Name) or not isinstance(node.ctx, ast.Load) or node.id in seen: + continue + parent = self.f.parents.get(node) + if (isinstance(parent, ast.Call) and parent.func is node) or node.id not in bound: + continue # only the function's own parameters and locals: never a comprehension variable + seen.append(node.id) + self.f._site("extra_condition", span, f"{node.id} and {body}") + + def _While(self, node: ast.While) -> None: + self._extra_condition(node.test) + + def _comprehension(self, node: ast.comprehension) -> None: + for test in node.ifs: + self._extra_condition(test) + + # -- function misuse + def _Call(self, node: ast.Call) -> None: + func = node.func + parent = self.f.parents.get(node) + iterated = (isinstance(parent, (ast.For, ast.comprehension)) and parent.iter is node) + if isinstance(func, ast.Name): + siblings = _NAME_SIBLINGS.get(func.id, ()) + if func.id == "round" and (len(node.args) != 1 or node.keywords): + siblings = () + if iterated: + siblings += _ITER_SIBLINGS.get(func.id, ()) + for other in siblings: + self.f._site("call_swap", self.text.node_span(func), other) + elif isinstance(func, ast.Attribute): + siblings = self._method_siblings(node, func) + if func.attr in ("split", "rsplit") and len(node.args) < 2 and not any( + k.arg == "maxsplit" for k in node.keywords): + return # without maxsplit, split and rsplit agree + line, col, end_line, end_col = self.text.node_span(func) + if self.text.line(end_line)[end_col - len(func.attr):end_col] != func.attr: + return + for other in siblings: + self.f._site("call_swap", (end_line, end_col - len(func.attr), end_line, end_col), other) + + def _method_siblings(self, node: ast.Call, func: ast.Attribute) -> tuple[str, ...]: + receiver = func.value + if isinstance(receiver, ast.Name) and receiver.id in self.module_names: + return _MODULE_SIBLINGS.get((receiver.id, func.attr), ()) # re.split has no re.rsplit + function = self.owner.get(node) + kind = _expr_type(receiver, function.types if function is not None else {}) + siblings = _METHOD_SIBLINGS.get(kind, {}).get(func.attr, ()) + if func.attr == "append" and not (node.args and _iterable_value(node.args[0], function)): + return () # extend(x) on a non-iterable only raises + return siblings + + # -- variable misuse + def _var_swap(self, function: _Function) -> None: + types = function.types + bound = function.bound_names() + for use in function.loads: + kind = types.get(use.id) + if kind is None or use in self.f.skipped or use.id not in bound: + continue + parent = self.f.parents.get(use) + if isinstance(parent, ast.Call) and parent.func is use: + continue + span = self.text.node_span(use) + if self.text.segment(span) != use.id: + continue + for other in sorted(n for n, t in types.items() if t == kind and n != use.id and n in bound): + if other in function.params or any(function.dominates(b, use) for b in function.stores.get(other, [])): + self.f._site("var_swap", span, other) + + # -- value misuse + def _const_sibling(self, function: _Function) -> None: + docstring = function.func.body[0] if ast.get_docstring(function.func) is not None else None + constants: dict[str, list] = {"int": [], "str": []} + for node in ast.walk(function.func): + if not isinstance(node, ast.Constant) or node in self.f.skipped: + continue + if docstring is not None and node is docstring.value: + continue + parent = self.f.parents.get(node) + if _is_range_call(parent) and len(parent.args) == 3 and parent.args[2] is node: + continue + kind = "int" if type(node.value) is int else "str" if type(node.value) is str else None + if kind is not None: + constants[kind].append(node) + for nodes in constants.values(): + first: dict = {} + for node in nodes: + first.setdefault(node.value, self.text.segment(self.text.node_span(node))) + for node in nodes: + for value, text in first.items(): + if value != node.value: + self.f._site("const_sibling", self.text.node_span(node), text) + + +def enumerate_sites(source: str, operators: Sequence[str] = OPERATORS) -> list[Site]: + """Mutation sites in ``source`` for ``operators``, ordered by position, operator, replacement. + + Each returned site, applied alone, yields source that parses and whose AST differs from the + original's. Sites inside f-strings, decorators and annotations are skipped. Classic operators + replace one token; realistic operators may replace an expression or delete whole lines. + """ + unknown = set(operators) - set(OPERATORS) + if unknown: + raise ValueError(f"unknown operators: {sorted(unknown)}") + finder = _Finder(source) + finder.visit() + if set(operators) & set(REALISTIC_OPERATORS): + _Realistic(finder).visit() + wanted = set(operators) + baseline = ast.dump(finder.tree) + unique: dict[tuple, Site] = {} + for site in finder.sites: + if site.operator in wanted: + unique.setdefault((site.lineno, site.col, site.end_lineno, site.end_col, site.replacement), site) + valid = [] + for site in unique.values(): + try: + mutated = ast.parse(apply(source, [site])) + except SyntaxError: + continue + if ast.dump(mutated) != baseline: + valid.append(site) + valid.sort(key=lambda s: (s.lineno, s.col, s.end_lineno, s.end_col, s.operator, s.replacement)) + return valid + + +# --------------------------------------------------------------------------- application + +def _splice(source: str, edits: list[tuple[int, int, str]]) -> str: + """Replace non-overlapping [start, end) ranges; edits must be sorted by start.""" + out, pos = [], 0 + for start, end, text in edits: + out.append(source[pos:start]) + out.append(text) + pos = end + out.append(source[pos:]) + return "".join(out) + + +def apply(source: str, sites: Sequence[Site]) -> str: + """Apply non-overlapping sites to ``source``. Raises ValueError on overlap or a stale site.""" + text = _Text(source) + edits = [] + for site in sites: + start = text.offset(site.lineno, site.col) + end = text.offset(site.end_lineno, site.end_col) + if source[start:end] != site.original: + raise ValueError(f"site does not match source: {site.description}") + edits.append((start, end, site.replacement, site)) + edits.sort(key=lambda e: (e[0], e[1])) + for (s1, e1, _, a), (s2, e2, _, b) in zip(edits, edits[1:]): + if s2 < e1 or (s1 == s2 and e1 == e2): + raise ValueError(f"overlapping sites: {a.description} / {b.description}") + return _splice(source, [(s, e, r) for s, e, r, _ in edits]) + + +def unified_diff(a: str, b: str, path: str) -> str: + """Unified diff of two sources (2 lines of context), labelled a/ and b/.""" + def lines(s: str) -> list[str]: + out = s.splitlines(keepends=True) + if out and not out[-1].endswith(("\n", "\r")): + out[-1] += "\n" + return out + return "".join(difflib.unified_diff(lines(a), lines(b), f"a/{path}", f"b/{path}", n=2)) + + +def block_site(original: str, variant: str, operator: str, label: str) -> Site | None: + """One whole-line site that turns ``original`` into ``variant``, or None if they are equal. + + The span runs from the first to the last line that differs, so a multi-hunk change becomes a + single replacement that ``apply`` can combine with other, non-overlapping sites. + """ + a = original.splitlines(keepends=True) + b = variant.splitlines(keepends=True) + changed = [op for op in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes() if op[0] != "equal"] + if not changed: + return None + i1, i2, j1, j2 = changed[0][1], changed[-1][2], changed[0][3], changed[-1][4] + return Site(operator, i1 + 1, 0, i2 + 1, 0, "".join(a[i1:i2]), "".join(b[j1:j2]), + f"line {i1 + 1}: {label} ({operator})") + + +# --------------------------------------------------------------------------- procedural renaming + +_WORDS = ( + "acc", "buf", "cur", "idx", "item", "val", "tmp", "res", "count", "total", "part", "piece", "node", + "elem", "pos", "step", "seen", "out", "left", "right", "head", "tail", "chunk", "entry", "token", + "mark", "span", "width", "depth", "level", "limit", "prev", "best", "cell", "slot", "probe", + "bucket", "window", "cursor", "pivot", "group", "batch", "frame", "lane", "row", "col", "unit", + "score", "weight", "label", "record", "sample", "point", "edge", "field", "block", "stack", +) +_RESERVED = frozenset(dir(builtins)) | frozenset(keyword.kwlist) | frozenset(keyword.softkwlist) +_FUNC_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda) + + +def _walk_scoped(node: ast.AST, in_function: bool = False) -> Iterator[tuple[ast.AST, bool]]: + yield node, in_function + inner = in_function or isinstance(node, _FUNC_SCOPES) + for child in ast.iter_child_nodes(node): + yield from _walk_scoped(child, inner) + + +def _string_bound_names(tree: ast.AST) -> set[str]: + """Identifiers bound through string fields (defs, params, aliases, except/match captures).""" + names: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(node.name) + elif isinstance(node, ast.arg): + names.add(node.arg) + elif isinstance(node, ast.alias): + names.add((node.asname or node.name).split(".")[0]) + elif isinstance(node, ast.ExceptHandler) and node.name: + names.add(node.name) + elif isinstance(node, (ast.Global, ast.Nonlocal)): + names.update(node.names) + elif isinstance(node, (ast.MatchAs, ast.MatchStar)) and node.name: + names.add(node.name) + elif isinstance(node, ast.MatchMapping) and node.rest: + names.add(node.rest) + elif isinstance(node, ast.keyword) and node.arg: + names.add(node.arg) + return names + + +def local_renaming(source: str, rng) -> dict[str, str]: + """Choose new names for the function-local variables of ``source``, deterministically per ``rng``. + + Parameters, function names, attributes, keyword arguments, imports, builtins and any name bound + at module scope are left alone. Only names bound exclusively inside function bodies (assignment, + loop/with/comprehension targets, walrus) are renamed. New names never collide with any name + already in ``source``. Returns {old: new}; empty when nothing can be renamed. + """ + text = _Text(source) + tree = ast.parse(source) + excluded = _string_bound_names(tree) | _RESERVED + in_fstring = {n.id for f in ast.walk(tree) if isinstance(f, ast.JoinedStr) + for n in ast.walk(f) if isinstance(n, ast.Name)} + excluded |= in_fstring + local_bound: set[str] = set() + module_bound: set[str] = set() + occurrences: dict[str, list[ast.Name]] = {} + for node, in_function in _walk_scoped(tree): + if not isinstance(node, ast.Name): + continue + occurrences.setdefault(node.id, []).append(node) + if isinstance(node.ctx, (ast.Store, ast.Del)): + (local_bound if in_function else module_bound).add(node.id) + candidates = [] + for name in sorted(local_bound - module_bound - excluded, + key=lambda n: min((o.lineno, o.col_offset) for o in occurrences[n])): + if name.startswith("__"): + continue + if all(text.segment(text.node_span(o)) == name for o in occurrences[name]): + candidates.append(name) + if not candidates: + return {} + taken = {t.string for t in _tokens(source) if t.type == tokenize.NAME} | _RESERVED + pool = list(_WORDS) + rng.shuffle(pool) + mapping: dict[str, str] = {} + suffix = 2 + for name in candidates: + while not pool: + pool = [f"{w}{suffix}" for w in _WORDS] + suffix += 1 + new = pool.pop(0) + while new in taken: + if not pool: + pool = [f"{w}{suffix}" for w in _WORDS] + suffix += 1 + new = pool.pop(0) + taken.add(new) + mapping[name] = new + return mapping + + +def rename_with(source: str, mapping: dict[str, str]) -> str: + """Rename every ``ast.Name`` whose id is in ``mapping``, preserving formatting. + + Raises ValueError if a new name already occurs in ``source`` or if the rename would change + the program's structure, so a mapping chosen for one source can be checked on a variant of it. + """ + if not mapping: + return source + text = _Text(source) + tree = ast.parse(source) + present = {t.string for t in _tokens(source) if t.type == tokenize.NAME} + if present & set(mapping.values()): + raise ValueError(f"renaming collides with existing names: {sorted(present & set(mapping.values()))}") + edits = [] + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id in mapping: + span = text.node_span(node) + if text.segment(span) != node.id: + raise ValueError(f"cannot rename {node.id!r} at line {node.lineno}") + edits.append((text.offset(span[0], span[1]), text.offset(span[2], span[3]), mapping[node.id])) + edits.sort() + renamed = _splice(source, edits) + check = ast.parse(renamed) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id in mapping: + node.id = mapping[node.id] + if ast.dump(check) != ast.dump(tree): + raise ValueError("renaming changed program structure") + return renamed + + +def rename_locals(source: str, rng) -> str: + """Rename function-local variables to other plausible names, deterministically per ``rng``. + + Every occurrence of a renamed name changes consistently, so the code is semantically + identical. See ``local_renaming`` for which names are eligible. + """ + return rename_with(source, local_renaming(source, rng)) diff --git a/components/qemedia/upstream/qe_arena/runtime_pins.json b/components/qemedia/upstream/qe_arena/runtime_pins.json new file mode 100644 index 0000000000000000000000000000000000000000..e2857ea6970b99652bfd111bdd76ad7e8f5675e7 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/runtime_pins.json @@ -0,0 +1,4 @@ +{ + "lib/python314.zip": "959c807f29a90f9de74ad3e5eafc1ccb667202d031e9ac8050c2683ed785f2c2", + "python.wasm": "d24bd98d3071af6b17d51d53a08700b9acef59172a0afcb6adb733645c2a1715" +} diff --git a/components/qemedia/upstream/qe_arena/sandbox.py b/components/qemedia/upstream/qe_arena/sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..11f2bb9a1a34c20b7b7cae3471f61871ca6c156b --- /dev/null +++ b/components/qemedia/upstream/qe_arena/sandbox.py @@ -0,0 +1,729 @@ +"""Sandboxed execution of corpus and candidate code; the oracle stays in this process. + +Layers, outermost first: + +1. ``static_gate`` rejects source before it runs: imports outside the allowlist, dunder and + introspection attributes, banned names (including ``MemoryError``, so a guest MemoryError can + only come from the memory cap), classes, ``global``/``nonlocal``, oversize or overly deep code. +2. ``run_calls`` hands the batch to a long-lived worker process (``qe_arena/wasi_worker.py``) over a + pipe, so the server never loads wasmtime and a worker fault cannot take down /health. +3. The worker runs CPython 3.14 compiled to WASI under wasmtime, a fresh Store and Instance per + batch: wasmtime fuel meters every call, linear memory is capped at ``mem_mb``, the only preopen is + a read-only stdlib zip, clocks and randomness are shadowed. Inside, the guest harness executes + the code with restricted builtins and proxy modules that expose an audited list of names. +4. Results come back as rows the parent validates; ``compare`` runs here. Expected values never + enter the worker or the guest. + +Outcomes are deterministic: the same source and calls give the same kind, value and fuel on any +host and under any load (pinned by the corpus fingerprint test). ``fuel`` (budget exhausted), +``resource`` (memory cap, MemoryError or RecursionError however the code handled it, wasm stack) and +``skipped`` (an earlier call trapped and ended the instance) are limits of the sandbox, never +behaviour. ``infra`` (worker died, hung or failed its identity check) is transient and never graded: +tasks._outputs turns a persistent one into InfraError. ``timeout`` is kept as an alias of ``infra`` +for callers written against the subprocess sandbox. docs/DESIGN.md "Verifier integrity" has the +full contract. + +The guest is CPython 3.14 on wasm32 while the server is 3.12 on 64-bit: pointers are 4 bytes and +``hash()`` is 32-bit. That is harmless because reference and candidate both run in the guest; never +compare a native reference with a guest result. +""" + +from __future__ import annotations + +import ast +import atexit +import collections +import contextlib +import contextvars +import json +import re +import string +import math +import os +import secrets +import selectors +import subprocess +import sys +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal + +ALLOWED_MODULES = ("math", "re", "itertools", "functools", "collections", "string", "bisect", "heapq", + "statistics", "decimal", "fractions", "typing", "operator") + +# Names each allowlisted module exposes to candidate code, frozen for the CPython 3.14 guest (the +# server's own 3.12 modules are irrelevant). Absent on purpose: anything that reads or writes an +# attribute or evaluates code from a runtime string (functools.update_wrapper/wraps, singledispatch, +# string.Formatter, operator.attrgetter/methodcaller, typing.get_type_hints/get_args/ForwardRef/ +# evaluate_forward_ref and every TypeVar-like object that can evaluate a lazy bound) and anything +# that hands back a module (typing.sys, typing.functools, ...). tests/test_sandbox.py walks every +# public attribute reachable from these names inside the guest and asserts no module, frame, code +# object or loader is among them. +SAFE_EXPORTS: dict[str, tuple[str, ...]] = { + "math": ("acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", "cbrt", "ceil", "comb", "copysign", + "cos", "cosh", "degrees", "dist", "e", "erf", "erfc", "exp", "exp2", "expm1", "fabs", "factorial", + "floor", "fma", "fmod", "frexp", "fsum", "gamma", "gcd", "hypot", "inf", "isclose", "isfinite", + "isinf", "isnan", "isqrt", "lcm", "ldexp", "lgamma", "log", "log10", "log1p", "log2", "modf", + "nan", "nextafter", "perm", "pi", "pow", "prod", "radians", "remainder", "sin", "sinh", "sqrt", + "sumprod", "tan", "tanh", "tau", "trunc", "ulp"), + "itertools": ("accumulate", "batched", "chain", "combinations", "combinations_with_replacement", + "compress", "count", "cycle", "dropwhile", "filterfalse", "groupby", "islice", "pairwise", + "permutations", "product", "repeat", "starmap", "takewhile", "tee", "zip_longest"), + "re": ("A", "ASCII", "DOTALL", "I", "IGNORECASE", "M", "MULTILINE", "NOFLAG", "S", "VERBOSE", "X", + "Match", "Pattern", "compile", "error", "escape", "findall", "finditer", "fullmatch", "match", + "search", "split", "sub", "subn"), + "functools": ("cache", "cmp_to_key", "lru_cache", "partial", "reduce"), + "collections": ("ChainMap", "Counter", "OrderedDict", "defaultdict", "deque", "namedtuple"), + "string": ("Template", "ascii_letters", "ascii_lowercase", "ascii_uppercase", "capwords", "digits", + "hexdigits", "octdigits", "printable", "punctuation", "whitespace"), + "bisect": ("bisect", "bisect_left", "bisect_right", "insort", "insort_left", "insort_right"), + "heapq": ("heapify", "heappop", "heappush", "heappushpop", "heapreplace", "merge", "nlargest", + "nsmallest"), + "statistics": ("StatisticsError", "correlation", "covariance", "fmean", "geometric_mean", + "harmonic_mean", "linear_regression", "mean", "median", "median_grouped", "median_high", + "median_low", "mode", "multimode", "pstdev", "pvariance", "quantiles", "stdev", + "variance"), + "decimal": ("BasicContext", "Clamped", "Context", "Decimal", "DecimalException", "DefaultContext", + "DivisionByZero", "ExtendedContext", "FloatOperation", "Inexact", "InvalidOperation", + "Overflow", "ROUND_05UP", "ROUND_CEILING", "ROUND_DOWN", "ROUND_FLOOR", "ROUND_HALF_DOWN", + "ROUND_HALF_EVEN", "ROUND_HALF_UP", "ROUND_UP", "Rounded", "Subnormal", "Underflow", + "getcontext", "localcontext", "setcontext"), + "fractions": ("Fraction",), + "typing": ("TYPE_CHECKING", "Any", "Callable", "Collection", "Container", "Dict", "Final", "FrozenSet", + "Hashable", "Iterable", "Iterator", "List", "Literal", "Mapping", "MutableMapping", + "MutableSequence", "MutableSet", "Optional", "Sequence", "Set", "Sized", "Tuple", "Union", + "cast"), + "operator": ("abs", "add", "and_", "concat", "contains", "countOf", "delitem", "eq", "floordiv", "ge", + "getitem", "gt", "iadd", "iand", "iconcat", "ifloordiv", "ilshift", "imatmul", "imod", "imul", + "index", "indexOf", "inv", "invert", "ior", "ipow", "irshift", "is_", "is_none", "is_not", + "is_not_none", "isub", "itemgetter", "itruediv", "ixor", "le", "length_hint", "lshift", "lt", + "matmul", "mod", "mul", "ne", "neg", "not_", "or_", "pos", "pow", "rshift", "setitem", "sub", + "truediv", "truth", "xor"), +} + +SAFE_BUILTINS = ( + "abs", "all", "any", "bin", "bool", "chr", "dict", "divmod", "enumerate", "filter", "float", "format", + "frozenset", "hash", "hex", "int", "isinstance", "issubclass", "iter", "len", "list", "map", "max", + "min", "next", "object", "oct", "ord", "pow", "range", "repr", "reversed", "round", "set", "slice", + "sorted", "str", "sum", "tuple", "zip", "callable", + "ArithmeticError", "AssertionError", "AttributeError", "Exception", "IndexError", "KeyError", + "LookupError", "NotImplementedError", "OverflowError", "RecursionError", + "RuntimeError", "StopIteration", "TypeError", "ValueError", "ZeroDivisionError", + "True", "False", "None", "NotImplemented", +) + +BANNED_NAMES = frozenset({ + "open", "exec", "eval", "compile", "__import__", "globals", "locals", "vars", "getattr", "setattr", + "delattr", "breakpoint", "input", "help", "memoryview", "exit", "quit", "MemoryError", +}) +# Introspection attributes that reach frames, code objects or tracebacks without a dunder, and the +# string-driven attribute or evaluation helpers that are kept out of SAFE_EXPORTS (defence in depth). +DENIED_ATTR_PREFIXES = ("_", "gi_", "cr_", "ag_", "f_", "tb_", "co_") +DENIED_ATTRS = frozenset({"mro", "format_map", "get_field", "vformat", "convert_field", "format_field", + "get_value", "with_traceback", "attrgetter", "methodcaller", "get_type_hints", + "get_args", "get_origin", "evaluate", "evaluate_forward_ref", "evaluate_bound", + "evaluate_constraints", "evaluate_default"}) +# str.format resolves "{0.attr}" and "{0[key]}" at runtime, outside the AST checks, and reaches frames +# and module globals through dunders ("{0.__traceback__.tb_frame.f_back.f_locals}"). So .format needs a +# literal receiver whose fields are plain positions or names and which mentions no traversal name, and +# format() needs a literal spec that mentions none either. +TRAVERSAL_TOKENS = ("__", "tb_frame", "tb_next", "f_back", "f_locals", "f_globals", "f_builtins", "f_code", + "gi_frame", "gi_code", "cr_frame", "cr_code", "ag_frame", "ag_code") +# "__" anywhere; the frame attribute names as whole identifier words, with the same boundary on both sides +# (letters, digits and "_" continue a word), so "lines_of_code" or "prefix_f_back" is fine and ".f_back" or +# "[f_back]" is not. +_WORD = "A-Za-z0-9_" +_TRAVERSAL_RE = re.compile(r"__|(? bool: + return bool(name) and name.startswith("__") + + +def _ast_depth(tree: ast.AST) -> int: + deepest, stack = 0, [(tree, 1)] + while stack: + node, depth = stack.pop() + deepest = max(deepest, depth) + stack.extend((child, depth + 1) for child in ast.iter_child_nodes(node)) + return deepest + + +def _format_fields(template: str) -> list[str]: + """Field names in a format template, nested specs included; raises ValueError if malformed.""" + names = [] + for _, field, spec, _ in string.Formatter().parse(template): + if field is not None: + names.append(field) + if spec: + names.extend(_format_fields(spec)) + return names + + +# re.DEBUG (128) makes the re module print its parse tree. The guest discards Python-level stdout, so +# a computed flag is harmless; a literal one is refused so honest code never depends on that. +RE_FLAGS_POSITION = {"compile": 1, "search": 2, "match": 2, "fullmatch": 2, "findall": 2, "finditer": 2, + "split": 3, "sub": 4, "subn": 4} +RE_DEBUG = 128 + + +def _check_re_debug(node: ast.AST) -> list[str]: + if isinstance(node, ast.Attribute) and node.attr == "DEBUG": + return ["re.DEBUG is not allowed"] + if not isinstance(node, ast.Call): + return [] + name = node.func.attr if isinstance(node.func, ast.Attribute) else getattr(node.func, "id", None) + if name not in RE_FLAGS_POSITION: + return [] + flags = [kw.value for kw in node.keywords if kw.arg == "flags"] + if len(node.args) > RE_FLAGS_POSITION[name]: + flags.append(node.args[RE_FLAGS_POSITION[name]]) + for expr in flags: + for sub in ast.walk(expr): + if isinstance(sub, ast.Constant) and type(sub.value) is int and sub.value & RE_DEBUG: + return ["re.DEBUG is not allowed"] + return [] + + +def _check_format_literal(text: str) -> list[str]: + found = _TRAVERSAL_RE.search(text) + return [f"format string mentions {found.group(0)!r}"] if found else [] + + +def _check_formatting(tree: ast.AST) -> list[str]: + """Only a string that reaches a format path is checked for traversal names: the literal receiver of + .format and the literal spec of format(). Any other literal (a docstring, x.split('__'), a dict key) + cannot drive an attribute lookup: getattr, vars, globals, format_map, string.Formatter and + operator.attrgetter are unavailable, and a non-literal .format receiver is refused below.""" + problems = [] + allowed_format_names = set() + for node in ast.walk(tree): + if isinstance(node, ast.Attribute) and node.attr == "format": + receiver = node.value + if not (isinstance(receiver, ast.Constant) and isinstance(receiver.value, str)): + problems.append(".format needs a string literal receiver") + continue + problems.extend(_check_format_literal(receiver.value)) + try: + fields = _format_fields(receiver.value) + except ValueError: + problems.append("malformed format string") + continue + if any("." in f or "[" in f for f in fields): + problems.append("format fields may not use attribute or index lookups") + elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "format": + spec_ok = len(node.args) == 1 or ( + len(node.args) == 2 and isinstance(node.args[1], ast.Constant) and isinstance(node.args[1].value, str)) + if spec_ok and not node.keywords: + allowed_format_names.add(node.func) + if len(node.args) == 2: + problems.extend(_check_format_literal(node.args[1].value)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id == "format" and node not in allowed_format_names: + problems.append("format() needs a string literal spec and may not be passed around") + return problems + + +def _check_node(node: ast.AST) -> list[str]: + problems = [] + for node_type, message in REJECTED_NODES.items(): + if isinstance(node, node_type): + problems.append(message) + if isinstance(node, ast.Name): + if _is_dunder(node.id): + problems.append(f"dunder name {node.id!r}") + elif node.id in BANNED_NAMES: + problems.append(f"banned name {node.id!r}") + elif isinstance(node, ast.Attribute): + if node.attr.startswith(DENIED_ATTR_PREFIXES) or node.attr in DENIED_ATTRS: + problems.append(f"attribute {node.attr!r} is not allowed") + elif isinstance(node, ast.Import): + for alias in node.names: + if alias.name not in ALLOWED_MODULES: + problems.append(f"import of {alias.name!r} is not allowed") + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + if node.level or module not in ALLOWED_MODULES: + problems.append(f"import from {'.' * node.level + module!r} is not allowed") + else: + for alias in node.names: + if alias.name not in SAFE_EXPORTS[module]: + problems.append(f"{module}.{alias.name} is not available") + elif isinstance(node, ast.FunctionDef) and getattr(node, "type_params", None): + problems.append("type parameters are not allowed") + for field in ("name", "arg", "asname"): + value = getattr(node, field, None) + if isinstance(value, str) and _is_dunder(value): + problems.append(f"dunder identifier {value!r}") + if isinstance(node, ast.alias) and _is_dunder(node.name): + problems.append(f"dunder identifier {node.name!r}") + return problems + + +def static_gate(source: str) -> list[str]: + """Return the reasons ``source`` may not run; an empty list means it passed.""" + if not isinstance(source, str): + return ["source must be a string"] + size = len(source.encode("utf-8", "surrogatepass")) + if size > MAX_SOURCE_BYTES: + return [f"source is {size} bytes; the limit is {MAX_SOURCE_BYTES}"] + try: + tree = ast.parse(source) + except (SyntaxError, ValueError, RecursionError, MemoryError) as exc: + return [f"does not parse: {type(exc).__name__}: {exc}"[:200]] + if _ast_depth(tree) > MAX_AST_DEPTH: + return [f"syntax tree deeper than {MAX_AST_DEPTH}"] + problems: list[str] = [] + found = [p for node in ast.walk(tree) for p in _check_node(node) + _check_re_debug(node)] + for problem in found + _check_formatting(tree): + if problem not in problems: + problems.append(problem) + return problems + + +# --------------------------------------------------------------------------- worker pool + +PACKAGE_PARENT = Path(__file__).resolve().parents[1] + + +def runtime_root() -> Path: + """Where python.wasm and lib/python314.zip live (built by scripts/build_wasi_runtime.py).""" + configured = os.environ.get("QE_ARENA_WASI_ROOT") + if configured: + return Path(configured) + local = PACKAGE_PARENT / "runtime" + return local if (local / "python.wasm").exists() else Path("/opt/qe-arena/wasi") + + +class _Worker: + def __init__(self, deadline: float | None = None) -> None: + """Start a worker and wait for its ready line, no longer than WORKER_STARTUP_S and never past + ``deadline`` (the caller's dispatch deadline).""" + env = dict(os.environ, QE_ARENA_WASI_ROOT=str(runtime_root()), PYTHONDONTWRITEBYTECODE="1", + PYTHONPATH=os.pathsep.join(filter(None, [str(PACKAGE_PARENT), os.environ.get("PYTHONPATH")]))) + self.proc = subprocess.Popen( + [sys.executable, "-P", "-B", "-m", "qe_arena.wasi_worker"], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=None, env=env, close_fds=True) + os.set_blocking(self.proc.stdin.fileno(), False) # writes honour the deadline (see send) + self.buf = bytearray() + limit = time.monotonic() + WORKER_STARTUP_S + ready = self.read(limit if deadline is None else min(limit, deadline)) + if not (isinstance(ready, dict) and ready.get("ready")): + self.close() + raise RuntimeError(f"sandbox worker did not start: {ready!r}") + + def read(self, deadline: float) -> Any: + """One JSON line from the worker, or a status string on timeout, EOF or overflow.""" + fd = self.proc.stdout.fileno() + with selectors.DefaultSelector() as sel: + sel.register(fd, selectors.EVENT_READ) + while True: + nl = self.buf.find(b"\n") + if nl >= 0: + line = bytes(self.buf[:nl]) + del self.buf[:nl + 1] + try: + return json.loads(line.decode("utf-8", "surrogatepass")) + except ValueError: + return "bad response" + remaining = deadline - time.monotonic() + if remaining <= 0: + return "timeout" + if not sel.select(remaining): + continue + chunk = os.read(fd, 1 << 16) + if not chunk: + return "exited" + self.buf += chunk + if len(self.buf) > MAX_RESPONSE_BYTES: + return "overflow" + + def send(self, data: bytes, deadline: float) -> str: + """Write all of ``data`` before the deadline. A stopped or wedged worker stops reading, and a + payload larger than the pipe buffer would otherwise block this thread forever.""" + fd = self.proc.stdin.fileno() + view = memoryview(data) + with selectors.DefaultSelector() as sel: + sel.register(fd, selectors.EVENT_WRITE) + while view: + remaining = deadline - time.monotonic() + if remaining <= 0: + return "timeout" + if not sel.select(remaining): + continue + try: + view = view[os.write(fd, view):] + except BlockingIOError: + continue + except OSError: + return "exited" + return "sent" + + def request(self, payload: dict, deadline: float) -> Any: + status = self.send(json.dumps(payload, allow_nan=True).encode("utf-8", "surrogatepass") + b"\n", deadline) + if status != "sent": + return status + response = self.read(deadline) + if isinstance(response, dict) and response.get("id") != payload.get("id"): + return "mismatched response" + return response + + def close(self) -> None: + if self.proc.poll() is None: + self.proc.kill() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: # pragma: no cover - SIGKILL does not fail on POSIX + pass + for pipe in (self.proc.stdin, self.proc.stdout): + try: + pipe.close() + except OSError: + pass + + +MAX_WORKERS = 4 +CGROUP_ROOT = Path("/sys/fs/cgroup") + + +def detect_workers(cgroup_root: Path = CGROUP_ROOT) -> int: + """One worker per CPU the container may actually use, between 1 and MAX_WORKERS. + + ``docker run --cpus=2`` sets a CFS quota but leaves every host CPU visible, so os.cpu_count() + and the affinity mask say 16 on ruos. Read the quota first: cgroup v2 ``cpu.max`` ("max 100000" + or "200000 100000"), then cgroup v1 ``cpu.cfs_quota_us``/``cpu.cfs_period_us``, then the + affinity mask, then os.cpu_count(). A fractional quota rounds up. + """ + cpus = None + try: + fields = (cgroup_root / "cpu.max").read_text().split() + if fields and fields[0] != "max": + cpus = int(fields[0]) / int(fields[1] if len(fields) > 1 else 100_000) + except (OSError, ValueError, ZeroDivisionError): + pass + if cpus is None: + try: + quota = int((cgroup_root / "cpu" / "cpu.cfs_quota_us").read_text()) + period = int((cgroup_root / "cpu" / "cpu.cfs_period_us").read_text()) + if quota > 0 and period > 0: + cpus = quota / period + except (OSError, ValueError): + pass + if cpus is None: + try: + cpus = len(os.sched_getaffinity(0)) + except (AttributeError, OSError): + cpus = os.cpu_count() or 1 + return min(MAX_WORKERS, max(1, math.ceil(cpus))) + + +_DETECTED: list[int] = [] + + +def _pool_size() -> int: + """QE_ARENA_WASI_WORKERS overrides (at least 1); otherwise ``detect_workers()``, read once.""" + override = os.environ.get("QE_ARENA_WASI_WORKERS") + if override: + try: + return max(1, int(override)) + except ValueError: + pass + if not _DETECTED: + _DETECTED.append(detect_workers()) + return _DETECTED[0] + + +_POOL = threading.Condition() +_IDLE: list[_Worker] = [] +_LIVE = [0] +_WAITING: collections.deque = collections.deque() # (ticket, session, capped), oldest first +_INFLIGHT: collections.Counter = collections.Counter() # workers held per session + +# Which episode a batch belongs to. QEEnvironment sets it around reset and step, so one session cannot +# hold every worker: a session that keeps grading looping code waits its turn like anyone else. +_SESSION: contextvars.ContextVar = contextvars.ContextVar("qe_arena_sandbox_session", default=None) + + +@contextlib.contextmanager +def session(key: Any): + """Attribute the sandbox batches run inside this block to ``key`` (fairness only).""" + token = _SESSION.set(key) + try: + yield + finally: + _SESSION.reset(token) + + +def _session_cap() -> int: + """Workers one session may hold at once: all but one, so another session can always get one.""" + return max(1, _pool_size() - 1) + + +class _PoolTimeout(Exception): + pass + + +def _next_eligible() -> Any: + """The oldest waiting ticket whose session is under its cap (FIFO among those that may proceed).""" + for ticket, key, capped in _WAITING: + if not capped or _INFLIGHT[key] < _session_cap(): + return ticket + return None + + +def _acquire(deadline: float, *, capped: bool = True) -> _Worker: + """A worker for the current session, served first come first served among sessions under their cap. + Reuses an idle worker or starts one if the pool has room; waits only until the deadline.""" + key, ticket = _SESSION.get(), object() + with _POOL: + _WAITING.append((ticket, key, capped)) + try: + while _next_eligible() is not ticket or (not _IDLE and _LIVE[0] >= _pool_size()): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise _PoolTimeout("no sandbox worker became free before the deadline") + _POOL.wait(remaining) + finally: + _WAITING.remove(next(item for item in _WAITING if item[0] is ticket)) + _POOL.notify_all() + _INFLIGHT[key] += 1 + if _IDLE: + worker = _IDLE.pop() + worker.session, worker.held = key, True + return worker + _LIVE[0] += 1 + try: + worker = _Worker(deadline) + except BaseException: + with _POOL: + _LIVE[0] -= 1 + _INFLIGHT[key] -= 1 + _POOL.notify_all() + raise + worker.session, worker.held = key, True + return worker + + +def _release(worker: _Worker, healthy: bool) -> None: + """Return a worker to the pool (or retire it). A second release of the same acquisition is ignored: + no caller does that today, but it would list the worker twice or uncount it while it sits idle.""" + with _POOL: + if not getattr(worker, "held", True): + return + worker.held = False + if not healthy: + worker.close() + with _POOL: + key = getattr(worker, "session", None) + if _INFLIGHT[key] > 0: + _INFLIGHT[key] -= 1 + if healthy: + _IDLE.append(worker) + else: + _LIVE[0] -= 1 + _POOL.notify_all() + + +def _dispatch(payload: dict) -> Any: + """Send one request; return the response dict or a status string. Every wait (a free worker, + starting one, writing, reading) ends by BATCH_BACKSTOP_S; a worker that fails is replaced.""" + deadline = time.monotonic() + BATCH_BACKSTOP_S + try: + worker = _acquire(deadline) + except _PoolTimeout: + return "pool timeout" + except (RuntimeError, OSError) as exc: + return f"worker start failed: {exc}"[:200] + response: Any = "exited" + try: + response = worker.request(dict(payload, id=secrets.token_hex(8)), deadline) + return response + finally: + _release(worker, isinstance(response, dict) and "error" not in response) + + +def warm() -> None: + """Start every worker now (each compiles python.wasm) so the first episode does not wait. + Workers already acquired go back to the pool even if a later one fails to start.""" + deadline = time.monotonic() + WORKER_STARTUP_S * _pool_size() + acquired = [] + try: + for _ in range(_pool_size()): + acquired.append(_acquire(deadline, capped=False)) + finally: + for worker in acquired: + _release(worker, True) + + +def shutdown() -> None: + with _POOL: + workers, _IDLE[:] = list(_IDLE), [] + _LIVE[0] -= len(workers) + _POOL.notify_all() + for worker in workers: + worker.close() + + +atexit.register(shutdown) + + +def _parse_results(response: Any, n: int) -> list[CallResult]: + if not isinstance(response, dict) or not isinstance(response.get("results"), list): + raise ValueError(f"no results: {response!r}"[:200]) + rows = response["results"] + if len(rows) != n: + raise ValueError("result count mismatch") + out = [] + for row in rows: + if not isinstance(row, dict) or set(row) - {"k", "v", "e", "f"}: + raise ValueError("bad result row") + kind, error, fuel = row.get("k"), row.get("e", ""), row.get("f", 0) + if kind not in WORKER_KINDS or not isinstance(error, str) or type(fuel) is not int or fuel < 0: + raise ValueError("bad result kind") + if kind == "exc" and not isinstance(row.get("v"), str): + raise ValueError("bad exception name") + value = row.get("v") if kind in ("ok", "exc") else None + out.append(CallResult(kind=kind, value=value, error=error[:200], fuel=fuel)) + return out + + +def run_calls(source: str, entry: str, calls: list[list], *, timeout_s: float | None = None, + per_call_timeout_s: float | None = None, mem_mb: int = DEFAULT_MEM_MB, fuel: int | None = None, + _skip_gate: bool = False) -> list[CallResult]: + """Call ``entry(*args)`` for each args list in ``calls`` in one sandboxed guest instance. + + Each call may consume ``fuel`` units (default ``FUEL_PER_CALL``) and the module body + ``MODULE_FUEL``. ``per_call_timeout_s`` is accepted for compatibility and converted at + ``FUEL_PER_SECOND``; ``timeout_s`` is accepted and ignored (fuel bounds every call and a + wall-clock backstop bounds the instance). ``_skip_gate`` exists only so tests can prove the + runtime layers on their own. + """ + del timeout_s + if not all(isinstance(c, (list, tuple)) for c in calls): + raise TypeError("each call must be a list of positional arguments") + calls = [list(c) for c in calls] + if not calls: + return [] + if not _skip_gate: + problems = static_gate(source) + if problems: + return [CallResult("rejected", None, "; ".join(problems)[:400]) for _ in calls] + if fuel is None: + fuel = FUEL_PER_CALL if per_call_timeout_s is None else max(1, int(per_call_timeout_s * FUEL_PER_SECOND)) + payload = { + "source": source, "entry": entry, "calls": calls, "nonce": secrets.token_hex(16), + "fuel": int(fuel), "module_fuel": MODULE_FUEL, "mem_mb": int(mem_mb), + "modules": SAFE_EXPORTS, "builtins": SAFE_BUILTINS, + "max_value_bytes": MAX_VALUE_BYTES, "max_total_bytes": MAX_RESULT_BYTES, + } + status = "" + for _ in range(2): # a dead worker is replaced and the batch retried once + response = _dispatch(payload) + try: + return _parse_results(response, len(calls)) + except ValueError as exc: + status = str(exc) + return [CallResult("infra", None, f"sandbox worker: {status}"[:200]) for _ in calls] + + +def _probe_guest(kind: str = "surface", mem_mb: int = DEFAULT_MEM_MB) -> dict: + """Ask the guest harness to describe its own surface (test hook; runs no candidate code).""" + response = _dispatch({"probe": kind, "nonce": secrets.token_hex(16), "modules": SAFE_EXPORTS, + "mem_mb": mem_mb}) + return response.get("probe", {}) if isinstance(response, dict) else {"error": response} + + +# --------------------------------------------------------------------------- comparison + +def _equal(a: Any, b: Any) -> bool: + ta, tb = type(a), type(b) + if ta is not tb: + return False + if ta is float: + if math.isnan(a) or math.isnan(b): + return math.isnan(a) and math.isnan(b) + if math.isinf(a) or math.isinf(b): + return a == b + return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12) + if ta is list: + return len(a) == len(b) and all(_equal(x, y) for x, y in zip(a, b)) + if ta is dict: + return a.keys() == b.keys() and all(_equal(a[k], b[k]) for k in a) + if ta in (int, str, bool, type(None)): + return a == b + return False + + +def compare(expected: CallResult, actual: CallResult) -> bool: + """True when two results agree: ok/ok by strict JSON value equality (bool is not int, int is not + float, floats within rel 1e-9 / abs 1e-12), exc/exc by exception type name. Anything else, + including fuel, resource, crash, infra and rejected on either side, is a mismatch. Fuel is never + compared: it depends on what ran earlier in the same instance.""" + if expected.kind == "ok" and actual.kind == "ok": + try: + return _equal(_jsonish(expected.value), _jsonish(actual.value)) + except (RecursionError, ValueError): + return False + if expected.kind == "exc" and actual.kind == "exc": + return isinstance(expected.value, str) and expected.value == actual.value + return False + + +def _jsonish(value: Any) -> Any: + """Normalize a caller-built value (tuples become lists) the way the child normalizes results.""" + if isinstance(value, tuple): + return [_jsonish(v) for v in value] + if type(value) is list: + return [_jsonish(v) for v in value] + if type(value) is dict: + return {k: _jsonish(v) for k, v in value.items()} + return value diff --git a/components/qemedia/upstream/qe_arena/shell.py b/components/qemedia/upstream/qe_arena/shell.py new file mode 100644 index 0000000000000000000000000000000000000000..fb33220396caa25b5f971344a3dc7fdd49a37d9d --- /dev/null +++ b/components/qemedia/upstream/qe_arena/shell.py @@ -0,0 +1,566 @@ +"""A real bash shell per episode, for exploring only: the reward never depends on anything it prints. + +Isolation comes from the operating system, not from parsing commands: + +* ``uid`` mode (the terminal image, whose server runs as root): every episode gets its own unprivileged uid + from ``UID_POOL`` and a 0700 workspace owned by it. Commands, file writes and the read of the graded file + all run as that uid, so it cannot read the image's sources (0700 root), other episodes' workspaces or the + server's memory and environment, and cannot signal the server. The shared world-writable directories are + locked (``SHARED_DIRS``), so the workspace is the only place an episode can write, and anything the uid + still owns elsewhere is removed when the episode closes. A seccomp filter (``NETBLOCK``) allows only + AF_UNIX sockets, so there is no network, loopback to the server included. Each command runs under ulimits + with a minimal environment (no inherited secrets) and umask 077, and every process the uid left behind is + killed afterwards. A uid whose processes could not be killed is never reused. +* ``unsandboxed`` mode (tests and local development only, opt-in with ``QE_ARENA_UNSANDBOXED_SHELL=1``): + the same code path as the server's own user, with no isolation. Never set this on a shared host. +* ``disabled`` mode (anything else, e.g. a node that drops CAP_SETUID, board #213, or one where any part + of the uid-mode probe fails): ``exec`` is refused, while ``write_file`` and the graded-file read happen + in-process on validated relative paths. Without ``exec`` nothing the model controls can plant a symlink or + FIFO, so that is safe, and the episode still trains the write-then-evaluate habit instead of scoring 0. + +Not isolated, for want of privileges (no cgroups or namespaces): total disk use and inode count inside the +workspace (only per file, ``LIMITS``), total memory across an episode's processes (only per process), the +argv of programs a command starts (``/proc//cmdline`` is world-readable without hidepid), and abstract +AF_UNIX sockets. The last two let concurrently running episodes cooperate if both try; neither reaches the +grader, the hidden tests or the reference sources. +""" + +from __future__ import annotations + +import logging +import os +import select +import shutil +import signal +import stat +import subprocess +import sys +import tempfile +import threading +import time +from dataclasses import dataclass +from pathlib import Path + +log = logging.getLogger(__name__) + +EXEC_TIMEOUT_S = 30.0 +IO_TIMEOUT_S = 10.0 +KILL_HELPER_TIMEOUT_S = 5.0 +EXIT_GRACE_S = 0.5 # after the command exits, how long background holders of its output may keep writing +MAX_OUTPUT_BYTES = 8192 # about 2-3k tokens: a careless cat still costs budget, as in the eval +MAX_COMMAND_BYTES = 16384 +MAX_WRITE_BYTES = 65536 +MAX_READ_BYTES = 65536 +MAX_PATH_CHARS = 256 +UID_POOL = range(20000, 20064) +# Per command: CPU seconds, virtual memory (KiB), largest file (KiB), processes of the episode uid. +LIMITS = (("t", 30), ("v", 786432), ("f", 16384), ("u", 32)) +SAFE_PATH = "/usr/local/bin:/usr/bin:/bin" +ENV_FLAG = "QE_ARENA_UNSANDBOXED_SHELL" +ROOT_ENV = "QE_ARENA_WORKSPACES" +# World-writable directories of the image and its runtime mounts. Dockerfile.terminal locks the image's own; +# the probe locks the mounts (tmpfs /tmp, /dev/shm, /dev/mqueue) and checks that an episode uid can write none. +SHARED_DIRS = ("/tmp", "/var/tmp", "/run/lock", "/dev/shm", "/dev/mqueue") + +# Runs as the episode uid, before bash: no_new_privs, then a seccomp filter, then exec of the rest of argv. +# Denied with EACCES: socket() and socketpair() for any family but AF_UNIX (so no network, loopback to the +# server included), io_uring (it can open sockets), System V IPC and POSIX message queues (objects that outlive +# the episode). Killed: another architecture, and syscall numbers >= 512 (x32 and the old x32 range). Jumps are +# assembled from labels. Unprivileged by design; if it cannot be installed the probe selects disabled mode. +NETBLOCK = r""" +import ctypes, os, platform, struct, sys +NRS = {"x86_64": (0xC000003E, 41, 53, (425, 29, 30, 31, 64, 65, 66, 68, 69, 70, 71, 220, 240)), + "aarch64": (0xC00000B7, 198, 199, (425, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 180))} +spec = NRS.get(platform.machine()) +if spec is None: + sys.stderr.write("netblock: unsupported architecture\n"); os._exit(126) +audit, socket_nr, socketpair_nr, denied = spec +LD, JEQ, JGE, RET = 0x20, 0x15, 0x35, 0x06 +code = [("ld", 4), ("jeq", audit, None, "kill"), ("ld", 0), ("jge", 512, "kill", None)] +code += [("jeq", nr, "deny", None) for nr in denied] +code += [("jeq", socket_nr, "family", None), ("jeq", socketpair_nr, "family", "allow")] +code += [("label", "family"), ("ld", 16), ("jeq", 1, "allow", "deny")] +code += [("label", "allow"), ("ret", 0x7FFF0000), ("label", "deny"), ("ret", 0x00050000 | 13), + ("label", "kill"), ("ret", 0x80000000)] +labels, n = {}, 0 +for op in code: + if op[0] == "label": + labels[op[1]] = n + else: + n += 1 +out, i = [], 0 +for op in code: + if op[0] == "label": + continue + rel = lambda t: 0 if t is None else labels[t] - i - 1 + if op[0] == "ld": + out.append((LD, 0, 0, op[1])) + elif op[0] == "ret": + out.append((RET, 0, 0, op[1])) + else: + out.append((JEQ if op[0] == "jeq" else JGE, rel(op[2]), rel(op[3]), op[1])) + i += 1 +buf = ctypes.create_string_buffer(b"".join(struct.pack("HBBI", *ins) for ins in out)) +class Prog(ctypes.Structure): + _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.c_void_p)] +libc = ctypes.CDLL(None, use_errno=True) +fprog = Prog(len(out), ctypes.addressof(buf)) +if libc.prctl(38, 1, 0, 0, 0) != 0 or libc.prctl(22, 2, ctypes.byref(fprog), 0, 0) != 0: + sys.stderr.write("netblock: seccomp unavailable: errno %d\n" % ctypes.get_errno()); os._exit(126) +os.execv(sys.argv[1], sys.argv[1:]) +""" +_MODE: list[str] = [] +_MODE_LOCK = threading.Lock() +_UIDS_LOCK = threading.Lock() +_UIDS_IN_USE: set[int] = set() +_UIDS_QUARANTINED: set[int] = set() + + +def mode() -> str: + """``uid``, ``unsandboxed`` or ``disabled``; probed once per process.""" + with _MODE_LOCK: + if not _MODE: + _MODE.append(_probe()) + log.warning("shell isolation mode: %s", _MODE[0]) + return _MODE[0] + + +def _netblocked(argv: list[str]) -> list[str]: + return [sys.executable, "-I", "-S", "-c", NETBLOCK, *argv] + + +def _lock_shared_dirs() -> None: + for name in SHARED_DIRS: + try: + st = os.lstat(name) + except FileNotFoundError: + continue + if stat.S_ISDIR(st.st_mode) and st.st_mode & 0o002: + os.chmod(name, 0o711) # traversable, so the workspace root below /tmp stays reachable + + +def _probe() -> str: + if os.environ.get(ENV_FLAG) == "1": + return "unsandboxed" + if os.name != "posix" or not hasattr(os, "geteuid") or os.geteuid() != 0 or not Path("/proc").is_dir(): + return "disabled" + uid = UID_POOL[-1] + try: + _lock_shared_dirs() + probe_dir = Path(tempfile.mkdtemp(prefix="probe-", dir=_workspace_root())) + try: + os.chown(probe_dir, uid, uid) # CAP_CHOWN + script = ('test "$(id -u)" = ' + str(uid) + ' || exit 3; ' + + "".join(f"touch {d}/.qe-probe 2>/dev/null && exit 4; " for d in SHARED_DIRS) + + "python3 -c 'import socket; socket.socket()' 2>/dev/null && exit 5; " + + "setsid sleep 60 >/dev/null 2>&1 & echo $! > pid; touch ok") + probe = subprocess.run(_netblocked(["/bin/sh", "-c", script]), cwd=probe_dir, user=uid, group=uid, + extra_groups=[], env={"PATH": SAFE_PATH}, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=IO_TIMEOUT_S, + check=False) + if probe.returncode != 0 or not (probe_dir / "ok").is_file(): + log.warning("shell probe failed: exit %s %s", probe.returncode, probe.stderr[-200:]) + return "disabled" + pid = int((probe_dir / "pid").read_text()) + if not Path(f"/proc/{pid}").exists() or os.stat(f"/proc/{pid}").st_uid != uid: + log.warning("shell probe failed: the detached process did not start") + return "disabled" + killed = _kill_uid(uid) # kill(-1) as the uid must reach it; tini then reaps it + for _ in range(50): + if not Path(f"/proc/{pid}").exists(): + break + time.sleep(0.05) + if not killed or _uid_pids(uid): + log.warning("shell probe failed: a detached process survived SIGKILL") + return "disabled" + finally: + shutil.rmtree(probe_dir, ignore_errors=True) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + log.warning("shell probe failed: %s", exc) + _kill_uid(uid) + return "disabled" + return "uid" + + +def _reset_mode_for_tests() -> None: + with _MODE_LOCK: + _MODE.clear() + + +@dataclass +class Result: + output: str + exit_code: int | None # None: timed out or could not start + timed_out: bool = False + + +def _workspace_root() -> Path: + root = Path(os.environ.get(ROOT_ENV) or Path(tempfile.gettempdir()) / "qe-arena-ws") + root.mkdir(mode=0o711, parents=True, exist_ok=True) + return root + + +def _acquire_uid() -> int: + with _UIDS_LOCK: + for uid in UID_POOL[:-1]: # the last one is the probe's + if uid not in _UIDS_IN_USE and uid not in _UIDS_QUARANTINED: + _UIDS_IN_USE.add(uid) + return uid + raise RuntimeError("no free shell uid: too many live episodes") + + +def _release_uid(uid: int, clean: bool) -> None: + with _UIDS_LOCK: + _UIDS_IN_USE.discard(uid) + if not clean: + _UIDS_QUARANTINED.add(uid) + log.error("shell uid %s quarantined: its processes or files could not be removed", uid) + + +def _state(path: Path) -> bytes | None: + """The state letter from a /proc stat file (bytes: a process name need not be UTF-8), or None if gone.""" + try: + fields = path.read_bytes().rsplit(b")", 1)[1].split() + except (FileNotFoundError, ProcessLookupError, IndexError): + return None + return fields[0] if fields else None + + +def _uid_pids(uid: int) -> list[int]: + """Processes of ``uid`` with any live thread. A zombie thread-group leader whose other threads still run + counts as live (signalling its pid kills the whole group); a fully dead zombie does not, since only its + parent can reap it.""" + pids = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid != uid: + continue + except FileNotFoundError: + continue + state = _state(entry / "stat") + if state is None: + continue + if state in (b"Z", b"X"): + try: + tasks = list((entry / "task").iterdir()) + except (FileNotFoundError, ProcessLookupError): + continue + if not any(_state(t / "stat") not in (None, b"Z", b"X") for t in tasks): + continue + pids.append(int(entry.name)) + return pids + + +KILLER_UID_OFFSET = 10_000 # each episode uid's kill helper runs with real/saved uid uid + this +_KILL_ALL = ("import os, signal, sys\n" + "killer, uid = int(sys.argv[1]), int(sys.argv[2])\n" + "os.setgroups([])\n" + "os.setresgid(killer, killer, killer)\n" + "os.setresuid(killer, uid, killer)\n" + "status = dict(line.split(':', 1) for line in open('/proc/self/status') if ':' in line)\n" + "if any(int(status[k], 16) for k in ('CapEff', 'CapPrm', 'CapAmb')):\n" + " sys.exit(3) # e.g. SECBIT_NO_SETUID_FIXUP kept CAP_KILL: kill(-1) could reach root\n" + "try:\n" + " os.kill(-1, signal.SIGKILL)\n" + "except ProcessLookupError:\n" + " pass\n") + + +def _kill_as(uid: int) -> bool: + """Run a helper that sends kill(-1, SIGKILL) for ``uid``; True only if it exited 0 in time. + + The helper starts as root and switches to real and saved uid ``uid + KILLER_UID_OFFSET`` with effective + uid ``uid`` (no capabilities remain). kill(-1) then reaches every process whose real or saved uid is + ``uid``, in one pass under the task-list lock, so a fork cannot slip past it and no pid is ever signalled + as root; root's processes and other episodes' are out of reach. The episode cannot signal, trace or read + the helper at any point: before the switch it is root, after it its real and saved uid are not the + episode's. A timeout kills our own unreaped child, which has no pid-reuse race.""" + try: + proc = subprocess.Popen([sys.executable, "-I", "-S", "-c", _KILL_ALL, str(uid + KILLER_UID_OFFSET), str(uid)], + env={}, cwd="/", stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, close_fds=True) + except (OSError, subprocess.SubprocessError): + return False + try: + return proc.wait(timeout=KILL_HELPER_TIMEOUT_S) == 0 + except subprocess.TimeoutExpired: + proc.kill() + try: + proc.wait(timeout=KILL_HELPER_TIMEOUT_S) + except subprocess.TimeoutExpired: + log.error("shell kill helper %s did not exit after SIGKILL", proc.pid) + return False + + +def _kill_uid(uid: int) -> bool: + """SIGKILL every process of ``uid``; True only when a kill(-1) for that uid completed and /proc then shows + nothing live. A scan alone never counts: it can miss a child forked while it ran. Any error is a failure.""" + try: + for _ in range(10): + if _kill_as(uid): + for _ in range(20): # SIGKILL is queued; let the targets finish dying + if not _uid_pids(uid): + return True + time.sleep(0.01) + time.sleep(0.05) + except Exception: # noqa: BLE001 - an unexpected failure must read as unclean, never as clean + log.exception("shell uid %s kill failed", uid) + return False + + +def _sweep_uid_files(uid: int) -> bool: + """Remove what ``uid`` owns in the shared directories; normally nothing, since they are locked.""" + clean = True + for name in SHARED_DIRS: + try: + entries = list(os.scandir(name)) + except FileNotFoundError: + continue + except OSError: + clean = False + continue + for entry in entries: + try: + if entry.stat(follow_symlinks=False).st_uid != uid: + continue + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.path) + else: + os.unlink(entry.path) + except FileNotFoundError: + continue + except OSError: + clean = False + return clean + + +def _valid_relative(path: str) -> str | None: + """A normalised relative path inside the workspace, or None.""" + if not path or len(path) > MAX_PATH_CHARS or "\0" in path: + return None + parts = [p for p in path.split("/") if p not in ("", ".")] + if path.startswith("/") or not parts or any(p == ".." for p in parts): + return None + return "/".join(parts) + + +def _feed(pipe, data: bytes) -> None: + """Write stdin from a thread, so a reader that never reads cannot block the caller past its deadline.""" + try: + pipe.write(data) + except (BrokenPipeError, OSError, ValueError): + pass + finally: + try: + pipe.close() + except (BrokenPipeError, OSError): + pass + + +class Workspace: + """One episode's directory and, in ``uid`` mode, its uid. ``close`` removes both.""" + + def __init__(self, files: dict[str, str]): + self._closed = True # until fully built: close() then has nothing to undo + self._tainted = False # a per-command cleanup failed: never release the uid as clean + self.path: Path | None = None + self.mode = mode() + self.uid = _acquire_uid() if self.mode == "uid" else None + try: + self.path = Path(tempfile.mkdtemp(prefix="ep-", dir=_workspace_root())) + for name, text in files.items(): + target = self.path / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + if self.uid is not None: + for dirpath, dirnames, filenames in os.walk(self.path): + for name in dirnames + filenames: + os.chown(os.path.join(dirpath, name), self.uid, self.uid) + os.chown(self.path, self.uid, self.uid) + os.chmod(self.path, 0o700) + except BaseException: + removed = True + if self.path is not None: + shutil.rmtree(self.path, ignore_errors=True) + removed = not self.path.exists() + if self.uid is not None: + _release_uid(self.uid, clean=removed) # nothing ran as it, but files may already be its + raise + self._closed = False + + @property + def exec_available(self) -> bool: + return self.mode in ("uid", "unsandboxed") + + def _env(self) -> dict[str, str]: + home = str(self.path) + return {"PATH": SAFE_PATH, "HOME": home, "TMPDIR": home, "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", + "TERM": "dumb", "PYTHONDONTWRITEBYTECODE": "1", "PYTHONUNBUFFERED": "1"} + + def _spawn(self, argv: list[str], stdin: bool, extra_env: dict[str, str] | None = None) -> subprocess.Popen: + kwargs = {} + if self.uid is not None: + kwargs = {"user": self.uid, "group": self.uid, "extra_groups": [], "umask": 0o077} + argv = _netblocked(argv) + return subprocess.Popen(argv, cwd=self.path, env={**self._env(), **(extra_env or {})}, + start_new_session=True, close_fds=True, + stdin=subprocess.PIPE if stdin else subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs) + + def _run(self, argv: list[str], timeout_s: float, cap: int, stdin: bytes | None = None, + extra_env: dict[str, str] | None = None) -> tuple[bytes, int, int | None, bool]: + """(first ``cap`` bytes of output, total bytes, exit code, timed out).""" + deadline = time.monotonic() + timeout_s + proc = self._spawn(argv, stdin is not None, extra_env) + kept, total, timed_out, exited_at = bytearray(), 0, False, None + try: + if stdin is not None: + threading.Thread(target=_feed, args=(proc.stdin, stdin), daemon=True).start() + fd = proc.stdout.fileno() + while True: + now = time.monotonic() + if exited_at is None and proc.poll() is not None: + exited_at = now + if now >= deadline: + timed_out = proc.poll() is None + break + if exited_at is not None and now - exited_at >= EXIT_GRACE_S: + break + limit = deadline if exited_at is None else min(deadline, exited_at + EXIT_GRACE_S) + ready, _, _ = select.select([fd], [], [], max(0.0, min(limit - now, 0.1))) + if not ready: + continue + chunk = os.read(fd, 65536) + if not chunk: + if exited_at is None: + try: + proc.wait(timeout=max(0.0, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + timed_out = True + break + total += len(chunk) + if len(kept) < cap: + kept.extend(chunk[:cap - len(kept)]) + finally: + self._kill(proc) # also unblocks the stdin thread: its reader is gone + proc.stdout.close() + code = None if timed_out else proc.returncode + return bytes(kept), total, code, timed_out + + def _kill(self, proc: subprocess.Popen) -> None: + if self.uid is None: # unsandboxed (tests): the command's own group + try: + os.killpg(proc.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + elif not _kill_uid(self.uid): # every process of the uid, including any that left the group + self._tainted = True # close() then quarantines the uid + log.error("shell uid %s has processes that SIGKILL did not remove", self.uid) + try: + proc.wait(timeout=IO_TIMEOUT_S) + except subprocess.TimeoutExpired: + log.error("shell process %s did not exit after SIGKILL", proc.pid) + + def exec(self, command: str, timeout_s: float = EXEC_TIMEOUT_S) -> Result: + if not self.exec_available: + return Result("exec is unavailable on this host; use write_file and evaluate", None) + if not command.strip(): + return Result("empty command", None) + if len(command.encode("utf-8", "surrogatepass")) > MAX_COMMAND_BYTES or "\0" in command: + return Result(f"command too long (limit {MAX_COMMAND_BYTES} bytes)", None) + # RLIMIT_NPROC counts every process of the real uid, so it is only meaningful for an episode's own uid. + limits = "; ".join(f"ulimit -{flag} {value} 2>/dev/null" for flag, value in LIMITS + if flag != "u" or self.uid is not None) + # The command travels in the environment, not argv: /proc//environ is private to the uid, while + # cmdline is world-readable. (What the command itself starts, e.g. python3 -c, is in argv as usual.) + wrapper = (f"{limits}; {{ echo 1000 > /proc/self/oom_score_adj; }} 2>/dev/null; " + 'qe_command=$QE_COMMAND; unset QE_COMMAND; eval "$qe_command"') + out, total, code, timed_out = self._run(["/bin/bash", "--noprofile", "--norc", "-c", wrapper, "qe-shell"], + timeout_s, MAX_OUTPUT_BYTES, extra_env={"QE_COMMAND": command}) + text = out.decode("utf-8", "replace") + if total > len(out): + text += f"\n[output truncated: {total} bytes, first {len(out)} shown]" + if timed_out: + text += f"\n[command timed out after {timeout_s:g} s and was killed]" + return Result(text, code, timed_out) + + def write(self, file_path: str, content: str) -> str | None: + """Write a whole file; an error message, or None on success.""" + data = content.encode("utf-8", "replace") + if len(data) > MAX_WRITE_BYTES: + return f"content too large (limit {MAX_WRITE_BYTES} bytes)" + if not file_path or len(file_path) > MAX_PATH_CHARS or "\0" in file_path: + return "file_path must be a non-empty path" + if not self.exec_available: + rel = _valid_relative(file_path) + if rel is None: + return "file_path must be a relative path inside the working directory" + return self._write_in_process(rel, data) + script = 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"' + out, _, code, timed_out = self._run(["/bin/sh", "-c", script, "qe-write", file_path], IO_TIMEOUT_S, 2048, + stdin=data) + if timed_out or code != 0: + return "could not write file: " + (out.decode("utf-8", "replace").strip() or "timed out")[:300] + return None + + def _write_in_process(self, rel: str, data: bytes) -> str | None: + target = self.path / rel + try: + target.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "wb") as handle: + handle.write(data) + except OSError as exc: + return f"could not write file: {exc.strerror}" + return None + + def read(self, rel: str) -> str | None: + """The graded file's text, read with the episode's own permissions; None if missing or unreadable.""" + if _valid_relative(rel) != rel: + raise ValueError("graded paths are fixed relative names") + if not self.exec_available: + try: + fd = os.open(self.path / rel, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError: + return None + with os.fdopen(fd, "rb") as handle: + if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): + return None + data = handle.read(MAX_READ_BYTES + 1) + else: + # As the episode uid, so a symlink or FIFO the model planted reads only what that uid could. + script = 'test -f "$1" && exec cat -- "$1"' + data, total, code, timed_out = self._run(["/bin/sh", "-c", script, "qe-read", rel], IO_TIMEOUT_S, + MAX_READ_BYTES + 1) + if timed_out or code != 0: + return None + if len(data) > MAX_READ_BYTES: + return None + try: + return data.decode("utf-8") + except UnicodeDecodeError: + return None + + def close(self) -> None: + if self._closed: + return + self._closed = True + clean = True + if self.uid is not None: + try: + clean = _kill_uid(self.uid) and _sweep_uid_files(self.uid) and not self._tainted + except Exception: # noqa: BLE001 - an unexpected scan failure must still free the directory + log.exception("shell uid %s cleanup failed", self.uid) + clean = False + shutil.rmtree(self.path, ignore_errors=True) + clean = clean and not self.path.exists() + if self.uid is not None: + _release_uid(self.uid, clean) + + def __del__(self): # a dropped environment must not leak its uid or directory + try: + self.close() + except Exception: # noqa: BLE001 + pass diff --git a/components/qemedia/upstream/qe_arena/skills/__init__.py b/components/qemedia/upstream/qe_arena/skills/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5bbc1d5267c4e5963db49e4e1bfe6a1c663fde66 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/skills/__init__.py @@ -0,0 +1,156 @@ +"""qe_skill: content tasks (science, math, media) served only behind the terminal interface. + +The arena's private tasks are Terminal-Bench 2 / SkillsBench-shaped: an instruction, input files in a working +directory, and hidden checks on an output file. These tasks train that work directly. A cell is a domain and a +level (``qe_skill-science-d2``); each seed draws one of the domain's families, as a code cell draws one corpus +function. Calibration can restrict a cell to one family with ``pool``; an episode cannot. + +Every family is generated from ``(task_id, seed)`` by trusted code, which also computes the reference. Grading +reads the model's output file as data and never runs it, so no sandbox is needed. A family also ships a solver with +named wrong-method variants ("traps"), and generation retries until every trap that applies at the level fails at +least one check, so a seed never rewards a listed wrong method. Check names never reach an observation. +""" + +from __future__ import annotations + +import random +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any + +from ..domains import BY_SLUG, SLUGS + +FAMILY = "qe_skill" +LEVELS = (1, 2, 3) +MAX_OUTPUT_BYTES = 65536 +MAX_ATTEMPTS = 64 # generation retries per seed before a family gives up + + +@dataclass +class Built: + """One generated task before it is bound to an ID: what the model sees and what grades it.""" + files: dict[str, str] + statement: str + output: str + reference: Any + + +@dataclass(frozen=True) +class Family: + name: str + domain: str + build: Callable[[int, random.Random], Built] + check: Callable[[Any, str], list[bool]] + solve: Callable[[dict[str, str], int, str | None], str] + traps: dict[str, tuple[int, ...]] # trap name -> levels where it applies + + +@dataclass +class SkillTask: + task_id: str + family: str + difficulty: int + seed: int + domain: str + kind: str + prompt: str + files: dict[str, str] + output: str + private: dict[str, Any] = field(repr=False) + + +def _families() -> dict[str, tuple[Family, ...]]: + from . import formal, media, science # noqa: PLC0415 - the modules import Built and Family from here + + by_domain: dict[str, list[Family]] = {} + for module in (science, formal, media): + for family in module.FAMILIES: + by_domain.setdefault(family.domain, []).append(family) + return {domain: tuple(fams) for domain, fams in by_domain.items()} + + +FAMILIES = _families() +ALL_SKILL_IDS = [f"{FAMILY}-{SLUGS[domain]}-d{level}" for domain in FAMILIES for level in LEVELS] + +# What an episode may draw, per cell: the families whose strict untrained solve rate fell in 4-12 of 16 in the v7 +# calibration (2026-10-20, runs/v7-cal; subtitles after its one adjustment round). Cells with no such family are +# not served. Calibration reaches any (cell, family) through ``pool``. +SERVED = { + "qe_skill-science-d2": ("units", "calibration", "decay", "dilution"), + "qe_skill-science-d3": ("units", "decay", "dilution"), + "qe_skill-math-d1": ("linear", "counting", "congruences", "falsify"), + "qe_skill-math-d2": ("counting", "congruences"), + "qe_skill-math-d3": ("linear", "counting", "congruences"), + "qe_skill-media-d1": ("timecode", "catalogue", "assets"), + "qe_skill-media-d2": ("subtitles", "timecode", "catalogue", "assets"), +} +SKILL_TASK_IDS = [task_id for task_id in ALL_SKILL_IDS if task_id in SERVED] + + +def parse_skill_id(task_id: str) -> tuple[str, int]: + """(domain, level) of a qe_skill task ID (served, or reachable by calibration through a pool).""" + if type(task_id) is not str or task_id not in ALL_SKILL_IDS: + raise ValueError(f"invalid task_id: {task_id!r}") + _, slug, level = task_id.split("-") + return BY_SLUG[slug], int(level[1:]) + + +def family_names(task_id: str) -> tuple[str, ...]: + return tuple(f.name for f in FAMILIES[parse_skill_id(task_id)[0]]) + + +def family(domain: str, name: str) -> Family: + for fam in FAMILIES[domain]: + if fam.name == name: + return fam + raise ValueError(f"no {name!r} family in {domain}") + + +def _trap_free(fam: Family, built: Built, level: int) -> bool: + for trap, levels in fam.traps.items(): + if level in levels and all(fam.check(built.reference, fam.solve(built.files, level, trap))): + return False + return True + + +def make_skill_task(task_id: str, seed: int, *, pool: tuple[str, ...] | None = None) -> SkillTask: + """Build the task for (task_id, seed). ``pool`` (family names) exists for calibration only.""" + domain, level = parse_skill_id(task_id) + if type(seed) is not int or not 0 <= seed < 2**64: + raise ValueError("seed must be an unsigned 64 bit integer") + fams = FAMILIES[domain] + if pool is not None: + if not pool or any(name not in {f.name for f in fams} for name in pool): + raise ValueError(f"pool must name {domain} families: {[f.name for f in fams]}") + fams = tuple(f for f in fams if f.name in pool) + elif task_id in SERVED: + fams = tuple(f for f in fams if f.name in SERVED[task_id]) + else: + raise ValueError(f"{task_id} is not served (no family passed calibration); calibration must name a pool") + rng = random.Random(f"{task_id}:{seed}") + fam = rng.choice(fams) + for _ in range(MAX_ATTEMPTS): + built = fam.build(level, rng) + if _trap_free(fam, built, level): + break + else: + raise RuntimeError(f"{fam.name} could not build a trap-free task for {task_id} seed {seed}") + return SkillTask(task_id=task_id, family=FAMILY, difficulty=level, seed=seed, domain=domain, kind=fam.name, + prompt=built.statement, files=built.files, output=built.output, + private={"reference": built.reference, "family": fam, "corpus": fam.name}) # calibration's key + + +def grade(task: SkillTask, text: str | None) -> float: + """1.0 only if every check passes on the output file; a missing, oversized or unparseable file scores 0.""" + if text is None or len(text.encode("utf-8")) > MAX_OUTPUT_BYTES: + return 0.0 + try: + results = task.private["family"].check(task.private["reference"], text) + except Exception: # noqa: BLE001 - malformed model output is a wrong answer, never a crash + return 0.0 + return 1.0 if results and all(results) else 0.0 + + +def solve(task: SkillTask, variant: str | None = None) -> str: + """The oracle's output (variant None) or a named wrong method's, computed from the visible files only.""" + return task.private["family"].solve(task.files, task.difficulty, variant) diff --git a/components/qemedia/upstream/qe_arena/skills/_common.py b/components/qemedia/upstream/qe_arena/skills/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..72d8a732cf9e0d9bf8290352acebcc2aa937ceed --- /dev/null +++ b/components/qemedia/upstream/qe_arena/skills/_common.py @@ -0,0 +1,54 @@ +"""Strict, bounded readers for model output. Output is data: parsed, never evaluated.""" + +from __future__ import annotations + +import csv +import io +import json +import math +from typing import Any + +MAX_DEPTH = 32 + + +def _depth(value: Any, level: int = 0) -> int: + if level > MAX_DEPTH: + raise ValueError("output nests too deeply") + if isinstance(value, dict): + return max([_depth(v, level + 1) for v in value.values()], default=level) + if isinstance(value, list): + return max([_depth(v, level + 1) for v in value], default=level) + return level + + +def load_object(text: str) -> dict: + """The output file as one JSON object (no NaN or Infinity), or ValueError.""" + def reject(token: str) -> None: + raise ValueError(f"non-finite number {token}") + + value = json.loads(text, parse_constant=reject) + if not isinstance(value, dict): + raise ValueError("output must be a JSON object") + _depth(value) + return value + + +def is_number(value: Any) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def close(value: Any, reference: float, tolerance: float) -> bool: + """A finite number within ``tolerance`` (absolute) of the reference.""" + return is_number(value) and abs(value - reference) <= tolerance + + +def rows(text: str) -> list[dict[str, str]]: + return list(csv.DictReader(io.StringIO(text))) + + +def write_csv(header: list[str], records: list[list[Any]]) -> str: + out = io.StringIO() + writer = csv.writer(out, lineterminator="\n") + writer.writerow(header) + writer.writerows(records) + return out.getvalue() diff --git a/components/qemedia/upstream/qe_arena/skills/formal.py b/components/qemedia/upstream/qe_arena/skills/formal.py new file mode 100644 index 0000000000000000000000000000000000000000..20f83dd83ac2bade9333ecdb17f4d5ad0a278df0 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/skills/formal.py @@ -0,0 +1,501 @@ +"""mathematics-or-formal-reasoning families for qe_skill. (Named formal, not math, to keep the stdlib module.)""" + +from __future__ import annotations + +import json +import random +import re +from fractions import Fraction +from itertools import permutations +from math import factorial, gcd, prod + +from . import Built, Family +from ._common import load_object + +DOMAIN = "mathematics-or-formal-reasoning" + +# M1 linear: an integer linear system solved exactly. +SIZES = {1: 2, 2: 3, 3: 4} +EQUATION = re.compile(r"^\s*(.+?)\s*=\s*(-?\d+)\s*$") +TERM = re.compile(r"([+-]?)\s*(\d*)\s*\*?\s*x(\d+)") +CANONICAL = re.compile(r"-?(0|[1-9]\d*)(/[1-9]\d*)?") + + +def _canonical(value: Fraction) -> str: + return str(value.numerator) if value.denominator == 1 else f"{value.numerator}/{value.denominator}" + + +def _equation(coeffs: list[int], rhs: int) -> str: + parts = [] + for i, c in enumerate(coeffs, 1): + if c == 0: + continue + sign = "-" if c < 0 else "+" + mag = "" if abs(c) == 1 else f"{abs(c)}*" + parts.append(f"{sign} {mag}x{i}") + text = " ".join(parts) or "0" + text = text[2:] if text.startswith("+ ") else "-" + text[2:] if text.startswith("- ") else text + return f"{text} = {rhs}" + + +def _parse_system(text: str) -> tuple[list[list[Fraction]], list[Fraction], int]: + eqs = [line for line in text.splitlines() if line.strip() and not line.lstrip().startswith("#")] + parsed = [] + n = 0 + for line in eqs: + match = EQUATION.match(line) + lhs, rhs = match.group(1), int(match.group(2)) + terms = {} + for sign, mag, idx in TERM.findall(lhs.replace(" ", "")): + terms[int(idx)] = (-1 if sign == "-" else 1) * (int(mag) if mag else 1) + n = max(n, int(idx)) + parsed.append((terms, rhs)) + a = [[Fraction(terms.get(j + 1, 0)) for j in range(n)] for terms, _ in parsed] + b = [Fraction(rhs) for _, rhs in parsed] + return a, b, n + + +def _eliminate(a: list[list[Fraction]], b: list[Fraction], n: int) -> tuple[str, list[Fraction]]: + """("unique", x), ("none", []) or ("infinite", []) by exact Gauss-Jordan elimination.""" + m = [row[:] + [rhs] for row, rhs in zip(a, b)] + rank, pivots = 0, [] + for col in range(n): + pivot = next((r for r in range(rank, len(m)) if m[r][col] != 0), None) + if pivot is None: + continue + m[rank], m[pivot] = m[pivot], m[rank] + m[rank] = [v / m[rank][col] for v in m[rank]] + for r in range(len(m)): + if r != rank and m[r][col] != 0: + f = m[r][col] + m[r] = [v - f * p for v, p in zip(m[r], m[rank])] + pivots.append(col) + rank += 1 + if any(all(v == 0 for v in row[:n]) and row[n] != 0 for row in m): + return "none", [] + if rank < n: + return "infinite", [] + x = [Fraction(0)] * n + for r, col in enumerate(pivots): + x[col] = m[r][n] + return "unique", x + + +def _linear_build(level: int, rng: random.Random) -> Built: + n = SIZES[level] + kind = "unique" if level < 3 else rng.choice(("unique", "unique", "none", "infinite")) + while True: + a = [[rng.randint(-9, 9) for _ in range(n)] for _ in range(n)] + if kind != "unique": # make the last row a combination of two others; keep or break consistency + i, j = rng.sample(range(n - 1), 2) + p, q = rng.choice((1, 2, -1, 3)), rng.choice((1, -1, 2)) + a[-1] = [p * a[i][k] + q * a[j][k] for k in range(n)] + b = [rng.randint(-30, 30) for _ in range(n)] + if kind != "unique": + b[-1] = p * b[i] + q * b[j] + (rng.choice((1, -1)) * rng.randint(1, 9) if kind == "none" else 0) + status, x = _eliminate([[Fraction(v) for v in row] for row in a], [Fraction(v) for v in b], n) + if status != kind or any(all(v == 0 for v in row) for row in a): + continue + if status == "unique" and not any(v.denominator > 1 for v in x): + continue + break + order = list(range(n)) + rng.shuffle(order) + system = "\n".join(_equation(a[r], b[r]) for r in order) + "\n" + variables = ", ".join(f"x{i}" for i in range(1, n + 1)) + statement = "\n".join([ + f"system.txt holds a system of linear equations in {variables} with integer coefficients.", + "Solve it exactly. Floating-point answers are wrong: give each value as a reduced fraction string such as " + '"-7/3", or an integer string such as "4".', + 'Write solution.json as {"status": "unique", "x": ["", "", ...]} in variable order.' + + (' If the system has no solution, or infinitely many, write an object whose only key is "status", set ' + 'to "none" or "infinite" respectively.' if level == 3 else ""), + ]) + built = Built(files={"system.txt": system}, statement=statement, output="solution.json", reference=None) + built.reference = json.loads(_linear_solve(built.files, level, None)) + return built + + +def _linear_solve(files: dict[str, str], level: int, variant: str | None) -> str: + a, b, n = _parse_system(files["system.txt"]) + status, x = _eliminate(a, b, n) + if variant == "singular_missed": # applies only to a singular system; elsewhere it names no answer at all + return json.dumps({"status": "unique", "x": ["0"] * n} if status != "unique" else {"status": "n/a"}) + if status != "unique": # the fraction-format traps name no answer for a singular system + return json.dumps({"status": "n/a" if variant in ("float", "unreduced") else status}) + if variant == "float": + return json.dumps({"status": "unique", "x": [f"{float(v):.6f}" for v in x]}) + if variant == "unreduced": # Cramer's rule without reducing: every value over the common determinant + det = abs(_det([row[:] for row in a])) + return json.dumps({"status": "unique", + "x": [f"{int(v * det)}/{int(det)}" if det != 1 else str(int(v)) for v in x]}) + return json.dumps({"status": "unique", "x": [_canonical(v) for v in x]}) + + +def _det(m: list[list[Fraction]]) -> Fraction: + n, det = len(m), Fraction(1) + for col in range(n): + pivot = next((r for r in range(col, n) if m[r][col] != 0), None) + if pivot is None: + return Fraction(0) + if pivot != col: + m[col], m[pivot] = m[pivot], m[col] + det = -det + det *= m[col][col] + for r in range(col + 1, n): + f = m[r][col] / m[col][col] + m[r] = [v - f * p for v, p in zip(m[r], m[col])] + return det + + +def _linear_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + if reference["status"] != "unique": + return [out.get("status") == reference["status"]] + x = out.get("x") + results = [out.get("status") == "unique", isinstance(x, list) and len(x) == len(reference["x"])] + if not all(results): + return results + return results + [isinstance(v, str) and CANONICAL.fullmatch(v) is not None and v == ref + for v, ref in zip(x, reference["x"])] + + +def _exact_int(value: object, reference: int) -> bool: + return type(value) is int and value == reference + + +# M2 counting: arrangements of letters in a row under constraints, counted by brute force. +COUNT_SIZES = {1: 5, 2: 6, 3: 7} + + +def _violates(arrangement: tuple[str, ...], c: dict) -> bool: + if c["type"] == "not_at": + return arrangement[c["position"] - 1] == c["item"] + x, y = c["items"] + if c["type"] == "not_adjacent": + return any({p, q} == {x, y} for p, q in zip(arrangement, arrangement[1:])) + return arrangement.index(x) > arrangement.index(y) # "before": x left of y; both letters appear once + + +def _constraint_text(c: dict) -> str: + if c["type"] == "not_at": + return f"no {c['item']} in position {c['position']}" + x, y = c["items"] + return f"no {x} directly next to a {y}" if c["type"] == "not_adjacent" else f"{x} somewhere left of {y}" + + +def _violation_masks(items: list[str], constraints: list[dict]) -> list[int]: + """One bitmask per distinct arrangement: bit i set when the arrangement breaks constraint i.""" + return [sum(1 << i for i, c in enumerate(constraints) if _violates(arr, c)) + for arr in sorted(set(permutations(items)))] + + +def _counting_build(level: int, rng: random.Random) -> Built: + n = COUNT_SIZES[level] + while True: + doubles = 0 if level == 1 else rng.choice((1, 2)) if level == 3 else 1 + letters = [chr(65 + i) for i in range(n - doubles)] + items = sorted(letters + rng.sample(letters, doubles)) + singles = [x for x in letters if items.count(x) == 1] + constraints: list[dict] = [] + while len(constraints) < level: + kind = rng.choice(("not_at", "not_adjacent", "before")) + if kind == "not_at": + c = {"type": kind, "item": rng.choice(letters), "position": rng.randint(1, n)} + else: + c = {"type": kind, "items": rng.sample(singles if kind == "before" else letters, 2)} + if all(_constraint_text(c) != _constraint_text(o) for o in constraints): + constraints.append(c) + masks = _violation_masks(items, constraints) + count = masks.count(0) + full = (1 << level) - 1 + binding = all(sum(1 for m in masks if m & (full ^ (1 << i)) == 0) != count for i in range(level)) + overlap = len(masks) - sum(bin(m).count("1") for m in masks) != count + if count > 0 and binding and (level == 1 or overlap): + break + for c in constraints: + c["text"] = _constraint_text(c) + problem = {"items": items, "constraints": constraints} + statement = "\n".join([ + "problem.json lists items to arrange in a row (place every entry of items exactly once, so a letter listed " + "twice appears twice) and constraints on the row. Count the distinct arrangements that satisfy every " + "constraint.", + "Copies of a repeated letter are identical: two arrangements are the same when every position holds the " + "same letter. Positions are numbered from 1 at the left.", + 'Constraint types: "not_at" means no copy of item stands at that position; "not_adjacent" with items [X, Y] ' + 'means no X stands directly next to a Y (either side); "before" with items [X, Y] means X stands somewhere ' + "left of Y. Each constraint also carries a plain-English text.", + 'Write answer.json as {"count": }, the count as a JSON integer.', + ]) + built = Built(files={"problem.json": json.dumps(problem, indent=2) + "\n"}, statement=statement, + output="answer.json", reference=None) + built.reference = json.loads(_counting_solve(built.files, level, None)) + return built + + +def _counting_solve(files: dict[str, str], level: int, variant: str | None) -> str: + problem = json.loads(files["problem.json"]) + items, constraints = problem["items"], problem["constraints"] + if variant == "drop_a_constraint": + constraints = constraints[:-1] + masks = _violation_masks(items, constraints) + count = masks.count(0) + if variant == "ignore_overlap": # total minus each constraint's violations, intersections never added back + count = len(masks) - sum(bin(m).count("1") for m in masks) + if variant == "order_matters_twice": # copies treated as distinct; applies only when a letter repeats + copies = prod(factorial(items.count(x)) for x in set(items)) + return json.dumps({"count": count * copies} if copies > 1 else {"status": "n/a"}) + return json.dumps({"count": count}) + + +def _counting_check(reference: dict, text: str) -> list[bool]: + return [_exact_int(load_object(text).get("count"), reference["count"])] + + +# M3 congruences: x = r_i (mod m_i), solved by combining one congruence at a time. +def _combine(pairs: list[tuple[int, int]], strict: bool = True) -> tuple[int, int] | None: + """(least non-negative x, lcm) of the system, or None when it is inconsistent (``strict``).""" + x, m = 0, 1 + for r, mod in pairs: + g = gcd(m, mod) + if strict and (r - x) % g: + return None + t = ((r - x) // g * pow(m // g, -1, mod // g)) % (mod // g) if mod // g > 1 else 0 + x, m = x + m * t, m * mod // g + x %= m + return x, m + + +def _congruences_build(level: int, rng: random.Random) -> Built: + count = 2 if level == 1 else 3 if level == 2 else rng.choice((3, 4)) + inconsistent = level == 3 and rng.random() < 1 / 3 + while True: + moduli = rng.sample(range(3, 31 if level == 1 else 46), count) + lcm = _combine([(0, m) for m in moduli])[1] + coprime = lcm == prod(moduli) + if (level == 1) != coprime or lcm > 20000 or any(a % b == 0 for a in moduli for b in moduli if a != b): + continue + x0 = rng.randrange(lcm) + pairs = [(x0 % m, m) for m in moduli] + if inconsistent: + i = rng.randrange(count) + pairs[i] = (rng.randrange(moduli[i]), moduli[i]) + if _combine(pairs) is not None: + continue + break + system = {"congruences": [{"remainder": r, "modulus": m} for r, m in pairs]} + statement = "\n".join([ + "system.json lists congruences x = remainder (mod modulus). Find every integer x that satisfies all of them.", + 'Write solution.json as {"status": "solved", "x": , "modulus": }, where M ' + "is the smallest positive integer such that the solutions are exactly the integers congruent to x mod M. " + "Both values are JSON integers." + + (' If no integer satisfies every congruence, write an object whose only key is "status", set to "none".' + if level == 3 else ""), + ]) + built = Built(files={"system.json": json.dumps(system, indent=2) + "\n"}, statement=statement, + output="solution.json", reference=None) + built.reference = json.loads(_congruences_solve(built.files, level, None)) + return built + + +def _congruences_solve(files: dict[str, str], level: int, variant: str | None) -> str: + pairs = [(c["remainder"], c["modulus"]) for c in json.loads(files["system.json"])["congruences"]] + solved = _combine(pairs) + if variant == "inconsistent_missed": # applies only to an inconsistent system: drop the congruence that clashes + rest = next((r for i in range(len(pairs)) if (r := _combine(pairs[:i] + pairs[i + 1:]))), None) + return json.dumps({"status": "solved", "x": rest[0], "modulus": rest[1]} if solved is None and rest + else {"status": "n/a"}) + if variant == "assume_coprime": # the coprime formula: no consistency check, modulus the product + x, _ = _combine(pairs, strict=False) if solved is None else solved + return json.dumps({"status": "solved", "x": x, "modulus": prod(m for _, m in pairs)}) + if solved is None: + return json.dumps({"status": "n/a"} if variant == "not_least" else {"status": "none"}) + x, m = solved + if variant == "not_least": + x += m + return json.dumps({"status": "solved", "x": x, "modulus": m}) + + +def _congruences_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + if reference["status"] == "none": + return [out.get("status") == "none"] + return [out.get("status") == "solved", _exact_int(out.get("x"), reference["x"]), + _exact_int(out.get("modulus"), reference["modulus"])] + + +# M4 falsify: the smallest counterexample to a claim over an integer range, or "holds". +GRID = 18 # claims are scanned on 0..GRID-1 per variable while choosing ranges + + +def _poly(terms: list[dict], point: dict[str, int]) -> int: + return sum(t["coef"] * prod(point[v] ** p for v, p in t.get("powers", {}).items()) for t in terms) + + +def _poly_text(terms: list[dict]) -> str: + parts = [] + for t in terms: + mono = "*".join(v if p == 1 else f"{v}^{p}" for v, p in t.get("powers", {}).items()) + c = t["coef"] + body = mono if mono and abs(c) == 1 else f"{abs(c)}*{mono}" if mono else str(abs(c)) + parts.append(("- " if c < 0 else "+ ") + body) + text = " ".join(parts) + return text[2:] if text.startswith("+ ") else "-" + text[2:] + + +def _is_prime(k: int) -> bool: + return k >= 2 and all(k % d for d in range(2, int(k ** 0.5) + 1)) + + +def _holds(claim: dict, point: dict[str, int]) -> bool: + kind = claim["kind"] + if kind == "at_most": + return _poly(claim["left"], point) <= _poly(claim["right"], point) + if kind == "prime": + return _is_prime(_poly(claim["expr"], point)) + if kind == "not_divisible": + return _poly(claim["expr"], point) % claim["divisor"] != 0 + return gcd(_poly(claim["left"], point), _poly(claim["right"], point)) == 1 # coprime + + +def _claim_text(claim: dict) -> str: + kind = claim["kind"] + if kind == "at_most": + return f"{_poly_text(claim['left'])} <= {_poly_text(claim['right'])}" + if kind == "prime": + return f"{_poly_text(claim['expr'])} is prime" + if kind == "not_divisible": + return f"{_poly_text(claim['expr'])} is not divisible by {claim['divisor']}" + return f"gcd({_poly_text(claim['left'])}, {_poly_text(claim['right'])}) = 1" + + +def _search(claim: dict, ranges: dict[str, list[int]], *, b_major: bool = False, + python_range: bool = False) -> tuple[int, ...] | None: + """The first counterexample in lexicographic order (or b before a, or range(hi) per variable), else None.""" + axes = [range(0, hi) if python_range else range(lo, hi + 1) for lo, hi in ranges.values()] + names = list(ranges) + if len(axes) == 1: + return next(((n,) for n in axes[0] if not _holds(claim, {names[0]: n})), None) + order = ((a, b) for b in axes[1] for a in axes[0]) if b_major else ((a, b) for a in axes[0] for b in axes[1]) + return next(((a, b) for a, b in order if not _holds(claim, dict(zip(names, (a, b))))), None) + + +def _term(rng: random.Random, names: list[str], degree: int) -> dict: + powers = {} + for _ in range(degree): + v = rng.choice(names) + powers[v] = powers.get(v, 0) + 1 + return {"coef": rng.choice((1, 1, 2, 3, -1, -2)), "powers": dict(sorted(powers.items()))} + + +def _random_claim(rng: random.Random, names: list[str]) -> dict: + one = len(names) == 1 + kinds = ("at_most", "prime", "not_divisible") if one else ("at_most", "at_most", "not_divisible", "coprime") + kind = rng.choice(kinds) + const = {"coef": rng.randint(1, 41)} + if kind == "prime": + return {"kind": kind, "expr": [{"coef": 1, "powers": {"n": 2}}, {"coef": rng.randint(-9, 9) or 1, + "powers": {"n": 1}}, {"coef": rng.choice(range(1, 42, 2))}]} + if kind == "not_divisible": + return {"kind": kind, "expr": [_term(rng, names, 2), _term(rng, names, rng.randint(1, 2)), const], + "divisor": rng.randint(5, 13)} + if kind == "coprime": + return {"kind": kind, "left": [_term(rng, names, 1), _term(rng, names, 1), const], + "right": [_term(rng, names, 2), {"coef": rng.randint(1, 9)}]} + left = [{"coef": rng.randint(1, 3), "powers": _term(rng, names, rng.randint(2, 3))["powers"]}] + right = [{"coef": rng.randint(2, 12), "powers": {v: 1}} for v in rng.sample(names, len(names))] + [const] + return {"kind": kind, "left": left, "right": right} + + +def _random_ranges(rng: random.Random, names: list[str]) -> dict[str, list[int]]: + ranges = {} + for v in names: + lo = rng.randint(1, 8) + ranges[v] = [lo, min(GRID - 1, lo + rng.randint(3, 9 if len(names) == 2 else 9))] + return ranges + + +def _falsify_ok(claim: dict, ranges: dict[str, list[int]], level: int, want_holds: bool) -> bool: + answer = _search(claim, ranges) + if (answer is None) != want_holds or _search(claim, ranges, python_range=True) == answer: + return False + if want_holds or level == 1: + return True + if _search(claim, ranges, b_major=True) == answer: + return False + lo, hi = ranges["a"] + return level == 2 or answer[0] - lo >= (hi - lo) * 2 / 3 # d3: the first counterexample sits late in a + + +def _falsify_build(level: int, rng: random.Random) -> Built: + names = ["n"] if level == 1 else ["a", "b"] + want_holds = level == 3 and rng.random() < 1 / 3 + while True: + claim = _random_claim(rng, names) + ranges = next((r for r in (_random_ranges(rng, names) for _ in range(12)) + if _falsify_ok(claim, r, level, want_holds)), None) + if ranges is not None: + break + bounds = " and ".join(f"{lo} <= {v} <= {hi}" for v, (lo, hi) in ranges.items()) + claim["text"] = f"for all integers {', '.join(names)} with {bounds}: {_claim_text(claim)}" + document = {"variables": names, "ranges": ranges, "claim": claim} + one = level == 1 + statement = "\n".join([ + "claim.json states a claim about integers over a search range and asks whether it holds there. Both range " + "bounds are inclusive.", + "Each expression is a list of terms; a term is coef times the product of each variable raised to its power " + '(a term with no powers is a constant). Claim kinds: "at_most" means left <= right; "prime" means expr is a ' + 'prime number (an integer of at least 2 whose only positive divisors are 1 and itself); "not_divisible" ' + 'means expr is not a multiple of divisor (0 is a multiple of everything); "coprime" means the greatest ' + "common divisor of left and right is 1 (taken on absolute values, so gcd(0, k) = |k|). The text field " + "restates the claim.", + "Find the smallest counterexample in the range: " + ( + "the smallest n for which the claim is false." if one else + "order points by a first and then by b, so (a, b) comes before (a', b') when a < a', or a = a' and " + "b < b'."), + 'Write answer.json as {"result": "counterexample", ' + ('"n": }' if one else '"a": , "b": }') + + ' with JSON integers. If the claim is true at every point of the range, write an object whose only key is ' + '"result", set to "holds".', + ]) + built = Built(files={"claim.json": json.dumps(document, indent=2) + "\n"}, statement=statement, + output="answer.json", reference=None) + built.reference = json.loads(_falsify_solve(built.files, level, None)) + return built + + +def _falsify_solve(files: dict[str, str], level: int, variant: str | None) -> str: + document = json.loads(files["claim.json"]) + claim, ranges, names = document["claim"], document["ranges"], document["variables"] + answer = _search(claim, ranges, b_major=variant == "first_found_not_smallest", + python_range=variant == "off_by_one_range") + if variant == "always_counterexample": # never says holds; applies only where the claim does hold + if _search(claim, ranges) is not None: + return json.dumps({"result": "n/a"}) + answer = tuple(lo for lo, _ in ranges.values()) + if variant == "first_found_not_smallest" and answer is None: + return json.dumps({"result": "n/a"}) + if answer is None: + return json.dumps({"result": "holds"}) + return json.dumps({"result": "counterexample", **dict(zip(names, answer))}) + + +def _falsify_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + if reference["result"] == "holds": + return [out.get("result") == "holds"] + return [out.get("result") == "counterexample"] + [_exact_int(out.get(k), v) + for k, v in reference.items() if k != "result"] + + +FAMILIES = ( + Family(name="linear", domain=DOMAIN, build=_linear_build, check=_linear_check, solve=_linear_solve, + traps={"float": (1, 2, 3), "unreduced": (1, 2, 3), "singular_missed": (3,)}), + Family(name="counting", domain=DOMAIN, build=_counting_build, check=_counting_check, solve=_counting_solve, + traps={"ignore_overlap": (2, 3), "drop_a_constraint": (1, 2, 3), "order_matters_twice": (2, 3)}), + Family(name="congruences", domain=DOMAIN, build=_congruences_build, check=_congruences_check, + solve=_congruences_solve, + traps={"assume_coprime": (2, 3), "not_least": (1, 2, 3), "inconsistent_missed": (3,)}), + Family(name="falsify", domain=DOMAIN, build=_falsify_build, check=_falsify_check, solve=_falsify_solve, + traps={"off_by_one_range": (1, 2, 3), "first_found_not_smallest": (2, 3), + "always_counterexample": (3,)}), +) diff --git a/components/qemedia/upstream/qe_arena/skills/media.py b/components/qemedia/upstream/qe_arena/skills/media.py new file mode 100644 index 0000000000000000000000000000000000000000..6a3b6446911a15257a1287e2cabdaa3f8b63875f --- /dev/null +++ b/components/qemedia/upstream/qe_arena/skills/media.py @@ -0,0 +1,363 @@ +"""media-content-production families for qe_skill.""" + +from __future__ import annotations + +import json +import random +import re +from datetime import date, timedelta +from fractions import Fraction + +from . import Built, Family +from ._common import load_object, rows, write_csv +from .subtitles import SUBTITLES, WORDS + +DOMAIN = "media-content-production" + + +# D2 timecode: per-clip frames and total runtime from an edit decision list. +NOMINAL = {"24": 24, "25": 25, "30": 30, "29.97": 30} # frames counted per timecode second +WRONG_FPS = {"24": "30", "25": "30", "30": "25"} +DF_TEN_MIN, DF_MIN = 17982, 1798 # 29.97 drop-frame: frames per 10 minutes and per dropped minute +TC = re.compile(r"^(\d{2}):(\d{2}):(\d{2})([:;])(\d{2})$") + + +def _tc_label(frame: int, fps: int, drop: bool) -> str: + if drop: # skip labels ;00 and ;01 at every minute not divisible by 10 + tens, rest = divmod(frame, DF_TEN_MIN) + frame += 18 * tens + (2 * ((rest - 2) // DF_MIN) if rest > 1 else 0) + seconds, ff = divmod(frame, fps) + minutes, ss = divmod(seconds, 60) + hh, mm = divmod(minutes, 60) + return f"{hh:02d}:{mm:02d}:{ss:02d}{';' if drop else ':'}{ff:02d}" + + +def _tc_frame(label: str, fps: int, drop: bool) -> int: + hh, mm, ss, _, ff = TC.match(label.strip()).groups() + total_minutes = int(hh) * 60 + int(mm) + frame = (total_minutes * 60 + int(ss)) * fps + int(ff) + return frame - 2 * (total_minutes - total_minutes // 10) if drop else frame + + +def _timecode_build(level: int, rng: random.Random) -> Built: + rate = {1: "25", 2: rng.choice(("30", "24")), 3: "29.97"}[level] + fps, drop = NOMINAL[rate], level == 3 + out_point = rng.choice(("exclusive", "inclusive")) + records = [] + for n, reel in enumerate(rng.sample(range(1, 90), rng.randint(4, 7))): + start = rng.randint(0, 3000 * fps) + length = rng.randint(20 * fps, 200 * fps) if drop else rng.randint(2 * fps, 90 * fps) + end = start + length - (out_point == "inclusive") + records.append([f"R{reel:02d}_C{n + 1:02d}", _tc_label(start, fps, drop), _tc_label(end, fps, drop)]) + job = {"fps": rate, "drop_frame": drop, "out_point": out_point} + files = {"edl.csv": write_csv(["clip", "source_in", "source_out"], records), + "job.json": json.dumps(job, indent=2) + "\n"} + notation = "HH:MM:SS;FF" if drop else "HH:MM:SS:FF" + lines = [ + "edl.csv is an edit decision list: one row per clip with its source in and out points as SMPTE timecode. " + "job.json gives the frame rate (fps), whether the timecode is drop-frame, and out_point: \"exclusive\" means " + "source_out is the first frame after the clip, \"inclusive\" means it is the clip's last frame.", + "Compute each clip's duration in frames, then the total runtime of all clips in frames, and write the total " + f"as a timecode at the same rate in {notation} notation, counting from {_tc_label(0, fps, drop)}.", + ] + if drop: + lines.insert(1, "The timecode is 29.97 fps drop-frame (HH:MM:SS;FF): frame labels 00 and 01 are skipped at " + "the start of every minute except minutes 00, 10, 20, 30, 40 and 50. No frames are dropped, " + "only labels.") + lines.append('Write runtime.json as {"clips": {"": , ...}, "total_frames": , ' + '"total_timecode": ""} with integer frame counts.') + built = Built(files=files, statement="\n".join(lines), output="runtime.json", reference=None) + built.reference = json.loads(_timecode_solve(files, level, None)) + return built + + +def _timecode_solve(files: dict[str, str], level: int, variant: str | None) -> str: + job = json.loads(files["job.json"]) + rate, drop = job["fps"], job["drop_frame"] + if variant == "wrong_fps": + if rate not in WRONG_FPS: + return "{}" + rate = WRONG_FPS[rate] + if variant == "dropframe_as_nondrop": + if not drop: + return "{}" + drop = False + fps = NOMINAL[rate] + inclusive = (job["out_point"] == "inclusive") != (variant == "inclusive_out_point") # the other convention + clips = {r["clip"]: _tc_frame(r["source_out"], fps, drop) - _tc_frame(r["source_in"], fps, drop) + inclusive + for r in rows(files["edl.csv"])} + total = sum(clips.values()) + if variant == "total_from_seconds_rounding": + real = Fraction(30000, 1001) if drop else fps + total = round(sum(round(f / real) for f in clips.values()) * real) + label_drop = drop + if variant == "dropframe_total_as_nondrop": + if not drop: + return "{}" + label_drop = False + return json.dumps({"clips": clips, "total_frames": total, "total_timecode": _tc_label(total, fps, label_drop)}) + + +def _timecode_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + clips = out.get("clips") + results = [isinstance(clips, dict) and set(clips) == set(reference["clips"])] + if not results[0]: + return results + results += [type(clips[k]) is int and clips[k] == v for k, v in reference["clips"].items()] + return results + [type(out.get("total_frames")) is int and out["total_frames"] == reference["total_frames"], + out.get("total_timecode") == reference["total_timecode"]] + + +# D3 catalogue: normalise a media library, dedupe it and build a capped playlist. +MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") +KINDS = ("film", "episode", "trailer", "music", "short") + + +def _iso_duration(seconds: int) -> str: + h, rest = divmod(seconds, 3600) + m, s = divmod(rest, 60) + text = "".join(f"{v}{u}" for v, u in ((h, "H"), (m, "M"), (s, "S")) if v) + return "PT" + (text or "0S") + + +def _date_text(day: date, rng: random.Random) -> str: + style = rng.randrange(4) + if style == 0: + return day.isoformat() + if style == 1: + return f"{day.day:02d}.{day.month:02d}.{day.year}" + if style == 2: + return f"{day.year}/{day.month:02d}/{day.day:02d}" + return f"{MONTHS[day.month - 1]} {day.day}, {day.year}" + + +def _parse_date(text: str) -> date: + text = text.strip() + if m := re.fullmatch(r"(\d{4})[-/](\d{2})[-/](\d{2})", text): + return date(int(m[1]), int(m[2]), int(m[3])) + if m := re.fullmatch(r"(\d{2})\.(\d{2})\.(\d{4})", text): + return date(int(m[3]), int(m[2]), int(m[1])) + m = re.fullmatch(r"([A-Z][a-z]{2}) (\d{1,2}), (\d{4})", text) + return date(int(m[3]), MONTHS.index(m[1]) + 1, int(m[2])) + + +def _duration_text(seconds: int, style: int) -> str: + if style == 0: + return f"{seconds // 3600}:{seconds % 3600 // 60:02d}:{seconds % 60:02d}" + if style == 1: + return f"{seconds // 60:02d}:{seconds % 60:02d}" + return str(seconds) + + +def _parse_duration(text: str, misparse: bool = False) -> int: + parts = [int(p) for p in text.strip().split(":")] + if len(parts) == 2 and misparse: # MM:SS read as H:MM + return parts[0] * 3600 + parts[1] * 60 + return sum(v * 60 ** i for i, v in enumerate(reversed(parts))) + + +def _messy_title(rng: random.Random) -> str: + words = [rng.choice(WORDS) for _ in range(rng.randint(2, 5))] + words[0] = words[0].capitalize() + inner = "".join(w + " " * rng.choice((1, 1, 2, 3)) for w in words[:-1]) + return " " * rng.randint(0, 2) + inner + words[-1] + " " * rng.randint(0, 2) + + +def _catalogue_build(level: int, rng: random.Random) -> Built: + count = {1: 6, 2: 8, 3: 10}[level] + ids = [f"M{n:04d}" for n in rng.sample(range(1, 10000), count)] + pool = [date(2023, 1, 1) + timedelta(days=rng.randint(0, 900)) for _ in range(4 if level == 3 else 20)] + styles = [1, 0, 2] + [rng.randrange(3) for _ in range(count - 3)] # every duration form at least once + rng.shuffle(styles) + records = [] + for item, style in zip(ids, styles): + seconds = rng.randint(3700, 9000) if style == 0 else rng.randint(30, 3500) + records.append([item, _messy_title(rng), _duration_text(seconds, style), rng.choice(KINDS), + rng.choice(pool)]) + rng.shuffle(records) + unique = list(range(count)) + if level == 3: # two short items share the newest date, listed against id order, so the tie-break shows + a, b = sorted(rng.sample([k for k in unique if records[k][2].count(":") < 2], 2)) + if records[a][0] < records[b][0]: + records[a][0], records[b][0] = records[b][0], records[a][0] + records[a][4] = records[b][4] = max(pool) + timedelta(days=rng.randint(1, 30)) + unique = [k for k in unique if k not in (a, b)] + if level >= 2: # duplicate ids with a later, revised row; the first group lists the older row first + for n, k in enumerate(sorted(rng.sample(unique, 2), reverse=True)): + orig = records[k] + later = orig[4] + timedelta(days=rng.randint(1, 60)) + seconds = _parse_duration(orig[2]) + rng.randint(5, 300) + dup = [orig[0], _messy_title(rng), _duration_text(seconds, rng.randrange(3)), orig[3], later] + records.insert(k + 1 if n == 0 else k, dup) + rows_out = [r[:4] + [_date_text(r[4], rng)] for r in records] + files = {"library.csv": write_csv(["id", "title", "duration", "type", "added"], rows_out)} + lines = [ + "library.csv lists media items (id, title, duration, type, added). Normalise every row:", + "- title: remove leading and trailing whitespace and replace every run of internal whitespace with one " + "space; keep the letter case.", + "- duration: given as H:MM:SS (hours, minutes, seconds), MM:SS (minutes, seconds) or a plain number of " + "seconds. Write it as an ISO 8601 duration PT#H#M#S, leaving out every zero component and using no leading " + 'zeros (3725 seconds is "PT1H2M5S", 300 seconds is "PT5M").', + "- added: given as YYYY-MM-DD, DD.MM.YYYY, YYYY/MM/DD or 'Mon D, YYYY' (English three-letter month). " + "Write it as YYYY-MM-DD.", + "- type: copy unchanged.", + ] + if level >= 2: + lines.append("Some ids appear more than once. For each id keep only the row with the latest added date " + "(rows sharing an id never share a date).") + out = '{"items": [{"id": ..., "title": ..., "duration": ..., "type": ..., "added": ...}, ...]}' + if level == 3: + cap = sum(_parse_duration(r[2]) for r in rows_out) * rng.randint(35, 55) // 100 + files["job.json"] = json.dumps({"cap_seconds": cap}, indent=2) + "\n" + lines.append("Then build a playlist from the deduplicated, normalised items, using cap_seconds from " + "job.json: order the items by added date, newest first, breaking ties by id ascending; walk " + "that order and add each item whose duration still keeps the running total at or under " + "cap_seconds, skipping any item that does not fit and continuing with the next.") + out = out[:-1] + ', "playlist": {"ids": [], "total_duration": ""}}' + lines.append(f"Write catalogue.json as {out}, with items sorted by id ascending and every item value a string.") + built = Built(files=files, statement="\n".join(lines), output="catalogue.json", reference=None) + built.reference = json.loads(_catalogue_solve(files, level, None)) + return built + + +def _catalogue_solve(files: dict[str, str], level: int, variant: str | None) -> str: + if variant in ("cap_exceeded", "tie_break_ignored") and level < 3 or variant == "dedupe_keep_first" and level < 2: + return "{}" + parsed = [dict(r, seconds=_parse_duration(r["duration"], variant == "duration_seconds_misparse"), + day=_parse_date(r["added"]), pos=n) for n, r in enumerate(rows(files["library.csv"]))] + kept: dict[str, dict] = {} + for r in parsed: + if r["id"] not in kept or (variant != "dedupe_keep_first" and r["day"] > kept[r["id"]]["day"]): + kept[r["id"]] = r + items = [kept[k] for k in sorted(kept)] + out: dict = {"items": [{"id": r["id"], "title": " ".join(r["title"].split()), + "duration": _iso_duration(r["seconds"]), "type": r["type"], + "added": r["day"].isoformat()} for r in items]} + if level == 3: + cap = json.loads(files["job.json"])["cap_seconds"] + tie = (lambda r: r["pos"]) if variant == "tie_break_ignored" else (lambda r: r["id"]) + ranked = sorted(items, key=lambda r: (-r["day"].toordinal(), tie(r))) + chosen, total = [], 0 + for r in ranked: + if total + r["seconds"] <= cap: + chosen.append(r["id"]) + total += r["seconds"] + elif variant == "cap_exceeded": # take the item that crosses the cap, then stop + chosen.append(r["id"]) + total += r["seconds"] + break + out["playlist"] = {"ids": chosen, "total_duration": _iso_duration(total)} + return json.dumps(out) + + +def _catalogue_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + items = out.get("items") + results = [isinstance(items, list) and len(items) == len(reference["items"]), + set(out) == set(reference)] + if not all(results): + return results + results += [item == ref for item, ref in zip(items, reference["items"])] + if "playlist" in reference: + results.append(out["playlist"] == reference["playlist"]) + return results + + +# D4 assets: centred crop rectangles and output sizes for platform targets. +TARGETS = (("square", 1, 1), ("portrait", 4, 5), ("story", 9, 16), ("landscape", 16, 9), ("classic", 4, 3), + ("cinema", 21, 9), ("tall", 2, 3)) +OUT_HEIGHTS = (720, 1080, 1280, 1350, 1440, 1920) +ASSET_HEADER = ["target", "crop_x", "crop_y", "crop_w", "crop_h", "out_w", "out_h"] + + +def _assets_build(level: int, rng: random.Random) -> Built: + width, height = rng.randint(1800, 6200), rng.randint(1200, 4200) + chosen = rng.sample(TARGETS, {1: 1, 2: rng.randint(3, 4), 3: rng.randint(3, 4)}[level]) + job: dict = {"source": {"width": width, "height": height}, + "targets": [{"name": n, "aspect": f"{aw}:{ah}", "out_height": rng.choice(OUT_HEIGHTS)} + for n, aw, ah in chosen]} + if level == 3: + job["safe_margin_pct"] = rng.randint(3, 9) + files = {"job.json": json.dumps(job, indent=2) + "\n"} + area, w_name, h_name = "source", "W", "H" + lines = ["job.json gives the source image width W and height H in pixels, and platform targets, each with an " + "aspect ratio aw:ah and an output height. For every target compute a crop rectangle and an output size."] + if level == 3: + area, w_name, h_name = "safe area", "SW", "SH" + lines.append("The crop must lie inside the safe area: the source minus a margin of mx = floor(W x " + "safe_margin_pct / 100) pixels on the left and on the right, and my = floor(H x " + "safe_margin_pct / 100) on the top and on the bottom. Its size is SW = W - 2mx by " + "SH = H - 2my.") + lines += [ + f"The crop is the largest rectangle with the target aspect that fits the {area}, centred in it. If " + f"{w_name} x ah > {h_name} x aw, crop_h = {h_name} and crop_w = floor({h_name} x aw / ah); otherwise " + f"crop_w = {w_name} and crop_h = floor({w_name} x ah / aw)." + + (" Then round crop_w and crop_h down to the nearest even number." if level == 3 else ""), + f"crop_x = {'mx + ' if level == 3 else ''}floor(({w_name} - crop_w) / 2) and " + f"crop_y = {'my + ' if level == 3 else ''}floor(({h_name} - crop_h) / 2), measured from the source's " + "top-left corner.", + "out_h is the target's out_height and out_w = floor(out_h x aw / ah)" + + (", rounded down to the nearest even number." if level == 3 else "."), + "Write crops.csv with the header " + ",".join(ASSET_HEADER) + " and one row per target, in the order of " + "job.json, every value but target an integer.", + ] + built = Built(files=files, statement="\n".join(lines), output="crops.csv", reference=None) + built.reference = rows(_assets_solve(files, level, None)) + return built + + +def _assets_solve(files: dict[str, str], level: int, variant: str | None) -> str: + if variant in ("odd_dimensions", "ignore_safe_area") and level < 3: + return "target\n" + job = json.loads(files["job.json"]) + width, height = job["source"]["width"], job["source"]["height"] + pct = 0 if variant == "ignore_safe_area" else job.get("safe_margin_pct", 0) + mx, my = width * pct // 100, height * pct // 100 + sw, sh = width - 2 * mx, height - 2 * my + + def size(v: Fraction) -> int: + if level < 3: + return v.numerator // v.denominator + return round(v) if variant == "odd_dimensions" else v.numerator // v.denominator // 2 * 2 + + records = [] + for target in job["targets"]: + aw, ah = (int(v) for v in target["aspect"].split(":")) + if variant == "distort_aspect": + x, y, cw, ch = 0, 0, width, height + else: + wide = sw * ah > sh * aw + cw, ch = (Fraction(sh * aw, ah), Fraction(sh)) if wide else (Fraction(sw), Fraction(sw * ah, aw)) + cw, ch = size(cw), size(ch) + x, y = (mx, my) if variant == "crop_not_centered" else (mx + (sw - cw) // 2, my + (sh - ch) // 2) + out_h = target["out_height"] + out_w = size(Fraction(out_h * aw, ah)) + records.append([target["name"], x, y, cw, ch, out_w, out_h]) + return write_csv(ASSET_HEADER, records) + + +def _assets_check(reference: list, text: str) -> list[bool]: + got = rows(text) + results = [len(got) == len(reference) and all(list(r) == ASSET_HEADER for r in got)] + if not results[0]: + return results + for row, ref in zip(got, reference): + results.append(row["target"] == ref["target"]) + results += [re.fullmatch(r"\d+", row[k] or "") is not None and int(row[k]) == int(ref[k]) + for k in ASSET_HEADER[1:]] + return results + + +FAMILIES = ( + SUBTITLES, + Family(name="timecode", domain=DOMAIN, build=_timecode_build, check=_timecode_check, solve=_timecode_solve, + traps={"wrong_fps": (1, 2), "inclusive_out_point": (1, 2, 3), "dropframe_as_nondrop": (3,), + "dropframe_total_as_nondrop": (3,), "total_from_seconds_rounding": (1, 2, 3)}), + Family(name="catalogue", domain=DOMAIN, build=_catalogue_build, check=_catalogue_check, solve=_catalogue_solve, + traps={"duration_seconds_misparse": (1, 2, 3), "dedupe_keep_first": (2, 3), "cap_exceeded": (3,), + "tie_break_ignored": (3,)}), + Family(name="assets", domain=DOMAIN, build=_assets_build, check=_assets_check, solve=_assets_solve, + traps={"distort_aspect": (1, 2, 3), "crop_not_centered": (1, 2, 3), "odd_dimensions": (3,), + "ignore_safe_area": (3,)}), +) diff --git a/components/qemedia/upstream/qe_arena/skills/science.py b/components/qemedia/upstream/qe_arena/skills/science.py new file mode 100644 index 0000000000000000000000000000000000000000..1430558cf2c375fd3744dd89ff14e922e434c932 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/skills/science.py @@ -0,0 +1,420 @@ +"""natural-science families for qe_skill.""" + +from __future__ import annotations + +import json +import math +import random +from statistics import fmean +from typing import Any + +from . import Built, Family +from ._common import close, is_number, load_object, rows, write_csv + +DOMAIN = "natural-science" + +# S1 units: per-sample mean concentration from a QC'd measurement sheet. +TO_MG_PER_L = {"mg/L": 1.0, "ug/L": 0.001, "ng/mL": 0.001, "g/L": 1000.0, "mg/mL": 1000.0} +TARGETS = ("mg/L", "ug/L") +ANALYTES = ("nitrate", "phosphate", "sulfate", "ammonium", "chloride", "fluoride") +TOLERANCE = 0.0006 # the statement asks for 3 decimals + + +def _units_build(level: int, rng: random.Random) -> Built: + target = rng.choice(TARGETS) + analytes = rng.sample(ANALYTES, 2 if level == 3 else 1) + analyte = analytes[0] + samples = [f"S{n:02d}" for n in rng.sample(range(1, 60), {1: 4, 2: 5, 3: 6}[level])] + header = ["sample_id", "analyte", "value", "unit", "qc"] + (["lod"] if level == 3 else []) + records: list[list[Any]] = [] + for sample in samples: + for name in analytes: + true = rng.uniform(0.2, 40.0) + count = rng.randint(3, 5) + fails = rng.sample(range(count), 1) + nd = rng.sample([i for i in range(count) if i not in fails], 1) if level == 3 and name == analyte else [] + for i in range(count): + unit = target if level == 1 else rng.choice(list(TO_MG_PER_L)) + factor = TO_MG_PER_L[unit] + if i in nd: + lod = true * rng.uniform(0.2, 0.6) / factor + records.append([sample, name, "ND", unit, "ok", f"{lod:.4g}"]) + continue + value = true * rng.gauss(1.0, 0.05) * (rng.choice((0.2, 4.0)) if i in fails else 1.0) / factor + lod = true * 0.05 / factor + records.append([sample, name, f"{value:.6g}", unit, "fail" if i in fails else "ok"] + + ([f"{lod:.4g}"] if level == 3 else [])) + rng.shuffle(records) + files = {"measurements.csv": write_csv(header, records), + "request.json": json.dumps({"analyte": analyte, "unit": target}, indent=2) + "\n"} + rules = ["Use only rows whose qc is ok."] + if level >= 2: + rules.append("Values come in several units; convert every value to the requested unit before averaging " + "(1 g/L = 1000 mg/L = 1 mg/mL; 1 mg/L = 1000 ug/L; 1 ng/mL = 1 ug/L).") + if level == 3: + rules.append("The sheet holds more than one analyte; report only the requested one. A value of ND means not " + "detected: count it as half of that row's lod (lod is in the row's own unit).") + statement = "\n".join([ + "A water lab sent measurements.csv and request.json. Report the mean concentration of the requested " + "analyte for every sample, in the requested unit.", + *rules, + 'Write result.json as {"unit": "", "means": {"": , ...}} with one ' + "entry per sample, each mean rounded to 3 decimal places.", + ]) + built = Built(files=files, statement=statement, output="result.json", reference=None) + built.reference = json.loads(_units_solve(files, level, None)) + return built + + +def _units_solve(files: dict[str, str], level: int, variant: str | None) -> str: + request = json.loads(files["request.json"]) + target = request["unit"] + values: dict[str, list[float]] = {} + for row in rows(files["measurements.csv"]): + if row["analyte"] != request["analyte"] and variant != "all_analytes": + continue + if row["qc"] != "ok" and variant != "keep_flagged": + continue + factor = 1.0 if variant == "no_conversion" else TO_MG_PER_L[row["unit"]] / TO_MG_PER_L[target] + if row["value"] == "ND": + if variant == "nd_dropped": + continue + raw = 0.0 if variant == "nd_as_zero" else float(row["lod"]) / 2 + else: + raw = float(row["value"]) + values.setdefault(row["sample_id"], []).append(raw * factor) + means = {sample: round(fmean(v), 3) for sample, v in sorted(values.items())} + return json.dumps({"unit": target, "means": means}, indent=2) + "\n" + + +def _units_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + means = out.get("means") + results = [out.get("unit") == reference["unit"], + isinstance(means, dict) and set(means) == set(reference["means"])] + if not all(results): + return results + tol = lambda ref: TOLERANCE + 1e-9 * abs(ref) # noqa: E731 + return results + [close(means[s], ref, tol(ref)) for s, ref in reference["means"].items()] + + + +# Shared numeric helpers for the families below. +def _fit(xs: list[float], ys: list[float], origin: bool = False) -> tuple[float, float, float]: + """Ordinary least squares y = slope*x + intercept: (slope, intercept, 1 - SS_res/SS_tot).""" + mx, my = fmean(xs), fmean(ys) + if origin: + slope, intercept = sum(x * y for x, y in zip(xs, ys)) / sum(x * x for x in xs), 0.0 + else: + slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs) + intercept = my - slope * mx + ss_res = sum((y - slope * x - intercept) ** 2 for x, y in zip(xs, ys)) + return slope, intercept, 1 - ss_res / sum((y - my) ** 2 for y in ys) + + +def _sig(value: float, digits: int) -> float: + return float(f"{value:.{digits - 1}e}") + + +def _ulp(reference: float, digits: int) -> float: + """One unit in the last of ``digits`` significant figures of the reference.""" + return 10 ** (math.floor(math.log10(abs(reference))) - digits + 1) if reference else 10 ** -digits + + +def _cell(text: str | None) -> float | None: + try: + return float(text) + except (TypeError, ValueError): + return None + + +def _relative(value: Any, reference: float, rel: float) -> bool: + return close(value, reference, rel * abs(reference) + 1e-12) + + +# S2 calibration: a linear calibration curve and the unknowns read off it. +INVERTED_MARGIN = 2e-4 # 20x the slope tolerance: regressing the wrong way round must miss by at least this + + +def _calibration_build(level: int, rng: random.Random) -> Built: + """A near-perfect fit makes the inverted-axes slope differ from the right one by only 1 - r^2; redraw those.""" + while True: + built = _calibration_once(level, rng) + wrong = json.loads(_calibration_solve(built.files, level, "inverted_axes")) + if abs(wrong["slope"] - built.reference["slope"]) >= INVERTED_MARGIN * abs(built.reference["slope"]): + return built + + +def _calibration_once(level: int, rng: random.Random) -> Built: + top = rng.choice((5, 10, 20, 25, 50)) + count = rng.randint(6, 8) + concs = [round(top * k / (count - 1), 3) for k in range(count)] + slope = rng.uniform(0.6, 1.0) / top + intercept = rng.uniform(0.015, 0.05) + absorb = [slope * c + intercept + rng.gauss(0, 0.004) for c in concs] + if level == 3: + absorb[rng.randrange(count)] += rng.choice((1, -1)) * rng.uniform(0.07, 0.12) + blank = rng.uniform(0.03, 0.08) if level >= 2 else 0.0 + samples = [[f"U{n:02d}", f"{slope * rng.uniform(0.1, 0.9) * top + intercept + blank + rng.gauss(0, 0.004):.4f}"] + for n in rng.sample(range(1, 40), rng.randint(3, 5))] + if level >= 2: + samples += [["BLANK", f"{blank + rng.gauss(0, 0.002):.4f}"] for _ in range(3)] + rng.shuffle(samples) + files = {"standards.csv": write_csv(["concentration_mg_L", "absorbance"], + [[c, f"{a:.4f}"] for c, a in zip(concs, absorb)]), + "samples.csv": write_csv(["sample_id", "absorbance"], samples)} + rules = ["Fit absorbance = slope * concentration + intercept to the standards by ordinary least squares, then " + "convert each sample's absorbance to a concentration with that line."] + if level >= 2: + rules.append("The standards are already blank-corrected; the sample readings are not. The rows with " + "sample_id BLANK are reagent blank readings: subtract their mean from every other sample reading " + "before converting it, and do not report the blanks.") + if level == 3: + files["job.json"] = json.dumps({"outlier_threshold": 0.03}, indent=2) + "\n" + rules.append("After the first fit, find the one standard with the largest absolute residual (its absorbance " + "minus the fitted absorbance). If that residual's magnitude exceeds outlier_threshold in job.json, " + "drop that standard and fit again; report the second fit. Drop at most one standard.") + statement = "\n".join([ + "A spectrophotometry run produced standards.csv (concentration_mg_L, absorbance) and samples.csv " + "(sample_id, absorbance).", + *rules, + 'Write calibration.json as {"slope": , "intercept": , "r_squared": , ' + '"concentrations": {"": , ...}}. Give slope and intercept to 6 significant figures, ' + "r_squared (1 - SS_res/SS_tot over the standards in the reported fit) to 6 decimal places, and each " + "concentration in mg/L to 3 decimal places.", + ]) + built = Built(files=files, statement=statement, output="calibration.json", reference=None) + built.reference = json.loads(_calibration_solve(files, level, None)) + return built + + +def _calibration_fit(xs: list[float], ys: list[float], variant: str | None) -> tuple[float, float, float]: + if variant == "inverted_axes": # concentration regressed on absorbance, then the line turned around + a, b, r2 = _fit(ys, xs) + return 1 / a, -b / a, r2 + return _fit(xs, ys, origin=variant == "through_origin") + + +def _calibration_solve(files: dict[str, str], level: int, variant: str | None) -> str: + std = [(float(r["concentration_mg_L"]), float(r["absorbance"])) for r in rows(files["standards.csv"])] + slope, intercept, r2 = _calibration_fit([c for c, _ in std], [a for _, a in std], variant) + if level == 3 and variant != "outlier_kept": + threshold = json.loads(files["job.json"])["outlier_threshold"] + worst = max(range(len(std)), key=lambda i: abs(std[i][1] - slope * std[i][0] - intercept)) + if abs(std[worst][1] - slope * std[worst][0] - intercept) > threshold: + kept = std[:worst] + std[worst + 1:] + slope, intercept, r2 = _calibration_fit([c for c, _ in kept], [a for _, a in kept], variant) + readings = [(r["sample_id"], float(r["absorbance"])) for r in rows(files["samples.csv"])] + blanks = [a for sid, a in readings if sid == "BLANK"] + blank = fmean(blanks) if blanks and variant != "no_blank" else 0.0 + concentrations = {sid: round((a - blank - intercept) / slope, 3) for sid, a in sorted(readings) if sid != "BLANK"} + return json.dumps({"slope": _sig(slope, 6), "intercept": _sig(intercept, 6), "r_squared": round(r2, 6), + "concentrations": concentrations}, indent=2) + "\n" + + +def _calibration_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + concentrations = out.get("concentrations") + results = [_relative(out.get("slope"), reference["slope"], 1e-5), + _relative(out.get("intercept"), reference["intercept"], 1e-5), + close(out.get("r_squared"), reference["r_squared"], 6e-7), + isinstance(concentrations, dict) and set(concentrations) == set(reference["concentrations"])] + if not all(results): + return results + return results + [close(concentrations[s], ref, 0.0006 + 1e-9 * abs(ref)) + for s, ref in reference["concentrations"].items()] + + +# S3 decay: half-life from a count-rate series, with background and dead-time corrections. +def _decay_build(level: int, rng: random.Random) -> Built: + half = rng.uniform(3.0, 40.0) + count = rng.randint(10, 14) + step = max(0.5, round(half * rng.uniform(3.0, 4.0) / (count - 1) * 2) / 2) + times = [k * step for k in range(count)] + start = rng.uniform(2000.0, 8000.0) + signal = [start * math.exp(-math.log(2) / half * t) * rng.gauss(1.0, 0.004) for t in times] + background = round(signal[-1] * rng.uniform(0.3, 0.8), 2) if level >= 2 else 0.0 + dead = float(f"{rng.uniform(0.1, 0.2) / (start + background):.3g}") if level == 3 else 0.0 + observed = [(s + background) / (1 + (s + background) * dead) for s in signal] + files = {"counts.csv": write_csv(["t_min", "rate_cps"], [[f"{t:g}", f"{m:.2f}"] for t, m in zip(times, observed)])} + rules = [] + if level == 2: + files["job.json"] = json.dumps({"background_cps": background}, indent=2) + "\n" + rules.append("Every reading includes the detector background, background_cps in job.json: subtract it from " + "each rate first.") + if level == 3: + files["job.json"] = json.dumps({"background_cps": background, "dead_time_s": dead}, indent=2) + "\n" + rules.append("The readings are not corrected for detector dead time or background (job.json). First correct " + "each observed rate m for dead time (non-paralysable): m / (1 - m * dead_time_s). Then subtract " + "background_cps.") + statement = "\n".join([ + "counts.csv holds the observed count rate (rate_cps, counts per second) of a radioactive sample at times " + "t_min (minutes).", + *rules, + "Fit a straight line to the natural log of the net rate against time by ordinary least squares, every point " + "weighted equally; the decay constant is minus the slope, and the half-life is ln(2) divided by it.", + 'Write decay.json as {"half_life_min": , "decay_constant_per_min": }, each to 5 ' + "significant figures. Values within 1% of the expected ones are accepted.", + ]) + built = Built(files=files, statement=statement, output="decay.json", reference=None) + built.reference = json.loads(_decay_solve(files, level, None)) + return built + + +def _decay_solve(files: dict[str, str], level: int, variant: str | None) -> str: + job = json.loads(files.get("job.json", "{}")) + times, net = [], [] + for row in rows(files["counts.csv"]): + m = float(row["rate_cps"]) + if level == 3 and variant != "no_dead_time": + m = m / (1 - m * job["dead_time_s"]) + if level >= 2 and variant != "no_background": + m -= job["background_cps"] + times.append(float(row["t_min"])) + net.append(m) + if variant == "linear_fit_raw": # a straight line through the rates, read off where it halves + slope, intercept, _ = _fit(times, net) + half = (intercept / 2) / -slope + rate = math.log(2) / half + else: + logs = [math.log10(v) if variant == "log10_instead_of_ln" else math.log(v) for v in net] + rate = -_fit(times, logs)[0] + half = math.log(2) / rate + return json.dumps({"half_life_min": _sig(half, 5), "decay_constant_per_min": _sig(rate, 5)}, indent=2) + "\n" + + +def _decay_check(reference: dict, text: str) -> list[bool]: + out = load_object(text) + return [_relative(out.get(key), ref, 0.01) for key, ref in reference.items()] + + +# S4 dilution: a pipetting plan by C1V1 = C2V2, serial chains, and a minimum transfer volume. +VOLUMES_UL = (200, 500, 1000, 1500, 2000, 5000) +FACTORS = (2, 2.5, 3, 4, 6, 7, 8, 12, 15) +BIG_FACTORS = (450, 750, 1600, 2500, 6000) # never an exact min_transfer_uL boundary + + +def _dilution_build(level: int, rng: random.Random) -> Built: + if level == 1: + stocks = {f"ST{n}": rng.choice((10, 25, 50, 100, 250, 500)) for n in rng.sample(range(1, 10), 2)} + targets = [] + for n in rng.sample(range(1, 50), rng.randint(4, 6)): + stock = rng.choice(sorted(stocks)) + targets.append([f"T{n:02d}", stock, f"{_sig(stocks[stock] * rng.uniform(0.01, 0.3), 3):g}", + rng.choice(VOLUMES_UL)]) + files = {"stocks.csv": write_csv(["stock_id", "concentration_mM"], sorted(stocks.items())), + "targets.csv": write_csv(["target_id", "stock_id", "target_mM", "final_uL"], targets)} + statement = "\n".join([ + "stocks.csv lists stock solutions (stock_id, concentration_mM) and targets.csv lists solutions to prepare " + "(target_id, stock_id, target_mM, final_uL). Each target is made by diluting its stock with diluent to " + "the final volume (C1 * V1 = C2 * V2).", + "Write plan.csv with the header target_id,stock_uL,diluent_uL and one row per target. Round stock_uL to " + "1 decimal place; diluent_uL is final_uL minus the rounded stock_uL.", + ]) + built = Built(files=files, statement=statement, output="plan.csv", reference=None) + built.reference = _dilution_parse(_dilution_solve(files, 1, None)) + return built + steps = [] + for n in range(rng.randint(4, 6) if level == 3 else rng.randint(5, 7)): + steps.append({"tube": f"D{n + 1}", "dilution_factor": rng.choice(FACTORS), "final_uL": rng.choice(VOLUMES_UL[:4])}) + job: dict[str, Any] = {"stock_mM": float(f"{rng.uniform(5, 500):.4g}"), "steps": steps} + rules = ["Rows follow the order of steps. Compute every concentration from the unrounded concentration of its " + "source; round only the values you write."] + if level == 3: + steps[rng.randrange(len(steps))]["dilution_factor"] = rng.choice(BIG_FACTORS) + job.update(min_transfer_uL=5.0, intermediate_factor=10, intermediate_uL=500) + rules.append("No transfer may be below min_transfer_uL. When a tube's transfer would be below it, first " + "make an intermediate tube named -I1 from that tube's source, diluted intermediate_factor-" + "fold to intermediate_uL, and make the tube from the intermediate with the remaining factor " + "(dilution_factor / intermediate_factor). If the transfer is still below the minimum, insert " + "-I2 made from -I1 the same way, dividing the remaining factor by " + "intermediate_factor again, and so on. Intermediates get their own rows, just before their " + "tube; the next tube in steps is still made from the previous tube, never from an intermediate.") + files = {"serial.json": json.dumps(job, indent=2) + "\n"} + statement = "\n".join([ + "serial.json describes a serial dilution: a stock at stock_mM and a list of steps. The first tube is made " + "from the stock and every later tube from the tube before it: transfer final_uL / dilution_factor of the " + "source and add diluent to final_uL.", + *rules, + "Write plan.csv with the header tube,source,transfer_uL,diluent_uL,concentration_mM and one row per tube " + "(source is stock or a tube name). Round transfer_uL to 1 decimal place; diluent_uL is final_uL minus the " + "rounded transfer_uL; give concentration_mM to 4 significant figures.", + ]) + built = Built(files=files, statement=statement, output="plan.csv", reference=None) + built.reference = _dilution_parse(_dilution_solve(files, level, None)) + return built + + +def _dilution_solve(files: dict[str, str], level: int, variant: str | None) -> str: + def transfer(final: float, factor: float) -> float: + return round(final * factor if variant == "inverted_c1v1" else final / factor, 1) + + if level == 1: + stocks = {r["stock_id"]: float(r["concentration_mM"]) for r in rows(files["stocks.csv"])} + records = [] + for r in rows(files["targets.csv"]): + final = float(r["final_uL"]) + stock = transfer(final, stocks[r["stock_id"]] / float(r["target_mM"])) + records.append([r["target_id"], f"{stock:.1f}", f"{final - stock:.1f}"]) + return write_csv(["target_id", "stock_uL", "diluent_uL"], records) + job = json.loads(files["serial.json"]) + records: list[list[Any]] = [] + carry = job["stock_mM"] + source = "stock" + + def make(tube: str, src: str, conc: float, factor: float, final: float) -> float: + conc = conc / factor + if variant == "round_each_step": + conc = _sig(conc, 4) + amount = transfer(final, factor) + records.append([tube, src, f"{amount:.1f}", f"{final - amount:.1f}", f"{_sig(conc, 4):g}"]) + return conc + + for step in job["steps"]: + factor, final, conc, src = step["dilution_factor"], step["final_uL"], carry, source + k = 0 + while level == 3 and variant != "ignore_min_volume" and final / factor < job["min_transfer_uL"]: + k += 1 + conc = make(f"{step['tube']}-I{k}", src, conc, job["intermediate_factor"], job["intermediate_uL"]) + src, factor = f"{step['tube']}-I{k}", factor / job["intermediate_factor"] + carry, source = make(step["tube"], src, conc, factor, final), step["tube"] + return write_csv(["tube", "source", "transfer_uL", "diluent_uL", "concentration_mM"], records) + + +def _dilution_parse(text: str) -> list[dict[str, Any]]: + return [{key: (value if key in ("target_id", "tube", "source") else _cell(value)) for key, value in row.items()} + for row in rows(text)] + + +def _dilution_check(reference: list[dict[str, Any]], text: str) -> list[bool]: + out = _dilution_parse(text) + ids = ("target_id",) if "target_id" in reference[0] else ("tube", "source") + key = lambda row: tuple(row.get(k) for k in ids) # noqa: E731 + if ids == ("target_id",): # targets may come in any order; serial rows must follow the steps + out = sorted(out, key=lambda row: str(row.get("target_id"))) + reference = sorted(reference, key=lambda row: row["target_id"]) + results = [len(out) == len(reference) and [key(r) for r in out] == [key(r) for r in reference]] + if not all(results): + return results + for got, ref in zip(out, reference): + for name, value in ref.items(): + if name in ids: + continue + tol = 0.6 * _ulp(value, 4) if name == "concentration_mM" else 0.06 + results.append(is_number(got.get(name)) and close(got[name], value, tol)) + return results + + +FAMILIES = ( + Family(name="units", domain=DOMAIN, build=_units_build, check=_units_check, solve=_units_solve, + traps={"keep_flagged": (1, 2, 3), "no_conversion": (2, 3), "nd_as_zero": (3,), "nd_dropped": (3,), + "all_analytes": (3,)}), + Family(name="calibration", domain=DOMAIN, build=_calibration_build, check=_calibration_check, + solve=_calibration_solve, + traps={"no_blank": (2, 3), "through_origin": (1, 2, 3), "outlier_kept": (3,), "inverted_axes": (1, 2, 3)}), + Family(name="decay", domain=DOMAIN, build=_decay_build, check=_decay_check, solve=_decay_solve, + traps={"linear_fit_raw": (1, 2, 3), "no_background": (2, 3), "no_dead_time": (3,), + "log10_instead_of_ln": (1, 2, 3)}), + Family(name="dilution", domain=DOMAIN, build=_dilution_build, check=_dilution_check, solve=_dilution_solve, + traps={"inverted_c1v1": (1, 2, 3), "round_each_step": (2, 3), "ignore_min_volume": (3,)}), +) diff --git a/components/qemedia/upstream/qe_arena/skills/subtitles.py b/components/qemedia/upstream/qe_arena/skills/subtitles.py new file mode 100644 index 0000000000000000000000000000000000000000..c2772f52396b8a8be9bdcfdbad8922cb5946dfe7 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/skills/subtitles.py @@ -0,0 +1,174 @@ +"""The media `subtitles` family: retime and repair an SRT file to an edit sheet. + +Recalibrated 2026-10-20: the first version was too easy at every level (14, 13 and 15 of 16 strict solves), so each +level now stacks more of the repair rules, and d3 adds a minimum display duration that interacts with the gap rule. +""" + +from __future__ import annotations + +import json +import random +import re +from fractions import Fraction + +from . import Built, Family + +DOMAIN = "media-content-production" +WORDS = ("the", "harbour", "light", "was", "never", "meant", "to", "go", "out", "tonight", "she", "said", "we", + "have", "until", "morning", "keep", "the", "engine", "running", "and", "do", "not", "look", "back", "at", + "storm", "coming", "over", "ridge", "listen", "carefully", "this", "is", "last", "train", "north") +TIME = re.compile(r"^(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})$") +TOLERANCE_MS = 1 + + +def _stamp(ms: int) -> str: + h, rest = divmod(ms, 3_600_000) + m, rest = divmod(rest, 60_000) + s, milli = divmod(rest, 1000) + return f"{h:02d}:{m:02d}:{s:02d},{milli:03d}" + + +def _render(cues: list) -> str: + return "\n".join(f"{idx}\n{_stamp(start)} --> {_stamp(end)}\n" + "\n".join(lines) + "\n" + for idx, start, end, lines in cues) + + +def _parse(text: str) -> list[tuple[int, int, int, list[str]]]: + blocks = re.split(r"\n\s*\n", text.replace("\r\n", "\n").strip()) + cues = [] + for block in blocks: + lines = [line.rstrip() for line in block.split("\n")] + match = TIME.match(lines[1].strip()) + g = [int(v) for v in match.groups()] + start = ((g[0] * 60 + g[1]) * 60 + g[2]) * 1000 + g[3] + end = ((g[4] * 60 + g[5]) * 60 + g[6]) * 1000 + g[7] + if not lines[2:]: + raise ValueError("cue without text") + cues.append((int(lines[0].strip()), start, end, lines[2:])) + return cues + + +def _sentence(rng: random.Random, words: int) -> str: + text = " ".join(rng.choice(WORDS) for _ in range(words)) + return text[0].upper() + text[1:] + rng.choice((".", "?", "!", "...")) + + +def _wrap(line: str, width: int) -> list[str]: + out = [] + while len(line) > width: + cut = line.rfind(" ", 0, width + 1) + if cut <= 0: + break + out.append(line[:cut]) + line = line[cut + 1:] + return out + [line] + + +def _build(level: int, rng: random.Random) -> Built: + count = {1: rng.randint(8, 11), 2: rng.randint(10, 13), 3: rng.randint(12, 16)}[level] + job: dict = {"shift_ms": rng.choice((-1, 1)) * rng.randint(400, 4000)} + if level >= 2: + job.update({"source_fps": "23.976", "target_fps": "25", "min_gap_ms": 80}) + if level == 3: + job.update({"max_line_chars": 42, "min_duration_ms": 1000}) + t = rng.randint(6000, 20000) + cues = [] + long_lines = set(rng.sample(range(count), 2)) if level == 3 else set() + short = set(rng.sample(range(count - 1), 3)) if level == 3 else set() + for i in range(count): + duration = rng.randint(450, 850) if i in short else rng.randint(1300, 4200) + lines = [_sentence(rng, 11 if i in long_lines else rng.randint(3, 6))] + cues.append([0, t, t + duration, lines]) + t += duration + rng.randint(30, 900) + if level >= 2: # pairs closer than the minimum gap, one of them right after a short cue at d3 + for k in rng.sample(range(count - 1), 2): + cues[k][2] = cues[k + 1][1] + rng.randint(-60, 40) + for k in short: + cues[k + 1][1] = cues[k][1] + rng.randint(900, 1100) + cues[k + 1][2] = max(cues[k + 1][2], cues[k + 1][1] + 1300) + order = list(range(count)) + rng.shuffle(order) + first = rng.randint(1, 20) + cues = [[first + 2 * n, *cues[i][1:]] for n, i in enumerate(order)] + files = {"input.srt": _render(cues), "job.json": json.dumps(job, indent=2) + "\n"} + rules = ["The cues in input.srt are out of order and misnumbered: sort them by start time and number them " + "1, 2, 3, ..."] + rules.append("Shift every start and end time by shift_ms milliseconds (negative means earlier)." if level == 1 else + "The cues were timed against source_fps video; the video now runs at target_fps (PAL speed-up), " + "so first rescale every time t to t x source_fps / target_fps, then apply shift_ms.") + if level == 3: + rules.append("After retiming, any cue shorter than min_duration_ms gets its end moved to start + " + "min_duration_ms. Apply this before the gap rule.") + if level >= 2: + rules.append("Then no cue may end later than min_gap_ms before the next cue starts; where one does, move its end " + "time earlier to exactly that point (the gap rule wins over the minimum duration).") + if level == 3: + rules.append("No text line may be longer than max_line_chars characters: break a longer line at the last " + "space that keeps the first part within the limit, and repeat for the rest.") + statement = "\n".join([ + "input.srt is a subtitle file and job.json is the edit sheet for it.", + *rules, + "Round every time to the nearest millisecond. Keep the text otherwise unchanged.", + "Write the result to output.srt in standard SRT format (index line, 'HH:MM:SS,mmm --> HH:MM:SS,mmm' line, " + "text lines, blank line between cues).", + ]) + built = Built(files=files, statement=statement, output="output.srt", reference=None) + built.reference = _parse(_solve(files, level, None)) + return built + + +def _solve(files: dict[str, str], level: int, variant: str | None) -> str: + job = json.loads(files["job.json"]) + cues = _parse(files["input.srt"]) + shift = -job["shift_ms"] if variant == "wrong_sign" else job["shift_ms"] + ratio = Fraction(1) + if level >= 2 and variant != "no_rate": + ratio = Fraction(job["source_fps"]) / Fraction(job["target_fps"]) + if variant == "inverted_rate": + ratio = 1 / ratio + + def retime(ms: int) -> int: + if variant == "shift_first": + return round((ms + shift) * ratio) + return round(ms * ratio) + shift + + out = [(idx, retime(start), retime(end), lines) for idx, start, end, lines in cues] + if variant != "no_sort": + out = [(n + 1, s, e, lines) for n, (_, s, e, lines) in enumerate(sorted(out, key=lambda c: c[1]))] + + def min_duration(cues: list) -> list: + least = job["min_duration_ms"] + return [(i, s, max(e, s + least), lines) for i, s, e, lines in cues] + + def gap(cues: list) -> list: + g = job["min_gap_ms"] + return [(i, s, min(e, cues[k + 1][1] - g) if k + 1 < len(cues) else e, lines) + for k, (i, s, e, lines) in enumerate(cues)] + + if level == 3 and variant not in ("no_min_duration", "gap_before_duration"): + out = min_duration(out) + if level >= 2 and variant != "no_gap": + out = gap(out) + if level == 3 and variant == "gap_before_duration": + out = min_duration(out) + if level == 3 and variant != "no_wrap": + width = job["max_line_chars"] + out = [(i, s, e, [part for line in lines for part in _wrap(line, width)]) for i, s, e, lines in out] + return _render(out) + + +def _check(reference: list, text: str) -> list[bool]: + cues = _parse(text) + results = [len(cues) == len(reference)] + if not results[0]: + return results + for (idx, start, end, lines), (r_idx, r_start, r_end, r_lines) in zip(cues, reference): + results += [idx == r_idx, abs(start - r_start) <= TOLERANCE_MS, abs(end - r_end) <= TOLERANCE_MS, + lines == r_lines] + return results + + +SUBTITLES = Family(name="subtitles", domain=DOMAIN, build=_build, check=_check, solve=_solve, + traps={"wrong_sign": (1, 2, 3), "no_sort": (1, 2, 3), "no_rate": (2, 3), "inverted_rate": (2, 3), + "shift_first": (2, 3), "no_gap": (2, 3), "no_wrap": (3,), "no_min_duration": (3,), + "gap_before_duration": (3,)}) diff --git a/components/qemedia/upstream/qe_arena/tasks.py b/components/qemedia/upstream/qe_arena/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..ca92048b654e3ccb8aea29d05e171699ef618f1e --- /dev/null +++ b/components/qemedia/upstream/qe_arena/tasks.py @@ -0,0 +1,573 @@ +"""Task generation and grading for the quality-engineering families. + +A task is fully determined by ``(task_id, seed)``. ``private`` holds verifier +material (reference outputs, mutants, hidden inputs) and MUST NOT be sent in an +observation. Every reference output comes from running our own corpus code in +the sandbox, so the oracle and the candidate share one execution semantics. +""" + +from __future__ import annotations + +import itertools +import json +import random +import re +from dataclasses import dataclass, field +from typing import Any + +from . import corpus, edit_budget, mutation, sandbox +from .domains import BY_SLUG, DOMAINS, SLUGS, SOFTWARE + +FAMILIES = ("qe_bugfix", "qe_mutant_kill", "qe_flaky") +LEVELS = {"qe_bugfix": (1, 2, 3, 4), "qe_mutant_kill": (1, 2, 3), "qe_flaky": (1, 2, 3)} +# The software-engineering cells, IDs and order frozen. d4 is appended so the original six (and exports) keep +# their order. +TASK_IDS = [f"{family}-d{level}" for family in FAMILIES for level in (1, 2, 3)] + ["qe_bugfix-d4"] +# Injected entries a domain needs before any of its cells is listed or served. With fewer, one function +# dominates a cell, and a function that cannot serve a seed (no subtle mutant, no fault that fits the d4 +# budget, too few short rows for a flaky suite) leaves too few others to fall back on. +MIN_DOMAIN_ENTRIES = {"qe_bugfix": 4, "qe_mutant_kill": 4, "qe_flaky": 4} + + +def _domain_cells() -> dict[str, tuple[str, str, int]]: + """Every servable task ID -> (family, domain, level). Domain cells come after the frozen ones.""" + cells = {} + for task_id in TASK_IDS: + family, level = task_id.rsplit("-d", 1) + cells[task_id] = (family, SOFTWARE, int(level)) + for domain in DOMAINS: + if domain == SOFTWARE: + continue + pool = len(corpus.domain_names(domain)) + for family in FAMILIES: + if pool >= MIN_DOMAIN_ENTRIES[family]: + for level in LEVELS[family]: + cells[f"{family}-{SLUGS[domain]}-d{level}"] = (family, domain, level) + return cells + + +CELLS = _domain_cells() +DOMAIN_TASK_IDS = [task_id for task_id in CELLS if task_id not in TASK_IDS] +ALL_TASK_IDS = TASK_IDS + DOMAIN_TASK_IDS +BUDGETED = 4 # qe_bugfix-d4: d3's faults plus a total edit budget, so a full rewrite does not fit + +HIDDEN_INPUTS = 48 +SUBTLE_RATE = 0.15 # a fault or mutant that at most this share of hidden inputs reveals +FAULTS = {1: 1, 2: 2, 3: 3, 4: 3} # qe_bugfix faults per level; the prompt never states the count +MIN_SUBTLE = {1: 0, 2: 1, 3: 2, 4: 2} +MIN_REVEALING_D1 = 3 # distinct hidden calls that reveal a d1 fault; the bug report names one of them +MAX_TESTS = {1: 1, 2: 1, 3: 3} +MAX_ARGS_BYTES = 2048 +MAX_FREE_REFUSALS = 4 # d4: refused edits that do not use a step; later ones do, so episodes stay bounded +MODULE = "module.py" +BUGFIX_CANDIDATES = 24 # fault candidates tried per corpus function +REAL_SHARE = 0.15 # share of qe_bugfix tasks that carry a real upstream fault (when real entries exist) +FILLER_KEEP = 0.5 # a real task keeps each filler candidate with this chance, so no filler site dominates +FAULT_KINDS = ("injected", "real") +# Passes over the pool before a generator gives up. A pass that builds nothing is followed by one with fresh +# draws (renaming, inputs, site order), which a small domain pool needs: at 4 passes 4 of 6,300 flaky domain +# builds still failed (seeds 5,000,000-5,000,299), at 16 none did. Software cells keep the original single +# pass, so their generation is unchanged in every case, and a domain cell's first pass is that same pass. +PASSES = {SOFTWARE: 1} +DOMAIN_PASSES = 16 + + +def passes(task_id: str) -> int: + return PASSES.get(CELLS[task_id][1], DOMAIN_PASSES) + + +@dataclass +class Task: + task_id: str + family: str + difficulty: int + seed: int + prompt: str + files: dict[str, str] + private: dict[str, Any] = field(repr=False) + + +def format_task_id(family: str, difficulty: int, domain: str = SOFTWARE) -> str: + if family not in FAMILIES: + raise ValueError(f"unknown family: {family!r}") + if type(difficulty) is not int or difficulty not in LEVELS[family]: + raise ValueError(f"difficulty must be one of {LEVELS[family]} for {family}") + if domain not in DOMAINS: + raise ValueError(f"unknown domain: {domain!r}") + task_id = f"{family}-d{difficulty}" if domain == SOFTWARE else f"{family}-{SLUGS[domain]}-d{difficulty}" + if task_id not in CELLS: + raise ValueError(f"{domain} has fewer than {MIN_DOMAIN_ENTRIES[family]} corpus entries, so no {family} cells") + return task_id + + +def _parse(task_id: str) -> tuple[str, str, int]: + if type(task_id) is not str or len(task_id) > 64: + raise ValueError("task_id must be a short string") + match = re.fullmatch(r"(qe_[a-z_]+)(?:-([a-z]+))?-d([1-4])", task_id) + if match is None or task_id not in CELLS: + if match is not None and match.group(2) in BY_SLUG: + raise ValueError(f"invalid task_id: {task_id!r} (domain cells served: {DOMAIN_TASK_IDS})") + raise ValueError(f"invalid task_id: {task_id!r}") + return CELLS[task_id] + + +def parse_task_id(task_id: str) -> tuple[str, int]: + """(family, level) of a served task ID; the domain is ``task_domain``.""" + family, _, level = _parse(task_id) + return family, level + + +def task_domain(task_id: str) -> str: + """The arena domain whose corpus entries a served task ID draws.""" + return _parse(task_id)[1] + + +def cell_names(task_id: str) -> tuple[str, ...]: + """Every corpus entry (injected and real-bug) of the task ID's domain, for per-function calibration.""" + return corpus.domain_names(task_domain(task_id), tuple(corpus.ENTRIES)) + + +def _show(value: Any) -> str: + return json.dumps(value, ensure_ascii=True, separators=(", ", ": ")) + + +def _call_text(entry: str, args: list) -> str: + return f"{entry}({', '.join(_show(a) for a in args)})" + + +MAX_SHOWN = 200 # characters of any one value shown in an observation + + +def _clip(text: str) -> str: + return text if len(text) <= MAX_SHOWN else text[:MAX_SHOWN] + f"... ({len(text)} chars)" + + +def _result_text(result: sandbox.CallResult) -> str: + if result.kind == "ok": + return _clip(_show(result.value)) + if result.kind == "exc": + return f"raises {_clip(str(result.value))}" + return result.kind + + +SETTLED = ("ok", "exc") +# Limits of our sandbox, not behaviour of the code: a 256 MiB cap or the stack depth can make one side +# raise these where the other merely ran longer. They are never a behavioural difference. +RESOURCE_EXCEPTIONS = ("MemoryError", "RecursionError") + + +def _settled(result: sandbox.CallResult) -> bool: + return result.kind == "ok" or (result.kind == "exc" and result.value not in RESOURCE_EXCEPTIONS) + + +def _outputs(source: str, entry: str, calls: list[list]) -> list[sandbox.CallResult]: + """Run calls once: fuel metering makes every outcome deterministic, so machine load cannot decide one. + + Callers treat any unsettled result (fuel, resource, crash, skipped) as unusable, never as a + behavioural difference. ``infra`` (the sandbox worker itself failed; ``timeout`` is its legacy + alias) is the only transient kind: the batch is run once more, and if it still fails this raises + InfraError instead of returning anything a grade could turn into a reward. + """ + results = sandbox.run_calls(source, entry, calls) + if any(r.kind in ("infra", "timeout") for r in results): + results = sandbox.run_calls(source, entry, calls) + failed = [r for r in results if r.kind in ("infra", "timeout")] + if failed: + raise sandbox.InfraError(f"sandbox infrastructure failed twice: {failed[0].error}"[:300]) + return results + + +def _killing(reference: list, outputs: list) -> list[int]: + """Inputs on which both sides settled and their results differ.""" + return [i for i, (r, o) in enumerate(zip(reference, outputs)) + if _settled(r) and _settled(o) and not sandbox.compare(r, o)] + + +def _usable(results: list) -> bool: + return all(_settled(r) for r in results) + + +def _subsets_all_fail(original: str, sites: list, entry: str, inputs: list, reference: list) -> bool: + """Every non-empty proper subset of the faults must still fail some hidden input. + + Otherwise fixing the complement passes the hidden tests: faults that cancel + each other on the hidden inputs would pay a partial fix 1.0. + """ + for size in range(1, len(sites)): + for subset in itertools.combinations(sites, size): + outputs = _outputs(mutation.apply(original, list(subset)), entry, inputs) + if not _usable(outputs) or not _killing(reference, outputs): + return False + return True + + +REPLY_FORMAT = ( + "Reply with exactly one JSON action object and nothing else: no prose, no markdown, " + "and do not repeat the schema." +) + + +def _budget_text(budget: int, allowance: int) -> str: + return (f"Edit budget: {budget} characters in total, counted as len(old) + len(new) over all your edits; " + "every edit reply shows what is left. Only a localised repair is accepted: keep every function and " + "all top-level code as they are (no new or redefined functions, no lambdas, no dead code such as an " + "early return or a constant condition; a `try: return X / except: pass` fallback counts as an " + f"unreachable fall-through and is refused) and change at most {allowance} syntax tokens in total. " + "An edit that breaks either rule is refused and not applied. The first " + f"{MAX_FREE_REFUSALS} refusals do not use a step; later ones do. Graded files must follow the same rules.") + + +def _bugfix_prompt(entry: str, visible: list[str], report: str, budget: int | None = None, + allowance: int | None = None) -> str: + lines = [ + f"Faults were introduced into `{entry}` in {MODULE}. The docstring is the specification " + "and is correct; the code is not. There may be more than one fault, and the number is not given.", + report, + *([_budget_text(budget, allowance)] if budget is not None else []), + "Fix the code so it matches the specification for every input. Hidden tests decide the reward, " + "and a partial fix earns nothing.", + "Visible tests:", + *visible, + "", + REPLY_FORMAT, + 'First action: {"op": "read", "path": "*"}', + 'Edit by exact text replacement (old must occur exactly once): ' + '{"op": "edit", "path": "module.py", "old": "if n < lo:", "new": "if n <= lo:"}', + 'Run the visible tests (at most 3 times): {"op": "run_tests"}', + 'Finish by grading your edited file: {"op": "submit", "answer": {}}', + ] + return "\n".join(lines) + + +def _kill_prompt(entry: str, level: int, diffs: list[str]) -> str: + count = MAX_TESTS[level] + target = "the mutant" if len(diffs) == 1 else f"each of the {len(diffs)} mutants" + lines = [ + f"original.py holds `{entry}`, which is correct. " + + ("mutant.diff shows a mutant: " if len(diffs) == 1 else f"{', '.join(diffs)} each show a mutant: ") + + "the same function with one small change.", + f"Write test cases that kill {target}: the original and the mutant must return different results " + "for your input, and expected must be exactly what the ORIGINAL returns.", + f"Submit at most {count} test case{'s' if count > 1 else ''}. Each test is " + '{"args": [positional arguments as JSON], "expected": }. ' + 'If the original raises an exception, use "expected": {"raises": "ValueError"}. ' + f"Keep each test under {MAX_ARGS_BYTES} characters of JSON.", + "Scoring per mutant: half for an input that tells them apart, half more when expected is also exact.", + "", + REPLY_FORMAT, + 'First action: {"op": "read", "path": "*"}', + 'Final action, for example: {"op": "submit", "answer": {"tests": [{"args": [3, 7], "expected": 10}]}}', + ] + return "\n".join(lines) + + +def _candidate_sites(source: str, rng: random.Random) -> list[mutation.Site]: + """Mutant-kill candidates: classic one-token operators only, in random order.""" + sites = mutation.enumerate_sites(source, mutation.CLASSIC_OPERATORS) + rng.shuffle(sites) + return sites + + +def _bugfix_sites(source: str, rng: random.Random, limit: int = BUGFIX_CANDIDATES) -> list[mutation.Site]: + """Bug-fix fault candidates, round-robin over operators with the realistic ones first. + + Every round takes one site from each realistic operator, then one from each classic operator, + so no operator with many sites (constants, variables) crowds out the others. + """ + groups: dict[str, list[mutation.Site]] = {} + for site in mutation.enumerate_sites(source): + groups.setdefault(site.operator, []).append(site) + for sites in groups.values(): + rng.shuffle(sites) + realistic = [op for op in mutation.REALISTIC_OPERATORS if op in groups] + classic = [op for op in mutation.CLASSIC_OPERATORS if op in groups] + rng.shuffle(realistic) + rng.shuffle(classic) + order: list[mutation.Site] = [] + while len(order) < limit and any(groups.values()): + for op in realistic + classic: + if groups[op]: + order.append(groups[op].pop()) + return order[:limit] + + +def _real_sites(item: corpus.CorpusEntry, original: str, renaming: dict[str, str]) -> dict: + """Each recorded real fault of ``item`` as one site on the renamed ``original``: {site: fault}.""" + found = {} + for fault in item.real_faults: + variant = item.function_source.replace(fault.find, fault.replace, 1) + try: + renamed = mutation.rename_with(variant, renaming) + except ValueError: + continue # the pre-fix code would collide with a chosen name: skip, never mis-rename + site = mutation.block_site(original, renamed, "real", f"{fault.id}: {fault.summary}") + if site is not None: + found[site] = fault + return found + + +def _make_bugfix(task_id: str, level: int, seed: int, rng: random.Random, pool: tuple[str, ...], + kind: str = "injected") -> Task: + # One pass for a real fault: when it fails, make_task falls back to injected faults on this same rng. + for _ in range(passes(task_id) if kind == "injected" else 1): + for name in rng.sample(sorted(pool), len(pool)): + item = corpus.ENTRIES[name] + renaming = mutation.local_renaming(item.function_source, random.Random(rng.random())) + original = mutation.rename_with(item.function_source, renaming) + inputs = corpus.gen_inputs(name, rng.randrange(2**31), HIDDEN_INPUTS) + graded = {json.dumps(a, sort_keys=True) for a in inputs} + display = [a for a in corpus.gen_inputs(name, rng.randrange(2**31), HIDDEN_INPUTS) + if json.dumps(a, sort_keys=True) not in graded] # shown, never graded + reference = _outputs(original, item.entry, inputs) + if not _usable(reference) or not display: + continue + real = _real_sites(item, original, renaming) if kind == "real" else {} + if kind == "real" and not real: + continue + real_first = list(real) + rng.shuffle(real_first) + chosen, buggy, killed, subtle = [], original, [], 0 + if kind == "real": # a small function has few fillers: sample them so one site cannot dominate + filler = [s for s in _bugfix_sites(original, rng, 2 * BUGFIX_CANDIDATES) if rng.random() < FILLER_KEEP] + else: + filler = _bugfix_sites(original, rng) + for site in real_first + filler: + try: + trial = mutation.apply(original, [site] + chosen) + except ValueError: + continue # overlaps an already chosen fault + alone = _outputs(mutation.apply(original, [site]), item.entry, inputs) + single = _killing(reference, alone) + if not _usable(alone) or not single: + continue # loops, crashes, or is equivalent on the hidden inputs: never a fault + is_subtle = len(single) <= SUBTLE_RATE * len(inputs) + if level == 1 and len({json.dumps(inputs[i], sort_keys=True) for i in single}) < MIN_REVEALING_D1: + continue # special-casing the one reported input must not pass every hidden test + if not is_subtle and MIN_SUBTLE[level] - subtle >= FAULTS[level] - len(chosen): + continue # the remaining slots are reserved for subtle faults + combined = _outputs(trial, item.entry, inputs) + kills = _killing(reference, combined) + if not _usable(combined) or not kills: + continue + if chosen and not _subsets_all_fail(original, chosen + [site], item.entry, inputs, reference): + continue # some faults cancel out: a partial fix would pass + if level == BUDGETED and edit_budget.plan(trial, original) is None: + continue # try another fault rather than another function: the fix must fit budget and gate + chosen, buggy, killed, subtle = chosen + [site], trial, kills, subtle + is_subtle + if len(chosen) == FAULTS[level]: + break + if len(chosen) != FAULTS[level] or (kind == "real" and not any(s in real for s in chosen)): + continue + budget = None + if level == BUDGETED: + planned = edit_budget.plan(buggy, original) + if planned is None: + continue # the minimal fix must fit the budget and the gate, and a full rewrite must not + budget = planned[0] + shown_ref = _outputs(original, item.entry, display) + shown_bug = _outputs(buggy, item.entry, display) + if not (_usable(shown_ref) and _usable(shown_bug)): + continue + revealing = _killing(shown_ref, shown_bug) + passing = [i for i in range(len(display)) if i not in revealing] + if not passing or (level == 1 and not revealing): + continue + visible_idx = rng.sample(passing, min(3, len(passing))) + if level == 1: + report = (f"A user reports a wrong result for {_call_text(item.entry, display[revealing[0]])} " + "(the correct value is not given; derive it from the docstring). The visible tests all pass.") + else: + report = ("Hidden tests fail but the visible tests all pass, so no failing input is known. " + "Compare the code with the docstring line by line to find every fault.") + visible = [{"args": display[i], "expected": shown_ref[i]} for i in visible_idx] + shown = [f" {_call_text(item.entry, v['args'])} == {_result_text(v['expected'])}" for v in visible] + return Task( + task_id=task_id, family="qe_bugfix", difficulty=level, seed=seed, + prompt=_bugfix_prompt(item.entry, shown, report, budget, + edit_budget.change_allowance(buggy) if budget is not None else None), + files={MODULE: buggy}, + private={ + "corpus": name, "entry": item.entry, "original": original, "buggy": buggy, + "sites": [s.description for s in chosen], "inputs": inputs, "reference": reference, + "visible": visible, "report_args": display[revealing[0]] if level == 1 else None, + "fault_kind": kind, "fault_sites": chosen, "edit_budget": budget, + "faults": [_fault_record(s, real.get(s)) for s in chosen], + }, + ) + raise RuntimeError(f"no usable {kind} bugfix task for {task_id} seed {seed}") + + +def _fault_record(site: mutation.Site, fault) -> dict: + if fault is None: + return {"kind": "injected", "operator": site.operator, "description": site.description} + return {"kind": "real", "id": fault.id, "fault_kind": fault.kind, "origin": fault.origin, + "summary": fault.summary, "description": site.description} + + +def _kill_rate(reference: list, outputs: list) -> float: + return len(_killing(reference, outputs)) / len(reference) + + +def _make_mutant_kill(task_id: str, level: int, seed: int, rng: random.Random, pool: tuple[str, ...]) -> Task: + wanted = 3 if level == 3 else 1 + for _ in range(passes(task_id)): + for name in rng.sample(sorted(pool), len(pool)): + item = corpus.ENTRIES[name] + original = mutation.rename_locals(item.function_source, random.Random(rng.random())) + inputs = corpus.gen_inputs(name, rng.randrange(2**31), HIDDEN_INPUTS) + reference = _outputs(original, item.entry, inputs) + if not _usable(reference): + continue + mutants = [] + for site in _candidate_sites(original, rng)[:24]: + mutant = mutation.apply(original, [site]) + outputs = _outputs(mutant, item.entry, inputs) + if not _usable(outputs): + continue # loops or crashes: its kill rate cannot be measured reliably + rate = _kill_rate(reference, outputs) + if rate == 0: + continue # possibly equivalent: never shown + if level == 1 and rate < 0.25: + continue + if level in (2, 3) and rate > SUBTLE_RATE: + continue + mutants.append({"source": mutant, "site": site.description, "random_kill_rate": rate}) + if len(mutants) == wanted: + break + if len(mutants) < wanted: + continue + files = {"original.py": original} + names = ["mutant.diff"] if wanted == 1 else [f"mutant_{i + 1}.diff" for i in range(wanted)] + for fname, m in zip(names, mutants): + files[fname] = mutation.unified_diff(original, m["source"], "original.py") + return Task( + task_id=task_id, family="qe_mutant_kill", difficulty=level, seed=seed, + prompt=_kill_prompt(item.entry, level, names), + files=files, + private={"corpus": name, "entry": item.entry, "original": original, "mutants": mutants, + "inputs": inputs, "reference": reference}, + ) + raise RuntimeError(f"no usable mutant_kill task for {task_id} seed {seed}") + + +def make_task(task_id: str, seed: int, *, pool: tuple[str, ...] | None = None, + fault_kind: str | None = None) -> Task: + """Build the task for (task_id, seed). + + The task ID's domain decides the corpus: a software-engineering ID draws exactly the entries it + always drew, and a domain cell draws only that domain's injected entries. ``pool`` restricts which + corpus functions may be drawn (all of the cell's domain), and ``fault_kind`` ("injected" or + "real") forces the qe_bugfix fault source. Both exist for per-function and per-tier + calibration and are never reachable from an episode: the server constructs environments + without them. By default a qe_bugfix task carries a real upstream fault with probability + REAL_SHARE (from a real-bug entry) and injected faults otherwise; qe_mutant_kill and the + injected tier never draw real-bug entries. + """ + family, domain, level = _parse(task_id) + if type(seed) is not int or not 0 <= seed < 2**64: + raise ValueError("seed must be an unsigned 64 bit integer") + if pool is not None and (not pool or any(name not in corpus.ENTRIES for name in pool)): + raise ValueError("pool must name corpus entries") + if pool is not None and any(corpus.ENTRIES[name].domain != domain for name in pool): + raise ValueError(f"pool must name {domain} entries for {task_id}") + if fault_kind is not None and (family != "qe_bugfix" or fault_kind not in FAULT_KINDS): + raise ValueError(f"fault_kind must be one of {FAULT_KINDS} for qe_bugfix") + injected = tuple(pool) if pool is not None else corpus.domain_names(domain) + real = tuple(n for n in (pool if pool is not None else corpus.domain_names(domain, corpus.REAL_NAMES)) + if corpus.ENTRIES[n].real_faults) + rng = random.Random(f"{task_id}:{seed}") + if family == "qe_mutant_kill": + return _make_mutant_kill(task_id, level, seed, rng, injected) + if family == "qe_flaky": + from .flaky import make_flaky_task # noqa: PLC0415 - flaky imports this module + + return make_flaky_task(task_id, level, seed, rng, injected) + if fault_kind == "real" and not real: + raise ValueError("fault_kind 'real' needs a pool with real-bug entries") + kind = fault_kind or ("real" if real and rng.random() < REAL_SHARE else "injected") + if kind == "injected": + return _make_bugfix(task_id, level, seed, rng, injected) + if fault_kind is None: + real = (rng.choice(real),) # every real entry is drawn equally often; if it cannot serve, fall back + try: + return _make_bugfix(task_id, level, seed, rng, real, "real") + except RuntimeError: + if fault_kind == "real": + raise + return _make_bugfix(task_id, level, seed, rng, injected) # no real fault fits this level and seed + + +def run_visible(task: Task, source: str) -> str: + """Visible-test report for the bugfix working copy (shown to the model).""" + p = task.private + calls = [v["args"] for v in p["visible"]] + results = _outputs(source, p["entry"], calls) + if results and all(r.kind == "rejected" for r in results): + return "REJECTED: " + "; ".join(sandbox.static_gate(source))[:400] + lines = [] + for v, got in zip(p["visible"], results): + ok = sandbox.compare(v["expected"], got) + lines.append(f"{'PASS' if ok else 'FAIL'} {_call_text(p['entry'], v['args'])}" + + ("" if ok else f" -> got {_result_text(got)}, expected {_result_text(v['expected'])}")) + passed = sum(line.startswith("PASS") for line in lines) + return f"{passed}/{len(lines)} visible tests passed\n" + "\n".join(lines) + + +def grade_bugfix(task: Task, source: str) -> float: + p = task.private + if source.strip() == p["buggy"].strip(): + return 0.0 + if p.get("edit_budget") is not None and edit_budget.structure_violation(p["buggy"], source) is not None: + return 0.0 # d4: only a localised repair counts, whatever path produced the file + results = _outputs(source, p["entry"], p["inputs"]) + return 1.0 if len(results) == len(p["reference"]) and all( + sandbox.compare(r, o) for r, o in zip(p["reference"], results)) else 0.0 + + +def _as_actual_types(expected: Any, actual: Any) -> Any: + """JSON writes 2.0 as 2: read an int as a float wherever the original returned a float.""" + if type(expected) is int and type(actual) is float: + return float(expected) + if type(expected) is list and type(actual) is list and len(expected) == len(actual): + return [_as_actual_types(e, a) for e, a in zip(expected, actual)] + if type(expected) is dict and type(actual) is dict: + return {k: _as_actual_types(v, actual[k]) if k in actual else v for k, v in expected.items()} + return expected + + +def _expected_matches(expected: Any, actual: sandbox.CallResult) -> bool: + """Exact match against what the original actually did; never raises.""" + try: + if actual.kind == "exc": + return type(expected) is dict and set(expected) == {"raises"} and expected["raises"] == actual.value + if actual.kind != "ok": + return False + return sandbox.compare(sandbox.CallResult(kind="ok", value=_as_actual_types(expected, actual.value)), actual) + except (OverflowError, ValueError, TypeError, RecursionError): + return False + + +def grade_mutant_kill(task: Task, answer: Any) -> float: + p = task.private + tests = answer.get("tests") if isinstance(answer, dict) else None + if not isinstance(tests, list) or not tests or len(tests) > MAX_TESTS[task.difficulty]: + return 0.0 + calls, expecteds = [], [] + for test in tests: + if not isinstance(test, dict) or set(test) != {"args", "expected"} or not isinstance(test["args"], list): + return 0.0 + if len(json.dumps(test, separators=(",", ":"))) > MAX_ARGS_BYTES: + return 0.0 + calls.append(test["args"]) + expecteds.append(test["expected"]) + # One batch per test: a trap ends a batch and skips the calls after it, so tests sharing a batch + # would score differently depending on their order. + reference = [r for call in calls for r in _outputs(p["original"], p["entry"], [call])] + scores = [] + for m in p["mutants"]: + outputs = [r for call in calls for r in _outputs(m["source"], p["entry"], [call])] + best = 0.0 + for i in _killing(reference, outputs): # only settled, differing results count as a kill + best = max(best, 1.0 if _expected_matches(expecteds[i], reference[i]) else 0.5) + scores.append(best) + return sum(scores) / len(scores) diff --git a/components/qemedia/upstream/qe_arena/terminal_app.py b/components/qemedia/upstream/qe_arena/terminal_app.py new file mode 100644 index 0000000000000000000000000000000000000000..4912ae9ce2ad8bac5dbe49995c87d39487dc32ea --- /dev/null +++ b/components/qemedia/upstream/qe_arena/terminal_app.py @@ -0,0 +1,23 @@ +"""The terminal-interface server (Dockerfile.terminal). The JSON-interface server is app.py.""" + +import logging +import threading + +from openenv.core.env_server.http_server import create_app + +from . import sandbox, shell +from .terminal_env import TerminalAction, TerminalEnvironment, TerminalObservation + +app = create_app(TerminalEnvironment, TerminalAction, TerminalObservation, env_name="qe_arena_terminal", + max_concurrent_envs=8) + + +def _warm() -> None: + try: + shell.mode() # logs the isolation mode once, at start-up + sandbox.warm() + except Exception: # noqa: BLE001 - logged here; the first episode raises the same error + logging.getLogger(__name__).exception("warm-up failed") + + +threading.Thread(target=_warm, name="sandbox-warm", daemon=True).start() diff --git a/components/qemedia/upstream/qe_arena/terminal_env.py b/components/qemedia/upstream/qe_arena/terminal_env.py new file mode 100644 index 0000000000000000000000000000000000000000..78263c53270995a803512e5daf9dd0d0e97f42c0 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/terminal_env.py @@ -0,0 +1,231 @@ +"""OpenEnv environment with a terminal interface: the QE tasks behind tbench2_env-shaped actions. + +The arena's evaluation probably serves its tasks through tbench2_env (`exec` / `write_file` / `evaluate`, +pytest over output files). This environment trains that protocol on our tasks: the model explores with a +real shell (``shell.py``) and writes its answer to a file, and ``evaluate`` grades that one file with the +same deterministic WASM graders as the JSON interface. Nothing the shell does can reach the reward except +the bytes of the graded file, and the hidden tests never exist on disk. + +Rewards are all or nothing, like ``evaluate``: a bug fix passes every hidden test, a mutant-kill answer kills +every mutant with exact expected values. The flaky family and qe_bugfix-d4 (whose edit budget needs the edit +op) are not served here. The qe_skill content tasks (``skills``) are served only here: their output file is +read as data by named checks, never run. +""" + +from __future__ import annotations + +import json +import secrets +from typing import Any, Literal +from uuid import uuid4 + +from openenv.core.env_server.interfaces import Environment +from openenv.core.env_server.types import Action, Observation, State +from pydantic import Field + +from . import sandbox, shell, skills +from .sandbox import InfraError +from .tasks import ALL_TASK_IDS, BUDGETED, MAX_TESTS, MODULE, REPLY_FORMAT, Task, grade_bugfix, grade_mutant_kill, \ + make_task, parse_task_id + +MAX_STEPS = 32 # tool_calls_total of the TB2 smoke contract (#196) +ANSWER = "answer.json" +MAX_ANSWER_BYTES = 8192 +TERMINAL_FAMILIES = ("qe_bugfix", "qe_mutant_kill") +TERMINAL_TASK_IDS = [t for t in ALL_TASK_IDS + if parse_task_id(t)[0] in TERMINAL_FAMILIES and parse_task_id(t)[1] != BUDGETED] +TERMINAL_TASK_IDS += skills.SKILL_TASK_IDS # appended, so every earlier cell keeps its position + + +class TerminalAction(Action): + action_type: Literal["exec", "write_file", "evaluate"] = Field(description=( + "exec: run a bash command in the working directory and see its output. " + "write_file: write a whole file. evaluate: end the episode; the hidden tests grade your file.")) + command: str = Field(default="", description="exec: the bash command.") + file_path: str = Field(default="", description="write_file: the file to write, relative to the working directory.") + content: str = Field(default="", description="write_file: the complete new file content.") + + +class TerminalObservation(Observation): + instruction: str = "" + output: str = "" + success: bool = False + error: str = "" + + +def _description(task: Task) -> str: + """The task statement without the JSON-interface action examples (everything before REPLY_FORMAT).""" + text = task.prompt.split("\n\n" + REPLY_FORMAT, 1)[0] + if task.family != "qe_mutant_kill": + return text + count = MAX_TESTS[task.difficulty] + lines = [line for line in text.split("\n") if not line.startswith("Scoring per mutant:")] + lines = [line.replace(f"Submit at most {count} test case", f"Use at most {count} test case") for line in lines] + lines.append("evaluate scores 1 only when your tests kill every mutant and every expected value is exact; " + "anything else scores 0.") + return "\n".join(lines) + + +def instruction(task: Task | skills.SkillTask, files: list[str], exec_available: bool) -> str: + """The reset observation. It never names the workspace path, so a seeded reset replays byte for byte.""" + if task.family == skills.FAMILY: + description = task.prompt + deliver = (f"evaluate grades {task.output} with hidden checks; it scores 1 only if every check passes " + "and 0 otherwise.") + elif task.family == "qe_bugfix": + deliver = (f"Fix {MODULE} in place (write_file replaces the whole file). evaluate grades {MODULE} " + "with the hidden tests.") + else: + deliver = (f'Write your tests to {ANSWER} as {{"tests": [{{"args": [...], "expected": ...}}]}}. ' + f"evaluate grades {ANSWER}.") + if task.family != skills.FAMILY: + description = _description(task) + shell_line = (f"Your working directory holds {', '.join(files)}. Commands run there in bash, with python3 and " + "git; there is no network." if exec_available else + f"Your working directory holds {', '.join(files)}. exec is unavailable on this host.") + return "\n".join([ + description, + "", + shell_line, + deliver, + f"You have {MAX_STEPS} actions in total. " + "Reply with exactly one JSON action object and nothing else: no prose, no markdown.", + 'Run a command: {"action_type": "exec", "command": "sed -n 1,40p ' + task_first_file(task) + '"}', + 'Write a file: {"action_type": "write_file", "file_path": "' + graded_file(task) + + '", "content": ""}', + 'Finish and get graded: {"action_type": "evaluate"}', + ]) + + +def graded_file(task: Task | skills.SkillTask) -> str: + if task.family == skills.FAMILY: + return task.output + return MODULE if task.family == "qe_bugfix" else ANSWER + + +def task_first_file(task: Task | skills.SkillTask) -> str: + if task.family == skills.FAMILY: + return sorted(task.files)[0] + return MODULE if task.family == "qe_bugfix" else "original.py" + + +class TerminalEnvironment(Environment[TerminalAction, TerminalObservation, State]): + SUPPORTS_CONCURRENT_SESSIONS = True + + def __init__(self, corpus_pool: tuple[str, ...] | None = None, fault_kind: str | None = None): + """``corpus_pool`` and ``fault_kind`` are for calibration only; the server passes nothing. For a qe_skill + cell, ``corpus_pool`` names families instead of corpus functions.""" + super().__init__() + self._pool = corpus_pool + self._fault_kind = fault_kind + self._state = State(episode_id=str(uuid4()), step_count=0) + self._task: Task | None = None + self._workspace: shell.Workspace | None = None + self._done = False + self._reward = 0.0 + self._sandbox_session = uuid4().hex + + def reset(self, seed: int | None = None, episode_id: str | None = None, **kwargs: Any) -> TerminalObservation: + task_id = kwargs.get("task_id", TERMINAL_TASK_IDS[0]) + if task_id not in TERMINAL_TASK_IDS and not (task_id in skills.ALL_SKILL_IDS and self._pool): + raise ValueError(f"task_id {task_id!r} is not served by the terminal interface") + if seed is None: + seed = secrets.randbelow(2**63) + kind = self._fault_kind if task_id.startswith("qe_bugfix") else None + if task_id in skills.ALL_SKILL_IDS: + task = skills.make_skill_task(task_id, seed, pool=self._pool) + else: + with sandbox.session(self._sandbox_session): + task = make_task(task_id, seed, pool=self._pool, fault_kind=kind) + self._close_workspace() + self._task = task + self._workspace = shell.Workspace(task.files) + self._state = State(episode_id=episode_id or str(uuid4()), step_count=0) + self._done, self._reward = False, 0.0 + text = instruction(task, sorted(task.files), self._workspace.exec_available) + return self._observe(instruction=text, success=True) + + def _observe(self, **fields: Any) -> TerminalObservation: + return TerminalObservation(done=self._done, reward=self._reward, **fields) + + def step(self, action: TerminalAction, timeout_s: float | None = None, **kwargs: Any) -> TerminalObservation: + """One action. An InfraError while grading propagates unscored and leaves the episode open, so + ``evaluate`` can be sent again.""" + if self._task is None: + raise RuntimeError("reset required") + if self._done: + return self._observe(error="episode is terminal; reset before another attempt") + self._state.step_count += 1 + if action.action_type == "evaluate": + return self._evaluate() + if action.action_type == "exec": + result = self._workspace.exec(action.command) + obs = dict(output=result.output, success=result.exit_code == 0, + error="" if result.exit_code == 0 else + ("timed out" if result.timed_out else + f"exit code {result.exit_code}" if result.exit_code is not None else result.output)) + if result.exit_code is None and not result.timed_out: + obs["output"] = "" + else: + error = self._workspace.write(action.file_path, action.content) + obs = dict(output="" if error else f"wrote {action.file_path}", success=error is None, error=error or "") + if self._state.step_count >= MAX_STEPS: + graded = self._evaluate() # the arena would send finish_action here; grade what is on disk + obs["output"] = (obs["output"] + "\n" if obs["output"] else "") + "action budget used up; " + graded.output + return graded.model_copy(update=obs) + return self._observe(**obs) + + def _grade(self, text: str | None) -> float: + task = self._task + if text is None: + return 0.0 + if task.family == skills.FAMILY: + return skills.grade(task, text) + if task.family == "qe_bugfix": + return grade_bugfix(task, text) + if len(text.encode("utf-8")) > MAX_ANSWER_BYTES: + return 0.0 + try: + answer = json.loads(text) + except (ValueError, RecursionError): + return 0.0 + return 1.0 if grade_mutant_kill(task, answer) == 1.0 else 0.0 + + def peek_reward(self) -> float: + """What evaluate would score now, without ending the episode (calibration's finish_action probe).""" + if self._task is None or self._workspace is None: + return float(self._reward) + text = self._workspace.read(graded_file(self._task)) + try: + with sandbox.session(self._sandbox_session): + return self._grade(text) + except InfraError: + raise + except Exception: # noqa: BLE001 + return 0.0 + + def _evaluate(self) -> TerminalObservation: + text = self._workspace.read(graded_file(self._task)) + try: + with sandbox.session(self._sandbox_session): + reward = self._grade(text) + except InfraError: + self._state.step_count -= 1 + raise # not the answer's fault: no reward, the episode stays open + except Exception: # noqa: BLE001 - any other grading failure on a model file scores 0 + reward = 0.0 + self._done, self._reward = True, reward + self._close_workspace() + return self._observe(output=f"graded: reward {reward:g}", success=reward == 1.0) + + def _close_workspace(self) -> None: + if self._workspace is not None: + self._workspace.close() + self._workspace = None + + def close(self) -> None: + self._close_workspace() + + @property + def state(self) -> State: + return self._state.model_copy(deep=True) diff --git a/components/qemedia/upstream/qe_arena/wasi_fs.py b/components/qemedia/upstream/qe_arena/wasi_fs.py new file mode 100644 index 0000000000000000000000000000000000000000..c353d5e67d824ae459593c63e07b9861f05060a1 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/wasi_fs.py @@ -0,0 +1,340 @@ +"""A read-only, in-memory WASI preview1 filesystem for the sandbox guest. + +wasmtime's own filesystem passes the host's metadata through to the guest: 64-bit inode numbers, +link counts, directory sizes and real access/modify/change times (reading the stdlib zip even +bumps its atime, so the guest could read the host clock). The interpreter stats the stdlib at +startup, those values become Python ints of host-dependent size, and the heap, and therefore fuel, +differed between a Linux host and a container on the same machine. + +So the guest gets no host directory at all. This module answers every fd_* and path_* call from +memory: one preopened directory ``/lib`` holding one file (the reproducible stdlib zip), with +canonical metadata (fixed times, fixed inode numbers, nlink 1). Stdio fds 0-2 look exactly as +wasmtime presents unattached stdio (unknown filetype, all-zero stat, not a tty); fd 1 and fd 2 +writes go to ``on_write``. Anything that would modify the filesystem is refused. + +The functions follow the WASI preview1 ABI (wasi_snapshot_preview1); every pointer is checked +against linear memory by wasmtime's memory accessors, which raise on an out-of-bounds access. +""" + +from __future__ import annotations + +import posixpath +import struct +from dataclasses import dataclass +from typing import Callable + +# errno +SUCCESS, EACCES, EBADF, EINVAL, EISDIR, ENOENT, ENOTDIR, ENOTSUP, EPERM, EROFS, ESPIPE = ( + 0, 2, 8, 28, 31, 44, 54, 58, 63, 69, 70) +# filetype +UNKNOWN, DIRECTORY, REGULAR_FILE = 0, 3, 4 +# oflags / rights +O_CREAT, O_DIRECTORY, O_EXCL, O_TRUNC = 1, 2, 4, 8 +FDFLAG_APPEND = 1 +RIGHT_FD_WRITE = 1 << 6 +RIGHTS_DIR = 0x1FFFFFFF & ~(RIGHT_FD_WRITE) +RIGHTS_FILE = (1 << 1) | (1 << 2) | (1 << 5) | (1 << 7) | (1 << 21) # read, seek, tell, advise, filestat_get +WHENCE_SET, WHENCE_CUR, WHENCE_END = 0, 1, 2 + +FIXED_TIME_NS = 1_700_000_000 * 10**9 +PREOPEN = "/lib" + + +@dataclass +class _Open: + path: str + is_dir: bool + pos: int = 0 + + +class VirtualFS: + def __init__(self, files: dict[str, bytes], on_write: Callable[[object, int, bytes], int]) -> None: + """``files`` maps absolute guest paths under /lib to contents. ``on_write(caller, fd, data)`` + receives fd 1 and fd 2 writes and returns the errno.""" + self.files = dict(files) + self.dirs = {PREOPEN} + for path in self.files: + parent = posixpath.dirname(path) + while parent.startswith(PREOPEN) and parent not in self.dirs: + self.dirs.add(parent) + parent = posixpath.dirname(parent) + self.inodes = {path: i + 2 for i, path in enumerate(sorted(self.dirs | set(self.files)))} + self.fds: dict[int, _Open] = {3: _Open(PREOPEN, True)} + self.on_write = on_write + + # ------------------------------------------------------------------ helpers + @staticmethod + def _mem(caller): + return caller.get("memory") + + def _read(self, caller, ptr: int, length: int) -> bytes: + return bytes(self._mem(caller).read(caller, ptr, ptr + length)) + + def _write(self, caller, ptr: int, data: bytes) -> None: + self._mem(caller).write(caller, data, ptr) + + def _iovs(self, caller, iovs: int, count: int) -> list[tuple[int, int]]: + raw = self._read(caller, iovs, 8 * count) + return [struct.unpack_from(" tuple[int, str]: + base = self.fds.get(dirfd) + if base is None: + return EBADF, "" + if not base.is_dir: + return ENOTDIR, "" + rel = raw.decode("utf-8", "surrogateescape") + if rel.startswith("/"): + return EPERM, "" + path = posixpath.normpath(posixpath.join(base.path, rel)) if rel else base.path + if path != PREOPEN and not path.startswith(PREOPEN + "/"): + return EPERM, "" # escapes the preopen (wasmtime refuses these too) + if path not in self.files and path not in self.dirs: + return ENOENT, "" + return SUCCESS, path + + def _filestat(self, path: str | None) -> bytes: + if path is None: # stdio, as wasmtime presents unattached stdio + return bytes(64) + is_dir = path in self.dirs + size = 0 if is_dir else len(self.files[path]) + return struct.pack(" int: + return if_stdio if fd in (0, 1, 2) else EBADF + + # ------------------------------------------------------------------ fd_* + def fd_write(self, caller, fd, iovs, iovs_len, nwritten_ptr): + if fd not in (1, 2): + return EBADF + data = b"".join(self._read(caller, p, n) for p, n in self._iovs(caller, iovs, iovs_len)) + self._write(caller, nwritten_ptr, struct.pack("= buf_len: + break + data = bytes(out[:buf_len]) + if data: + self._write(caller, buf, data) + self._write(caller, bufused_ptr, struct.pack(" int: + return EROFS if dirfd in self.fds else EBADF + + def path_create_directory(self, caller, dirfd, path, path_len): + return self._refuse(dirfd) + + def path_remove_directory(self, caller, dirfd, path, path_len): + return self._refuse(dirfd) + + def path_unlink_file(self, caller, dirfd, path, path_len): + return self._refuse(dirfd) + + def path_filestat_set_times(self, caller, dirfd, flags, path, path_len, atim, mtim, fst_flags): + return self._refuse(dirfd) + + def path_symlink(self, caller, old, old_len, dirfd, new, new_len): + return self._refuse(dirfd) + + def path_link(self, caller, old_fd, old_flags, old, old_len, new_fd, new, new_len): + return self._refuse(new_fd) + + def path_rename(self, caller, fd, old, old_len, new_fd, new, new_len): + return self._refuse(new_fd) + + +I32, I64 = "i32", "i64" +SIGNATURES: dict[str, tuple[list[str], list[str]]] = { + "fd_advise": ([I32, I64, I64, I32], [I32]), + "fd_close": ([I32], [I32]), + "fd_datasync": ([I32], [I32]), + "fd_fdstat_get": ([I32, I32], [I32]), + "fd_fdstat_set_flags": ([I32, I32], [I32]), + "fd_filestat_get": ([I32, I32], [I32]), + "fd_filestat_set_size": ([I32, I64], [I32]), + "fd_filestat_set_times": ([I32, I64, I64, I32], [I32]), + "fd_pread": ([I32, I32, I32, I64, I32], [I32]), + "fd_prestat_get": ([I32, I32], [I32]), + "fd_prestat_dir_name": ([I32, I32, I32], [I32]), + "fd_pwrite": ([I32, I32, I32, I64, I32], [I32]), + "fd_read": ([I32, I32, I32, I32], [I32]), + "fd_readdir": ([I32, I32, I32, I64, I32], [I32]), + "fd_seek": ([I32, I64, I32, I32], [I32]), + "fd_sync": ([I32], [I32]), + "fd_tell": ([I32, I32], [I32]), + "fd_write": ([I32, I32, I32, I32], [I32]), + "path_create_directory": ([I32, I32, I32], [I32]), + "path_filestat_get": ([I32, I32, I32, I32, I32], [I32]), + "path_filestat_set_times": ([I32, I32, I32, I32, I64, I64, I32], [I32]), + "path_link": ([I32, I32, I32, I32, I32, I32, I32], [I32]), + "path_open": ([I32, I32, I32, I32, I32, I64, I64, I32, I32], [I32]), + "path_readlink": ([I32, I32, I32, I32, I32, I32], [I32]), + "path_remove_directory": ([I32, I32, I32], [I32]), + "path_rename": ([I32, I32, I32, I32, I32, I32], [I32]), + "path_symlink": ([I32, I32, I32, I32, I32], [I32]), + "path_unlink_file": ([I32, I32, I32], [I32]), +} diff --git a/components/qemedia/upstream/qe_arena/wasi_worker.py b/components/qemedia/upstream/qe_arena/wasi_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..654adab5f481c5c25333cd5f12178d9da5951312 --- /dev/null +++ b/components/qemedia/upstream/qe_arena/wasi_worker.py @@ -0,0 +1,395 @@ +"""Long-lived sandbox worker: runs candidate Python inside CPython-WASI under wasmtime fuel. + +Started by ``qe_arena.sandbox`` as its own process (never inside the uvicorn process, so a wasmtime +fault or a host bug cannot take down /health). It reads one JSON request per line on stdin and +writes one JSON response per line. Each batch gets a fresh Store and Instance: + +* every call is metered in wasmtime fuel (about one unit per wasm instruction), never wall time, + so a loop ends as ``fuel`` at exactly its budget on every host and under any load; +* linear memory is capped (``resource`` when exceeded, as is wasm stack exhaustion); +* the guest sees no host filesystem: ``qe_arena/wasi_fs.py`` serves one read-only directory, + ``/lib``, holding the reproducible stdlib zip from memory, with canonical metadata (wasmtime's + own preopen leaked host inode numbers, link counts and timestamps, which moved fuel between a + host and a container on the same machine); the environment holds only PYTHONHASHSEED=0; clocks + and clock resolution are fixed or stepped, ``random_get`` is a seeded SHAKE-256 stream and + ``poll_oneoff`` is unsupported, so the guest cannot observe the host; +* call boundaries and per-call fuel come from nonce-tagged markers the harness writes to fd 1 + (see ``Protocol``); anything else on fd 1 fails the batch closed; +* a 60 s wall-clock epoch deadline exists only as an infrastructure backstop (``infra``), which is + never graded. +""" + +from __future__ import annotations + +import ctypes +import hashlib +import json +import os +import sys +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable + +import wasmtime as wt +from wasmtime import _ffi as ffi + +from .wasi_fs import SIGNATURES as FS_SIGNATURES, VirtualFS + +HARNESS = (Path(__file__).resolve().parent / "guest_harness.py").read_text(encoding="utf-8") +STARTUP_FUEL = 3_000_000_000 # interpreter init plus allowlisted imports (measured 287,333,867) +HARNESS_FUEL = 20_000_000 # harness work between calls (marker, row, next args); no candidate code runs there +BACKSTOP_S = 60.0 # wall clock per instance: infrastructure failure only, never graded +EPOCH_TICK_S = 0.1 +FIXED_REALTIME_NS = 1_700_000_000 * 10**9 +MAX_GUEST_STDOUT = 4 << 20 +ENOTSUP = 58 +RNG_SEED = b"qe-arena" +GUEST_ARGV = ["python", "-S", "-s", "-P", "-B", "-c", HARNESS] +GUEST_ENV = [("PYTHONHASHSEED", "0"), ("PYTHONDONTWRITEBYTECODE", "1")] + +I32 = wt.ValType.i32() +I64 = wt.ValType.i64() + + +PINS: dict[str, str] = json.loads((Path(__file__).resolve().parent / "runtime_pins.json").read_text()) + + +class RuntimeIdentityError(Exception): + """python.wasm or the stdlib zip is not the pinned, reproducible build.""" + + +class ProtocolError(Exception): + """The guest's fd 1 carried something other than this run's markers, in order.""" + + +class Protocol: + """Parses the harness's fd 1 stream and drives fuel at call boundaries. + + Order is enforced: [B E R] for the module body, then [B E R] per call; a probe writes a single R. + Every marker must carry this run's nonce. Violations raise ProtocolError, which the worker turns + into a crash for the whole batch: nothing on fd 1 can forge a result or move fuel accounting. + """ + + def __init__(self, nonce: str, budgets: list[int], get_fuel: Callable[[], int], + set_fuel: Callable[[int], None]) -> None: + self.begin = b"\x01B " + nonce.encode("ascii") + self.end = b"\x01E " + nonce.encode("ascii") + self.row_head = b"\x01R " + nonce.encode("ascii") + b" " + self.budgets = budgets + self.get_fuel, self.set_fuel = get_fuel, set_fuel + self.state = "start" + self.slot = 0 + self.budget_now = 0 + self.used: list[int] = [] + self.rows: list[dict] = [] + self.buf = bytearray() + self.total = 0 + + @property + def in_call(self) -> bool: + return self.state == "in" + + def feed(self, data: bytes) -> None: + self.total += len(data) + if self.total > MAX_GUEST_STDOUT: + raise ProtocolError("guest stdout over its cap") + self.buf += data + while True: + nl = self.buf.find(b"\n") + if nl < 0: + return + line = bytes(self.buf[:nl]) + del self.buf[:nl + 1] + self._line(line) + + def _line(self, line: bytes) -> None: + if line == self.begin and self.state in ("start", "ready"): + if self.slot >= len(self.budgets): + raise ProtocolError("more calls than budgets") + self.budget_now = self.budgets[self.slot] + self.state = "in" + self.set_fuel(self.budget_now) + elif line == self.end and self.state == "in": + self.used.append(self.budget_now - self.get_fuel()) + self.slot += 1 + self.state = "after" + self.set_fuel(HARNESS_FUEL) + elif line.startswith(self.row_head) and self.state in ("after", "start"): + try: + row = json.loads(line[len(self.row_head):].decode("utf-8", "surrogatepass")) + except ValueError as exc: + raise ProtocolError(f"bad row: {exc}") from exc + if not isinstance(row, dict): + raise ProtocolError("row is not an object") + self.rows.append(row) + self.state = "ready" if self.state == "after" else "done" + else: + raise ProtocolError(f"unexpected line in state {self.state}: {line[:40]!r}") + + +# --------------------------------------------------------------------------- engine (one per process) + +def make_engine() -> wt.Engine: + cfg = wt.Config() + cfg.consume_fuel = True + cfg.epoch_interruption = True + cfg.cranelift_nan_canonicalization = True # NaN bit patterns identical across hosts + cfg.wasm_relaxed_simd_deterministic = True + cfg.wasm_threads = False + return wt.Engine(cfg) + + +def set_caller_fuel(caller: wt.Caller, amount: int) -> None: + """wasmtime-py exposes fuel only on Store; inside a host call we must use the caller's context. + This uses the private ``_ffi`` surface, so tests/test_sandbox.py pins it (wasmtime==47.0.1).""" + err = ffi.wasmtime_context_set_fuel(caller._context(), amount) + if err: + raise wt.WasmtimeError._from_ptr(err) + + +def get_caller_fuel(caller: wt.Caller) -> int: + out = ctypes.c_uint64(0) + err = ffi.wasmtime_context_get_fuel(caller._context(), ctypes.byref(out)) + if err: + raise wt.WasmtimeError._from_ptr(err) + return out.value + + +@dataclass +class Instance: + """Outcome of one guest instance.""" + protocol: Protocol + status: str # exit | fuel | resource | infra | protocol | trap + detail: str = "" + remaining: int = 0 # fuel left in the store when the instance stopped + + @property + def call_fuel(self) -> int: + """Fuel the interrupted call consumed (meaningful when it died inside a call).""" + return max(0, self.protocol.budget_now - self.remaining) if self.protocol.in_call else 0 + + +@dataclass +class Runtime: + root: Path + engine: wt.Engine = field(default_factory=make_engine) + module: Any = None + files: dict = field(default_factory=dict) + + def load(self, pins: dict[str, str] | None = None) -> None: + """Read the runtime, check it against the pins, then compile and serve those same bytes (no + window to swap a file between the check and its use). Raises RuntimeIdentityError.""" + pins = PINS if pins is None else pins + wasm = (self.root / "python.wasm").read_bytes() + stdlib = (self.root / "lib" / "python314.zip").read_bytes() + for name, data in (("python.wasm", wasm), ("lib/python314.zip", stdlib)): + digest = hashlib.sha256(data).hexdigest() + if digest != pins.get(name): + raise RuntimeIdentityError(f"{name} sha256 {digest} is not the pinned {pins.get(name)}") + self.files = {"/lib/python314.zip": stdlib} + self.module = wt.Module(self.engine, wasm) + threading.Thread(target=self._ticker, daemon=True).start() + + def _ticker(self) -> None: + while True: + time.sleep(EPOCH_TICK_S) + self.engine.increment_epoch() + + def _linker(self, state: dict) -> wt.Linker: + linker = wt.Linker(self.engine) + linker.define_wasi() # args, environ, proc_exit, sched_yield, sock_* (on stdio only) + linker.allow_shadowing = True + + def on_write(caller, fd, data): + if fd != 1: + return 0 # stderr: swallowed + protocol = state["protocol"] + protocol.get_fuel = lambda: get_caller_fuel(caller) + protocol.set_fuel = lambda amount: set_caller_fuel(caller, amount) + try: + protocol.feed(data) + except ProtocolError as exc: + state["violation"] = str(exc) + raise wt.Trap("protocol violation") from exc + return 0 + + fs = VirtualFS(self.files, on_write) + + def clock_time_get(caller, clock_id, precision, out_ptr): + if clock_id == 0: + value = FIXED_REALTIME_NS + else: + state["mono_ns"] += 1000 # stepped, never real + value = state["mono_ns"] + caller.get("memory").write(caller, value.to_bytes(8, "little"), out_ptr) + return 0 + + def clock_res_get(caller, clock_id, out_ptr): + caller.get("memory").write(caller, (1000).to_bytes(8, "little"), out_ptr) # not the host's + return 0 + + def random_get(caller, buf, length): + if length: + state["rng"] += 1 + data = hashlib.shake_256(RNG_SEED + state["rng"].to_bytes(8, "little")).digest(length) + caller.get("memory").write(caller, data, buf) + return 0 + + def poll_oneoff(caller, a, b, c, d): + return ENOTSUP # no sleeping, no waiting on the host + + def sig(params, results): + return wt.FuncType(params, results) + ns = "wasi_snapshot_preview1" + types = {"i32": I32, "i64": I64} + for name, (params, results) in FS_SIGNATURES.items(): + linker.define_func(ns, name, sig([types[t] for t in params], [types[t] for t in results]), + getattr(fs, name), access_caller=True) + linker.define_func(ns, "clock_time_get", sig([I32, I64, I32], [I32]), clock_time_get, access_caller=True) + linker.define_func(ns, "clock_res_get", sig([I32, I32], [I32]), clock_res_get, access_caller=True) + linker.define_func(ns, "random_get", sig([I32, I32], [I32]), random_get, access_caller=True) + linker.define_func(ns, "poll_oneoff", sig([I32] * 4, [I32]), poll_oneoff, access_caller=True) + return linker + + def instance(self, request: dict, budgets: list[int], mem_mb: int) -> Instance: + store = wt.Store(self.engine) + store.set_limits(memory_size=mem_mb << 20) + store.set_fuel(STARTUP_FUEL) + store.set_epoch_deadline(int(BACKSTOP_S / EPOCH_TICK_S)) + wasi = wt.WasiConfig() + wasi.argv = GUEST_ARGV + [json.dumps(request, ensure_ascii=True, allow_nan=True)] + wasi.env = GUEST_ENV + store.set_wasi(wasi) + protocol = Protocol(request["nonce"], budgets, lambda: 0, lambda amount: None) + state = {"protocol": protocol, "mono_ns": 0, "rng": 0, "violation": ""} + inst = self._run(store, state) + try: + inst.remaining = store.get_fuel() + except wt.WasmtimeError: + inst.remaining = 0 + return inst + + def _run(self, store: wt.Store, state: dict) -> Instance: + protocol = state["protocol"] + try: + self._linker(state).instantiate(store, self.module).exports(store)["_start"](store) + return Instance(protocol, "exit", "0") + except wt.ExitTrap as exc: + return Instance(protocol, "exit", str(exc.code)) + except wt.Trap as exc: + if state["violation"]: + return Instance(protocol, "protocol", state["violation"]) + code = exc.trap_code + if code == wt.TrapCode.OUT_OF_FUEL: + return Instance(protocol, "fuel") + if code == wt.TrapCode.INTERRUPT: + return Instance(protocol, "infra", "wall-clock backstop") + if code == wt.TrapCode.STACK_OVERFLOW: + return Instance(protocol, "resource", "wasm stack exhausted") + return Instance(protocol, "trap", (exc.message or "")[:200]) + except wt.WasmtimeError as exc: + if state["violation"]: + return Instance(protocol, "protocol", state["violation"]) + return Instance(protocol, "trap", str(exc)[:200]) + + +def _row(kind: str, value: Any = None, error: str = "", fuel: int = 0) -> dict: + return {"k": kind, "v": value, "e": error, "f": fuel} + + +def run_batch(runtime: Runtime, req: dict) -> list[dict]: + """Run every call in one instance, in order. + + A trap (fuel, wasm stack, any other trap) ends the instance. The call it interrupted gets that + outcome and every later call is ``skipped``: there is no reconstructed state to run them on, so + their results would depend on which earlier calls trapped. Callers that need independent + results put calls in separate batches (grade_mutant_kill does). + """ + calls = req["calls"] + n = len(calls) + guest_req = {key: req[key] for key in ("source", "entry", "calls", "nonce", "modules", "builtins", + "max_value_bytes", "max_total_bytes")} + inst = runtime.instance(guest_req, [int(req["module_fuel"])] + [int(req["fuel"])] * n, int(req["mem_mb"])) + proto = inst.protocol + if inst.status == "protocol": + return [_row("crash", None, f"sandbox protocol: {inst.detail}")] * n + if not proto.rows: # died in startup or inside the module body + if inst.status == "fuel" and proto.slot == 0 and proto.in_call: + return [_row("fuel", None, "module body: fuel budget exhausted", proto.budget_now)] * n + kind = inst.status if inst.status in ("infra", "resource") else "crash" + return [_row(kind, None, f"module: {inst.status} {inst.detail}".strip())] * n + head, rows = proto.rows[0], proto.rows[1:] + if head.get("k") != "ok": + kind = "resource" if head.get("k") == "resource" else "crash" + return [_row(kind, None, str(head.get("e", ""))[:200])] * n + results = [] + for j, r in enumerate(rows): + used = proto.used[j + 1] if j + 1 < len(proto.used) else 0 + kind = r.get("k") + results.append(_row(kind, r.get("v") if kind in ("ok", "exc") else None, str(r.get("e", ""))[:200], used)) + if len(results) < n: + if inst.status == "exit": + results.append(_row("crash", None, "guest exited early")) + elif inst.status == "fuel" and proto.in_call: + results.append(_row("fuel", None, "fuel budget exhausted", proto.budget_now)) + elif inst.status in ("resource", "infra"): + results.append(_row(inst.status, None, inst.detail, inst.call_fuel)) + else: + results.append(_row("crash", None, f"{inst.status}: {inst.detail}"[:200])) + stopped = len(results) - 1 + results += [_row("skipped", None, f"call {stopped} stopped the instance")] * (n - len(results)) + return results + + +def probe(runtime: Runtime, req: dict) -> dict: + guest_req = {"probe": req["probe"], "nonce": req["nonce"], "modules": req["modules"]} + inst = runtime.instance(guest_req, [], int(req.get("mem_mb", 256))) + if inst.protocol.rows: + return inst.protocol.rows[0] + return {"error": f"{inst.status} {inst.detail}"} + + +def main() -> int: + out = os.fdopen(os.dup(1), "wb", buffering=0) + os.dup2(2, 1) # nothing but responses may reach the parent's pipe + root = Path(os.environ["QE_ARENA_WASI_ROOT"]) + + def send(obj: dict) -> None: + out.write(json.dumps(obj, allow_nan=True).encode("utf-8", "surrogatepass") + b"\n") + + runtime = Runtime(root) + try: + runtime.load() + except (RuntimeIdentityError, OSError) as exc: + print(f"qe_arena sandbox worker refused to start: {exc}", file=sys.stderr) + try: + send({"ready": False, "error": str(exc)[:300]}) + except BrokenPipeError: + pass + return 1 + + try: + send({"ready": True}) + for line in sys.stdin.buffer: + send(_answer(runtime, line)) + except BrokenPipeError: + pass # the parent went away (server shutdown): nothing left to answer + return 0 + + +def _answer(runtime: Runtime, line: bytes) -> dict: + try: + req = json.loads(line) + except ValueError: + return {"error": "bad request"} + try: + if "probe" in req: + return {"id": req.get("id"), "probe": probe(runtime, req)} + return {"id": req.get("id"), "results": run_batch(runtime, req)} + except Exception as exc: # noqa: BLE001 - report, keep serving + return {"id": req.get("id"), "error": f"{type(exc).__name__}: {exc}"[:300]} + +if __name__ == "__main__": + sys.exit(main()) diff --git a/components/skillsdesk/ADAPTER_NOTICE b/components/skillsdesk/ADAPTER_NOTICE deleted file mode 100644 index 1187600f72d9c86490157d1321db0c6bea1a7746..0000000000000000000000000000000000000000 --- a/components/skillsdesk/ADAPTER_NOTICE +++ /dev/null @@ -1,2 +0,0 @@ -This distribution adds the shared Arena interface and the selected task registry. -Original Skills Desk task generators, graders and fixed instance seeds are retained. diff --git a/components/skillsdesk/Dockerfile b/components/skillsdesk/Dockerfile deleted file mode 100644 index 8f28be1a5e8bb20c8eb33864128ae227b23ea7ff..0000000000000000000000000000000000000000 --- a/components/skillsdesk/Dockerfile +++ /dev/null @@ -1,15 +0,0 @@ -FROM ghcr.io/syndicate604/skills-desk@sha256:5492135dea6e9ec3b0c9a0dacf22a53d79014271c1736b152afdab69d89414df -USER root -COPY upstream/terminal_desk /opt/terminal_desk/terminal_desk -COPY upstream/openenv.yaml /opt/terminal_desk/openenv.yaml -COPY runtime /opt/skillsdesk_compat -COPY SOURCE_MANIFEST.json /opt/skillsdesk_compat/SOURCE_MANIFEST.json -COPY LICENSE NOTICE ADAPTER_NOTICE /opt/skillsdesk_compat/licenses/ -RUN chmod -R go-rwx /opt/terminal_desk /opt/skillsdesk_compat -ENV PYTHONPATH=/opt/skillsdesk_compat:/opt/terminal_desk OPENENV_MODE=production PYTHONDONTWRITEBYTECODE=1 -WORKDIR /opt/skillsdesk_compat -LABEL org.opencontainers.image.title="Skills Breadth v10" \ - org.opencontainers.image.description="Original Skills Desk artifact and code repair tasks with the shared Arena interface" \ - org.opencontainers.image.source="https://huggingface.co/datasets/bochencs/openenv-multidomain" \ - org.opencontainers.image.licenses="Apache-2.0" -CMD ["python", "-m", "skillsdesk_compat.server"] diff --git a/components/skillsdesk/LICENSE b/components/skillsdesk/LICENSE deleted file mode 100644 index d645695673349e3947e8e5ae42332d0ac3164cd7..0000000000000000000000000000000000000000 --- a/components/skillsdesk/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/components/skillsdesk/NOTICE b/components/skillsdesk/NOTICE deleted file mode 100644 index 58fdbd780296862854b0fe460190c4c628d1d18b..0000000000000000000000000000000000000000 --- a/components/skillsdesk/NOTICE +++ /dev/null @@ -1,12 +0,0 @@ -Skills Desk -Copyright 2026 Syndicate604 - -This product is a fork of Terminal Desk v2 by dnakhla -(https://huggingface.co/datasets/dnakhla/terminal-desk, revision 7fe454e7), -licensed under the Apache License, Version 2.0, by way of Science Desk -(Syndicate604). The server, sandbox and grading core come from that work, and -the fix_toolkit task is adapted from its sw_fix family. Changes: all task -families are new (five skills: evidence, computation, transformation, repair, -constraints), a frozen reserved evaluation set, a fixed instance per task id, -strict output-structure grading, hidden-input grading of repaired code, -reference agent scripts and deliberate-mistake tests. diff --git a/components/skillsdesk/README.md b/components/skillsdesk/README.md deleted file mode 100644 index 592f5af2bb6a94b2d8c0af38eae5135d7f089b8a..0000000000000000000000000000000000000000 --- a/components/skillsdesk/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Original Skills Desk tasks from Syndicate604, with the shared Arena interface. - -Run: `python -m skillsdesk_compat.server` - -Run the service as root; task commands run as nobody. Use one episode per fresh sandbox and one active session. The selected original fixed IDs are listed in SOURCE_MANIFEST.json. diff --git a/components/skillsdesk/SOURCE_MANIFEST.json b/components/skillsdesk/SOURCE_MANIFEST.json deleted file mode 100644 index 49f98d85b2bf5a6b6056e4fdfa1bf6ed1785736a..0000000000000000000000000000000000000000 --- a/components/skillsdesk/SOURCE_MANIFEST.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "dataset": "Syndicate604/skills-desk", - "revision": "a785ccdc9784ed863d0ffecec826d72176c0a785", - "license": "Apache-2.0", - "base_image": "ghcr.io/syndicate604/skills-desk@sha256:5492135dea6e9ec3b0c9a0dacf22a53d79014271c1736b152afdab69d89414df", - "original_files": { - "openenv.yaml": "88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e", - "terminal_desk/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "terminal_desk/core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "terminal_desk/core/grading.py": "d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9", - "terminal_desk/core/shell.py": "e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d", - "terminal_desk/families/__init__.py": "3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411", - "terminal_desk/families/base.py": "a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f", - "terminal_desk/families/compute.py": "60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3", - "terminal_desk/families/compute2.py": "91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33", - "terminal_desk/families/constraints.py": "25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0", - "terminal_desk/families/constraints2.py": "411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4", - "terminal_desk/families/evidence.py": "c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045", - "terminal_desk/families/evidence2.py": "d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60", - "terminal_desk/families/repair.py": "a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781", - "terminal_desk/families/repair2.py": "1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6", - "terminal_desk/families/transform.py": "d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1", - "terminal_desk/families/transform2.py": "2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2", - "terminal_desk/families/util.py": "0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832", - "terminal_desk/models.py": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4", - "terminal_desk/reserved/__init__.py": "012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330", - "terminal_desk/reserved/compute.py": "e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083", - "terminal_desk/reserved/constraints.py": "ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0", - "terminal_desk/reserved/evidence.py": "e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0", - "terminal_desk/reserved/repair.py": "121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5", - "terminal_desk/reserved/transform.py": "bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf", - "terminal_desk/server/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "terminal_desk/server/app.py": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8", - "terminal_desk/server/environment.py": "82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319" - }, - "selected_tasks": [ - "ev_calibration-L1", - "cmp_fifo-L1", - "tx_events-L1", - "fix_units-L1", - "plan_shifts-L1", - "ev_badges-L1", - "cmp_meter-L1", - "tx_pivot-L1", - "fix_toolkit-L1", - "plan_load-L1", - "ev_bankrec-L1", - "cmp_smooth-L1", - "tx_sessions-L1", - "fix_bizdays-L1", - "plan_disks-L1", - "ev_backorder-L2", - "ev_dupes-L1", - "tx_mdtable-L1", - "fix_mergelogs-L1", - "plan_delivery-L1" - ], - "instance_policy": "Original fixed base instance; production ignores client seed.", - "sdk_revision": "86a180ede21e044f7929b9a7783ad83aa67d83a3", - "sdk_wheel_sha256": "c00388296c8930d67d296c5d74eacb41dbd15372a144c24aeb5d816d049c403d" -} diff --git a/components/skillsdesk/UPSTREAM_DOCKERFILE b/components/skillsdesk/UPSTREAM_DOCKERFILE deleted file mode 100644 index 256cb33dfec6de07c63920d6f3d05622fa03b8fe..0000000000000000000000000000000000000000 --- a/components/skillsdesk/UPSTREAM_DOCKERFILE +++ /dev/null @@ -1,40 +0,0 @@ -# Skills Desk OpenEnv server (forked from Science Desk / dnakhla's Terminal Desk v2, Apache-2.0). linux/amd64 only: -# DOCKER_DEFAULT_PLATFORM=linux/amd64 docker build -t ghcr.io/syndicate604/skills-desk:v1 . -FROM python:3.12-slim - -RUN apt-get update \ - && apt-get install -y --no-install-recommends jq bc sqlite3 \ - && rm -rf /var/lib/apt/lists/* - -# The server lives outside /app: /app is the task workspace, as in the operator's task images. -WORKDIR /opt/terminal_desk -ENV PYTHONDONTWRITEBYTECODE=1 \ - PYTHONUNBUFFERED=1 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 \ - PYTHONPATH=/opt/terminal_desk - -# OpenEnv at the arena's pinned revision (86a180e), vendored as a wheel. -COPY vendor ./vendor -RUN pip install ./vendor/openenv-0.6.1.dev0-py3-none-any.whl && rm -rf ./vendor - -# Scientific Python for the agent's own scripts. -RUN pip install numpy==1.26.4 scipy==1.13.1 pandas==2.2.2 astropy==6.1.4 - -COPY terminal_desk ./terminal_desk -COPY openenv.yaml ./ - -# The server runs as root; agent commands run as nobody and cannot read the -# generators, the grader or the server's memory. -RUN chmod -R go-rwx /opt/terminal_desk && mkdir -p /app - -LABEL org.opencontainers.image.title="Skills Desk" \ - org.opencontainers.image.description="OpenEnv environment: multi-step tool-use tasks (evidence, computation, transformation, repair, constraints) served through the tbench2_env schema; forked from dnakhla/terminal-desk v2" \ - org.opencontainers.image.source="https://huggingface.co/datasets/Syndicate604/skills-desk" \ - org.opencontainers.image.licenses="Apache-2.0" - -EXPOSE 8000 -HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ - CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)" || exit 1 - -CMD ["uvicorn", "terminal_desk.server.app:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt b/components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt deleted file mode 100644 index 63f0f98e9ff56805df72c83b8ac4e27ae0009362..0000000000000000000000000000000000000000 --- a/components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt +++ /dev/null @@ -1,41 +0,0 @@ -# Skills Desk v1 training bank: 40 task ids, 8 per skill. Frozen 2026-10-18. -ev_backorder-L1 -ev_backorder-L2 -ev_calibration-L1 -cmp_channels-L1 -cmp_rainfall-L1 -cmp_rainfall-L2 -tx_contacts-L1 -tx_events-L1 -fix_toolkit-L1 -fix_report-L1 -plan_shifts-L1 -plan_shifts-L2 -plan_load-L1 -ev_deliveries-L1 -ev_badges-L1 -ev_dupes-L1 -ev_bankrec-L1 -ev_fixedin-L1 -cmp_meter-L1 -cmp_grades-L1 -cmp_fifo-L1 -cmp_smooth-L1 -cmp_loan-L1 -tx_xml-L1 -tx_pivot-L1 -tx_mdtable-L1 -tx_sessions-L1 -tx_fixedwidth-L1 -tx_dates-L1 -fix_paginate-L1 -fix_logline-L1 -fix_units-L1 -fix_bizdays-L1 -fix_dedupe-L1 -fix_mergelogs-L1 -plan_roster_fix-L1 -plan_roster_fill-L1 -plan_courses-L1 -plan_disks-L1 -plan_delivery-L1 diff --git a/components/skillsdesk/runtime/common/__init__.py b/components/skillsdesk/runtime/common/__init__.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/components/skillsdesk/runtime/common/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/components/skillsdesk/runtime/common/contracts.py b/components/skillsdesk/runtime/common/contracts.py deleted file mode 100644 index b33d03fd3c21f3b117be3a4664274c109ac6fa9d..0000000000000000000000000000000000000000 --- a/components/skillsdesk/runtime/common/contracts.py +++ /dev/null @@ -1,7 +0,0 @@ - -from copy import deepcopy - -ACTION_SCHEMA = {'type': 'object', 'description': 'Return one action object per reply, then wait for its observation. To finish, send {"op":"finish"}. A command is a JSON string: encode newlines as \\n and internal double quotes as \\". Do not wrap the object in prose, Markdown, or tags.', 'examples': [{'op': 'finish'}], 'oneOf': [{'properties': {'op': {'const': 'exec'}, 'command': {'type': 'string'}}, 'required': ['op', 'command'], 'additionalProperties': False}, {'properties': {'op': {'const': 'call'}, 'tool': {'type': 'string'}, 'arguments': {'type': 'object'}}, 'required': ['op', 'tool', 'arguments'], 'additionalProperties': False}, {'properties': {'op': {'const': 'finish'}}, 'required': ['op'], 'additionalProperties': False}]} - -def observation_payload(task_id, message, data=None, reward=0.0, done=False): - return {"task_id": str(task_id), "message": str(message), "data": {} if data is None else data, "reward": reward, "done": bool(done), "metadata": {}} diff --git a/components/skillsdesk/runtime/common/models.py b/components/skillsdesk/runtime/common/models.py deleted file mode 100644 index 4d7bfa208b39f5e19d3e358c6d23c0f59041efad..0000000000000000000000000000000000000000 --- a/components/skillsdesk/runtime/common/models.py +++ /dev/null @@ -1,55 +0,0 @@ - -from copy import deepcopy -import math -from typing import Any, Literal -import jsonschema -from openenv.core.env_server.types import Action, Observation -from pydantic import ConfigDict, Field, model_serializer, model_validator -from pydantic_core import PydanticCustomError -from .contracts import ACTION_SCHEMA - - -class ArenaAction(Action): - model_config=ConfigDict(extra='forbid',frozen=True,validate_assignment=False) - op: Literal['exec', 'call', 'finish'] - command: str | None = None - tool: str | None = None - arguments: dict[str, Any] | None = None - - @model_validator(mode='before') - @classmethod - def exact_contract(cls, value): - if isinstance(value, cls): - return value - def finite(item): - if isinstance(item,float) and not math.isfinite(item): - raise PydanticCustomError('finite_number', 'Non-finite JSON number') - if isinstance(item,dict): - for part in item.values():finite(part) - elif isinstance(item,list): - for part in item:finite(part) - finite(value) - try: - jsonschema.Draft202012Validator(ACTION_SCHEMA).validate(value) - except jsonschema.ValidationError as exc: - raise PydanticCustomError('action_contract', '{message}', {'message': exc.message}) from exc - return value - - @classmethod - def __get_pydantic_json_schema__(cls, core_schema, handler): - return deepcopy(ACTION_SCHEMA) - - def action_payload(self): - if self.op=='exec':return {'op':'exec','command':self.command} - if self.op=='call':return {'op':'call','tool':self.tool,'arguments':self.arguments} - return {'op':'finish'} - - @model_serializer - def canonical_serialization(self): - return self.action_payload() - - -class ArenaObservation(Observation): - task_id: str = '' - message: str = '' - data: dict[str, Any] = Field(default_factory=dict) diff --git a/components/skillsdesk/runtime/skillsdesk_compat/__init__.py b/components/skillsdesk/runtime/skillsdesk_compat/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/components/skillsdesk/runtime/skillsdesk_compat/environment.py b/components/skillsdesk/runtime/skillsdesk_compat/environment.py deleted file mode 100644 index 5c65b3698ba104ada0511cc5ba68a8735f616ae8..0000000000000000000000000000000000000000 --- a/components/skillsdesk/runtime/skillsdesk_compat/environment.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Serve a fixed original Skills Desk task bank through the shared Arena contract.""" -import hashlib -import json -import math -import os -from pathlib import Path -from threading import RLock - -from openenv.core.env_server.interfaces import Environment -from openenv.core.env_server.types import EnvironmentMetadata, State -from common.models import ArenaAction, ArenaObservation - -SOURCE_ROOT = Path('/opt/terminal_desk') -MANIFEST_PATH = Path('/opt/skillsdesk_compat/SOURCE_MANIFEST.json') -MANIFEST = json.loads(MANIFEST_PATH.read_text()) -if MANIFEST['dataset'] != 'Syndicate604/skills-desk' or MANIFEST['revision'] != 'a785ccdc9784ed863d0ffecec826d72176c0a785': - raise RuntimeError('Unexpected original source identity') -for relative, digest in MANIFEST['original_files'].items(): - path = SOURCE_ROOT / relative - if (path.is_symlink() or not path.is_file() or not path.resolve().is_relative_to(SOURCE_ROOT.resolve()) - or hashlib.sha256(path.read_bytes()).hexdigest() != digest): - raise RuntimeError('Original source hash mismatch: ' + relative) -actual_python = {p.relative_to(SOURCE_ROOT).as_posix() for p in (SOURCE_ROOT / 'terminal_desk').rglob('*.py')} -if actual_python != {p for p in MANIFEST['original_files'] if p.endswith('.py')}: - raise RuntimeError('Original Python source inventory mismatch') - -from terminal_desk.core import shell -from terminal_desk.families import is_reserved, parse_task_id -from terminal_desk.models import Tbench2Action -from terminal_desk.server.environment import APP, MAX_CALLS, TerminalDeskEnvironment - -TASK_IDS = tuple(MANIFEST['selected_tasks']) -if len(TASK_IDS) != 20 or len(set(TASK_IDS)) != len(TASK_IDS): - raise RuntimeError('Invalid selected task registry') -for task_id in TASK_IDS: - family, level, instance = parse_task_id(task_id) - if is_reserved(task_id) or instance != 0 or task_id != f'{family}-L{level}': - raise RuntimeError('Invalid selected original instance') -if APP != '/app' or MAX_CALLS != 32 or shell.WALL_TIMEOUT_S != 20 or shell.CPU_SECONDS != 20: - raise RuntimeError('Original runtime configuration changed') - -PROTOCOL = ( - '\n\nTools: {"op":"exec","command":""}; ' - '{"op":"call","tool":"write_file","arguments":{"file_path":"","content":""}}; ' - '{"op":"call","tool":"evaluate","arguments":{}}. ' - 'Use {"op":"finish"} to grade the artifact and finish. There are at most 32 actions.' -) - - -class CompatEnvironment(Environment): - SUPPORTS_CONCURRENT_SESSIONS = False - - def __init__(self): - super().__init__() - if os.geteuid() != 0 or not shell.IS_ROOT or shell.NOBODY != 65534: - raise RuntimeError('The server must run as root with the original nobody tool identity') - self._lock = RLock() - self._original = TerminalDeskEnvironment(allow_seed=False) - self._task_id = None - self._actions = 0 - self._terminal = None - - def reset(self, *, task_id=None, seed=None, index=None, split='train', episode_id=None, **kwargs): - with self._lock: - if split != 'train': - raise ValueError('Unknown split') - if kwargs.get('allow_seed') not in (None, False): - raise ValueError('Production instance override is unavailable') - if index is not None: - if type(index) is not int or not 0 <= index < len(TASK_IDS): - raise ValueError('Invalid task index') - if task_id is not None and task_id != TASK_IDS[index]: - raise ValueError('Task selection mismatch') - task_id = TASK_IDS[index] - if task_id is None: - raise ValueError('reset needs task_id or task index') - if not isinstance(task_id, str) or task_id not in TASK_IDS: - raise ValueError('Unknown task') - if seed is not None and type(seed) is not int: - raise ValueError('Invalid seed') - parse_task_id(task_id) - if is_reserved(task_id): - raise ValueError('Unknown task') - self._task_id = None - self._actions = 0 - self._terminal = None - # The original fixed-instance environment ignores client seeds in production. - opening = self._original.reset(task_id=task_id, seed=seed, episode_id=episode_id) - self._task_id = task_id - return self._translate(opening, reset=True) - - def _translate(self, original, reset=False): - if original.done: - reward = original.reward - if isinstance(reward, bool) or not isinstance(reward, (int, float)) or not math.isfinite(reward) or reward not in (0, 1): - raise RuntimeError('Native terminal reward is not binary') - result = ArenaObservation( - task_id=self._task_id, - message=original.instruction + PROTOCOL if reset else original.output, - data={'task_path': original.task_path, 'success': original.success, 'error': original.error, - 'actions_used': self._actions, 'steps_left': max(0, MAX_CALLS - self._actions), - 'info': original.info}, - reward=original.reward, done=original.done, - ) - if original.done: - self._terminal = result.model_copy(deep=True) - return result - - def _finish(self): - return self._translate(self._original.step(Tbench2Action(action_type='evaluate'))) - - def step(self, action, timeout_s=None, **kwargs): - with self._lock: - if self._task_id is None: - raise ValueError('Reset before stepping') - if self._terminal is not None: - return self._terminal.model_copy(deep=True) - value = action.action_payload() if isinstance(action, ArenaAction) else ArenaAction.model_validate(action).action_payload() - self._actions += 1 - if value['op'] == 'finish': - return self._finish() - mapped = Tbench2Action(action_type='unsupported_adapter_call') - if value['op'] == 'exec': - mapped = Tbench2Action(action_type='exec', command=value['command']) - elif value['op'] == 'call': - tool, args = value['tool'], value['arguments'] - if tool in ('evaluate', 'finish', 'close') and not args: - return self._finish() - if (tool == 'write_file' and set(args) == {'file_path', 'content'} - and all(isinstance(args[key], str) for key in args)): - mapped = Tbench2Action(action_type='write_file', **args) - original = self._original.step(mapped, timeout_s=timeout_s) - if not original.done and self._actions >= MAX_CALLS: - return self._finish() - return self._translate(original) - - @property - def state(self): - with self._lock: - return State(episode_id=self._original.state.episode_id, step_count=self._actions) - - def close(self): - with self._lock: - # SDK metadata factories have no episode and must not stop another session's tools. - if self._task_id is not None: - self._original.close() - self._task_id = None - self._terminal = None - - def get_metadata(self): - return EnvironmentMetadata(name='skillsdesk_compat', version='1.0.0', - description='Original Skills Desk tasks with the shared Arena interface.') - - def list_splits(self): - return ['train'] - - def list_tasks(self, split): - if split != 'train': - raise ValueError('Unknown split') - return [{'id': name, 'index': i} for i, name in enumerate(TASK_IDS)] - - def num_tasks(self, split): - return len(self.list_tasks(split)) - - def get_task(self, split, index): - if type(index) is not int or not 0 <= index < len(TASK_IDS): - raise ValueError('Invalid task index') - return self.list_tasks(split)[index] - - def get_task_range(self, split, start=None, stop=None): - return self.list_tasks(split)[start:stop] diff --git a/components/skillsdesk/runtime/skillsdesk_compat/server.py b/components/skillsdesk/runtime/skillsdesk_compat/server.py deleted file mode 100644 index 28c0868ebeb1d341521e6615bc59345598d294b1..0000000000000000000000000000000000000000 --- a/components/skillsdesk/runtime/skillsdesk_compat/server.py +++ /dev/null @@ -1,15 +0,0 @@ -from openenv.core.env_server.http_server import create_app -from common.models import ArenaAction, ArenaObservation -from .environment import CompatEnvironment - -app = create_app(CompatEnvironment, ArenaAction, ArenaObservation, - env_name='skillsdesk_compat', max_concurrent_envs=1, mode='production') - - -def main(): - import uvicorn - uvicorn.run(app, host='0.0.0.0', port=8000, log_level='warning') - - -if __name__ == '__main__': - main() diff --git a/components/skillsdesk/upstream/openenv.yaml b/components/skillsdesk/upstream/openenv.yaml deleted file mode 100644 index af39ddb3932df8bd0290f895e06878d03a194b52..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/openenv.yaml +++ /dev/null @@ -1,23 +0,0 @@ -spec_version: 1 -name: skills_desk -version: 1.0.0 -type: space -runtime: fastapi -app: terminal_desk.server.app:app -port: 8000 -validation: - reward: - range: [0.0, 1.0] - oracle_tolerance: 0.0 - floor_margin: 0.1 - resources: - cpu: 1.0 - memory_mb: 2048 - disk_mb: 10240 - episode_timeout_s: 1500.0 - capabilities: - verifier: - kind: reward_channel - types: - tags: - - tool-use diff --git a/components/skillsdesk/upstream/terminal_desk/__init__.py b/components/skillsdesk/upstream/terminal_desk/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/components/skillsdesk/upstream/terminal_desk/core/__init__.py b/components/skillsdesk/upstream/terminal_desk/core/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/components/skillsdesk/upstream/terminal_desk/core/grading.py b/components/skillsdesk/upstream/terminal_desk/core/grading.py deleted file mode 100644 index 528a9f483cde82944f7197ec1c96575aad13fa21..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/core/grading.py +++ /dev/null @@ -1,298 +0,0 @@ -"""Check the one output file a task names. Reward is 1.0 when every check passes, else 0.0. - -Checks only parse: no file under /app is executed here. The sw_fix family runs its -hidden tests itself, as nobody, on a copy (see families/software.py). -""" - -import csv -import io -import json -import math -import os -import re -import time -import wave -from typing import Any - -from ..families.base import Artifact, Built, Field, FileContent - -MAX_ARTIFACT_BYTES = 4 * 1024**2 - - -def _norm_text(value: Any) -> str: - return " ".join(str(value).strip().split()).casefold() - - -def _as_list(value: Any) -> list | None: - if isinstance(value, list): - return value - if isinstance(value, str): - return [part for part in (p.strip() for p in value.split(",")) if part] - return None - - -def _as_number(value: Any) -> float | None: - if isinstance(value, bool): - return None - if isinstance(value, (int, float)): - return float(value) - if isinstance(value, str): - try: - return float(value.strip().replace(",", "")) - except ValueError: - return None - return None - - -def score_field(field: Field, value: Any, expected: Any) -> float: - if value is None: - return 0.0 - kind = field.kind - if kind == "int": - number = _as_number(value) - return float(number is not None and math.isfinite(number) and number == int(expected)) - if kind == "number": - number = _as_number(value) - if number is None or not math.isfinite(number): - return 0.0 - tol = max(field.tol, field.rel * abs(expected)) - return float(abs(number - expected) <= tol + 1e-12) - if kind == "text": - return float(_norm_text(value) == _norm_text(expected)) - if kind == "list": - items = _as_list(value) - if items is None: - return 0.0 - got = {_norm_text(x) for x in items} - return float(len(got) == len(items) and got == {_norm_text(x) for x in expected}) - raise ValueError(f"unknown field kind {kind!r}") - - -def read_artifact(app: str, path: str) -> bytes | None: - """The file's bytes, or None when it is missing, a symlink, not a regular file, - outside the app dir or over MAX_ARTIFACT_BYTES. lstat first so a FIFO or a link - planted at the path cannot hang or redirect the root-owned reader.""" - app_real = os.path.realpath(app) - full = os.path.join(app_real, path) - if os.path.commonpath([app_real, os.path.realpath(os.path.dirname(full))]) != app_real: - return None - try: - st = os.lstat(full) - except OSError: - return None - import stat - - if not stat.S_ISREG(st.st_mode) or st.st_size > MAX_ARTIFACT_BYTES: - return None - with open(full, "rb") as fh: - return fh.read(MAX_ARTIFACT_BYTES + 1) - - -def _text(data: bytes) -> str: - return data.decode("utf-8-sig", errors="replace").replace("\r\n", "\n") - - -def _fields_by_name(artifact: Artifact) -> dict[str, Field]: - return {f.name: f for f in artifact.fields} - - -def compare_json(artifact: Artifact, data: bytes) -> bool: - got = json.loads(_text(data)) - if not isinstance(got, dict) or set(got) != set(artifact.expected): - return False # exact key set, as the operator's verifiers check - fields = _fields_by_name(artifact) - for key, expected in artifact.expected.items(): - field = fields.get(key) or Field(key, "text") - if score_field(field, got.get(key), expected) != 1.0: - return False - return True - - -def _csv_rows(text: str) -> tuple[list[str], list[dict]]: - """Strict: a row with extra or missing fields makes the whole file fail (empty header).""" - from ..families.util import parse_csv_strict - - parsed = parse_csv_strict(text) - return parsed if parsed is not None else ([], []) - - -def compare_csv(artifact: Artifact, data: bytes) -> bool: - header, rows = _csv_rows(_text(data)) - fields = _fields_by_name(artifact) - columns = [f.name for f in artifact.fields] - if header != columns: - return False # the exact header the instruction shows - key = tuple(artifact.key) or tuple(columns[:1]) - if any(k not in header for k in key): - return False - - def row_key(row: dict) -> tuple: - return tuple(_norm_text(row.get(k, "")) for k in key) - - expected = {row_key({k: str(v) for k, v in r.items()}): r for r in artifact.expected} - got = {} - for row in rows: - k = row_key(row) - if k in got: - return False # duplicate key row - got[k] = row - if set(got) != set(expected): - return False - if artifact.ordered: - want = [row_key({k: str(v) for k, v in r.items()}) for r in artifact.expected] - if [row_key(r) for r in rows] != want: - return False - for k, want_row in expected.items(): - for column in columns: - if score_field(fields[column], got[k].get(column), want_row[column]) != 1.0: - return False - return True - - -def compare_lines(artifact: Artifact, data: bytes) -> bool: - lines = [_norm_text(ln) for ln in _text(data).split("\n") if ln.strip()] - want = [_norm_text(x) for x in artifact.expected] - if artifact.ordered: - return lines == want - return len(lines) == len(set(lines)) and set(lines) == set(want) - - -_SRT_TIME = re.compile(r"(\d+):(\d\d):(\d\d)[,.](\d{1,3})") - - -def _srt_ms(token: str) -> int: - m = _SRT_TIME.fullmatch(token.strip()) - if not m: - raise ValueError(token) - h, mi, s, ms = m.groups() - return ((int(h) * 60 + int(mi)) * 60 + int(s)) * 1000 + int(ms.ljust(3, "0")) - - -def parse_srt(text: str) -> list[tuple[int, int, str]]: - cues = [] - for block in re.split(r"\n\s*\n", text.strip()): - lines = [ln.rstrip() for ln in block.strip().split("\n")] - if len(lines) < 2: - raise ValueError("short cue") - if "-->" not in lines[0] and "-->" in lines[1]: - lines = lines[1:] - start, end = (t.strip() for t in lines[0].split("-->")) - cues.append((_srt_ms(start), _srt_ms(end), "\n".join(lines[1:]).strip())) - return cues - - -def compare_srt(artifact: Artifact, data: bytes) -> bool: - got = parse_srt(_text(data)) - want = artifact.expected - if len(got) != len(want): - return False - for (gs, ge, gt), (ws, we, wt) in zip(got, want): - if abs(gs - ws) > artifact.tol_ms or abs(ge - we) > artifact.tol_ms: - return False - if _norm_text(gt) != _norm_text(wt): - return False - return True - - -def compare_wav(artifact: Artifact, data: bytes) -> bool: - with wave.open(io.BytesIO(data)) as got, wave.open(io.BytesIO(artifact.expected)) as want: - if (got.getnchannels(), got.getsampwidth(), got.getframerate()) != ( - want.getnchannels(), - want.getsampwidth(), - want.getframerate(), - ): - return False - if got.getnframes() != want.getnframes(): - return False - return got.readframes(got.getnframes()) == want.readframes(want.getnframes()) - - -COMPARERS = { - "json": compare_json, - "csv": compare_csv, - "lines": compare_lines, - "srt": compare_srt, - "wav": compare_wav, -} - - -def _stem(path: str) -> str: - return re.sub(r"[^a-z0-9]+", "_", os.path.basename(path).rsplit(".", 1)[0].lower()).strip("_") or "artifact" - - -def verify(app: str, built: Built) -> tuple[float, dict[str, bool], str]: - """Run the checks for the task's artifact. Returns (reward, named results, pytest-style tail).""" - started = time.time() - artifact = built.artifact - stem = _stem(artifact.path) - results: dict[str, bool] = {} - if artifact.kind == "custom": - exists = read_artifact(app, artifact.path) is not None if artifact.path else True - results[f"test_{stem}_exists"] = exists - try: - results[f"test_{stem}_correct"] = bool(exists and artifact.verify(app)) - except Exception: - results[f"test_{stem}_correct"] = False - else: - data = read_artifact(app, artifact.path) - results[f"test_{stem}_exists"] = data is not None - try: - results[f"test_{stem}_correct"] = data is not None and bool(COMPARERS[artifact.kind](artifact, data)) - except Exception: - results[f"test_{stem}_correct"] = False - passed = sum(results.values()) - failed = len(results) - passed - elapsed = f"{time.time() - started:.2f}s" - lines = [f"FAILED tests/test_outputs.py::{name}" for name, ok in results.items() if not ok] - summary = f"{failed} failed, {passed} passed in {elapsed}" if failed else f"{passed} passed in {elapsed}" - return (1.0 if not failed else 0.0), results, "\n".join(lines + [summary]) - - -def render_artifact(artifact: Artifact) -> FileContent: - """Oracle content for tests and replay: what a perfect agent would write.""" - if artifact.render is not None: - return artifact.render() - kind = artifact.kind - if kind == "json": - return json.dumps(artifact.expected, indent=1) + "\n" - if kind == "csv": - columns = [f.name for f in artifact.fields] - out = io.StringIO() - writer = csv.DictWriter(out, fieldnames=columns, lineterminator="\n") - writer.writeheader() - for row in artifact.expected: - writer.writerow({c: row[c] for c in columns}) - return out.getvalue() - if kind == "lines": - return "\n".join(str(x) for x in artifact.expected) + "\n" - if kind == "srt": - blocks = [] - for i, (start, end, text) in enumerate(artifact.expected, 1): - blocks.append(f"{i}\n{_fmt_srt(start)} --> {_fmt_srt(end)}\n{text}") - return "\n\n".join(blocks) + "\n" - if kind == "wav": - return artifact.expected - raise ValueError(f"no renderer for {kind!r}; give the artifact a render callable") - - -def _fmt_srt(ms: int) -> str: - h, rem = divmod(ms, 3600_000) - m, rem = divmod(rem, 60_000) - s, ms = divmod(rem, 1000) - return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" - - -def oracle_actions(path: str, content) -> list: - """Actions that write an oracle artifact: write_file for text, chunked base64 through exec for bytes.""" - from ..models import Tbench2Action - - if isinstance(content, str): - return [Tbench2Action(action_type="write_file", file_path=path, content=content)] - import base64 - - b64 = base64.b64encode(content).decode() - acts = [Tbench2Action(action_type="exec", command=f'mkdir -p "$(dirname {path})" && : > {path}.b64')] - for i in range(0, len(b64), 60000): - acts.append(Tbench2Action(action_type="exec", command=f"printf %s {b64[i:i + 60000]} >> {path}.b64")) - acts.append(Tbench2Action(action_type="exec", command=f"base64 -d {path}.b64 > {path} && rm {path}.b64")) - return acts diff --git a/components/skillsdesk/upstream/terminal_desk/core/shell.py b/components/skillsdesk/upstream/terminal_desk/core/shell.py deleted file mode 100644 index 77a2083dcbfd59993817396f9a4e5d1fafadf310..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/core/shell.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Run one agent command in the episode workspace. - -The command runs as nobody when the server is root, so it cannot read the -server code, the generators or the answers held in server memory. Output goes -to a root-owned file so a runaway writer cannot fill server memory, and every -nobody process is killed after each command so nothing lingers between steps -or into grading. Network is not blocked; the sandbox is the outer boundary. -""" - -import os -import resource -import signal -import subprocess -import tempfile -import time - -WALL_TIMEOUT_S = 20 -CPU_SECONDS = 20 -MEMORY_BYTES = 2 * 1024**3 -FILE_BYTES = 20 * 1024**2 -MAX_PROCESSES = 256 -# A safety cap only. The operator's wrapper does not cut output; the arena's token budget -# ends an episode whose observation no longer fits, and that is the pressure to train under. -MAX_OUTPUT_CHARS = 60000 -NOBODY = 65534 - -IS_ROOT = os.geteuid() == 0 - - -def _limits() -> None: - resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) - resource.setrlimit(resource.RLIMIT_CPU, (CPU_SECONDS, CPU_SECONDS + 1)) - resource.setrlimit(resource.RLIMIT_AS, (MEMORY_BYTES, MEMORY_BYTES)) - resource.setrlimit(resource.RLIMIT_FSIZE, (FILE_BYTES, FILE_BYTES)) - resource.setrlimit(resource.RLIMIT_NOFILE, (256, 256)) - if IS_ROOT: - resource.setrlimit(resource.RLIMIT_NPROC, (MAX_PROCESSES, MAX_PROCESSES)) - os.setgroups([]) - os.setgid(NOBODY) - os.setuid(NOBODY) - - -def kill_nobody() -> None: - """SIGKILL every process owned by nobody (no-op unless root).""" - if not IS_ROOT: - return - for _ in range(3): - found = False - for pid in os.listdir("/proc"): - if not pid.isdigit(): - continue - try: - if os.stat(f"/proc/{pid}").st_uid == NOBODY: - os.kill(int(pid), signal.SIGKILL) - found = True - except (FileNotFoundError, ProcessLookupError, PermissionError): - pass - if not found: - return - time.sleep(0.05) - - -def give_to_nobody(path: str) -> None: - if not IS_ROOT: - return - for dirpath, dirnames, filenames in os.walk(path): - os.chown(dirpath, NOBODY, NOBODY) - for name in filenames: - os.chown(os.path.join(dirpath, name), NOBODY, NOBODY) - - -def cut(text: str, limit: int = MAX_OUTPUT_CHARS) -> str: - if len(text) <= limit: - return text - head = int(limit * 0.75) - tail = limit - head - return f"{text[:head]}\n...[{len(text) - limit} characters cut]...\n{text[-tail:]}" - - -def run(argv: list[str], cwd: str, stdin_text: str | None = None) -> tuple[int, str]: - """Run argv as nobody in cwd. Returns (exit code, combined output, uncut).""" - env = { - "PATH": "/usr/local/bin:/usr/bin:/bin", - "HOME": cwd, - "LANG": "C.UTF-8", - "TERM": "dumb", - "PYTHONDONTWRITEBYTECODE": "1", - } - with tempfile.TemporaryFile() as sink: - proc = subprocess.Popen( - argv, - cwd=cwd, - env=env, - stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL, - stdout=sink, - stderr=subprocess.STDOUT, - preexec_fn=_limits, - start_new_session=True, - ) - timed_out = False - try: - proc.communicate( - input=stdin_text.encode() if stdin_text is not None else None, - timeout=WALL_TIMEOUT_S, - ) - except subprocess.TimeoutExpired: - timed_out = True - finally: - try: - os.killpg(proc.pid, signal.SIGKILL) - except ProcessLookupError: - pass - proc.wait() - kill_nobody() - sink.seek(0) - raw = sink.read(4 * 1024**2) - text = raw.decode("utf-8", errors="replace") - code = proc.returncode - if timed_out: - text += f"\n[stopped: {WALL_TIMEOUT_S} s time limit]" - code = 124 - elif code == -signal.SIGXCPU: - text += f"\n[stopped: {CPU_SECONDS} s CPU limit]" - elif code == -signal.SIGXFSZ: - text += "\n[stopped: file size limit (20 MB)]" - return code, text - - -def run_command(cmd: str, cwd: str) -> tuple[int, str]: - code, text = run(["/bin/bash", "-c", cmd], cwd) - text = text.rstrip("\n") - return code, cut(text) if text else "" - - -def write_file(path: str, content: str, cwd: str) -> tuple[int, str]: - """Write content to path (relative to cwd unless absolute) as nobody, creating parents. - Running as nobody is the path check: the server tree and system files are not writable.""" - script = 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"' - return run(["/bin/sh", "-c", script, "sh", path], cwd, stdin_text=content) diff --git a/components/skillsdesk/upstream/terminal_desk/families/__init__.py b/components/skillsdesk/upstream/terminal_desk/families/__init__.py deleted file mode 100644 index f1a07aadb92efc8d546ca1219c99ddd010511f94..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Registry of task families. A task id is '-L' or '-L-i', -e.g. 'ev_backorder-L1' or 'ev_backorder-L1-i3'. Each task id is one fixed problem (see instance_seed).""" - -import hashlib - -from . import compute, compute2, constraints, constraints2, evidence, evidence2, repair, repair2, transform, transform2 -from .base import Family - -FAMILIES: dict[str, Family] = { - f.id: f - for module in (evidence, compute, transform, repair, constraints, - evidence2, compute2, transform2, repair2, constraints2) - for f in module.FAMILIES -} - -# Changing the salt changes every fixed instance; bump it only with a new release. -INSTANCE_SALT = "skills-desk-pilot" - - -def parse_task_id(task_id: str) -> tuple[str, int, int]: - """(family id, level, instance). The instance defaults to 0.""" - base, instance = task_id, 0 - head, sep, tail = task_id.rpartition("-i") - if sep and tail.isdigit(): - base, instance = head, int(tail) - family_id, _, level = base.rpartition("-L") - if family_id not in ALL_FAMILIES or not level.isdigit() or int(level) not in ALL_FAMILIES[family_id].levels: - raise ValueError(f"unknown task_id {task_id!r}") - return family_id, int(level), instance - - -def instance_seed(task_id: str) -> int: - """The fixed seed of a task id: every reset of the same id builds the same problem, so a GRPO - group compares answers to one question rather than to different questions.""" - family_id, level, instance = parse_task_id(task_id) - salt = RESERVED_SALT if family_id in RESERVED else INSTANCE_SALT - key = f"{salt}:{family_id}-L{level}-i{instance}".encode() - return int.from_bytes(hashlib.sha256(key).digest()[:8], "big") - - -def all_task_ids() -> list[str]: - """Training task ids only. Reserved evaluation tasks are listed by reserved_task_ids().""" - return [f"{fid}-L{lv}" for fid, fam in FAMILIES.items() for lv in fam.levels] - - -def reserved_task_ids() -> list[str]: - return [f"{fid}-L{lv}" for fid, fam in RESERVED.items() for lv in fam.levels] - - -def is_reserved(task_id: str) -> bool: - return parse_task_id(task_id)[0] in RESERVED - - -# Reserved evaluation tasks: served by the same environment so a checkpoint can be evaluated on -# them, but never part of a training task list or of difficulty-based selection (see -# tools/make_submission.py). Their own salt keeps their instances independent of training ids. -from ..reserved import RESERVED # noqa: E402 - -RESERVED_SALT = "skills-desk-reserved-v1" -ALL_FAMILIES: dict[str, Family] = {**FAMILIES, **RESERVED} -assert not set(FAMILIES) & set(RESERVED) diff --git a/components/skillsdesk/upstream/terminal_desk/families/base.py b/components/skillsdesk/upstream/terminal_desk/families/base.py deleted file mode 100644 index 397007ad2bc27a44e7ff6f7766280967e5765125..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/base.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Shared types for task families. - -A family builds one instance per reset from a random generator: the task -instruction, the workspace files and the one output file the verifier checks. -The expected content stays in server memory; only the input files reach /app. -""" - -import random -from dataclasses import dataclass, field -from typing import Any, Callable, Union - -FileContent = Union[str, bytes] - - -@dataclass -class Field: - """One compared value: a JSON key or a CSV column. kind: int, number, text.""" - - name: str - kind: str - desc: str = "" - tol: float = 0.0 - rel: float = 0.0 - - -@dataclass -class Artifact: - """The file the agent must produce, and how it is checked (all or nothing). - - path: relative to /app, e.g. "report/schedule.csv". - kind: json | csv | lines | srt | wav | custom. - expected: json -> dict; csv -> list of row dicts; lines -> list of str; - srt -> list of (start_ms, end_ms, text); wav -> bytes; custom -> unused. - fields: json/csv comparers per key or column (reuse Field tolerances). - key: csv key column(s); rows are matched by key. ordered: csv/lines keep order. - verify: custom check, app dir -> bool. render: oracle content for wav/custom. - """ - - path: str - kind: str - expected: Any = None - fields: list = field(default_factory=list) - key: tuple = () - ordered: bool = False - tol_ms: int = 1 - verify: Callable[[str], bool] | None = None - render: Callable[[], FileContent] | None = None - - -@dataclass -class Built: - instruction: str # TB2 style, at most 700 characters; names the output path under /app - files: dict[str, FileContent] - artifact: Artifact - notes: dict = field(default_factory=dict) - - -@dataclass -class Family: - id: str - domain: str - title: str - build: Callable[[int, random.Random], Built] - levels: tuple = (1, 2, 3) - - -def money(x: float) -> str: - return f"{x:.2f}" diff --git a/components/skillsdesk/upstream/terminal_desk/families/compute.py b/components/skillsdesk/upstream/terminal_desk/families/compute.py deleted file mode 100644 index 5ca9e1f13a9be33c026af487476781860fc86b35..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/compute.py +++ /dev/null @@ -1,231 +0,0 @@ -"""Compute from data: grouped statistics, weighted means, unit conversions, stated rounding.""" - -import random - -from .base import Artifact, Built, Family -from .util import load_csv, to_csv - - -def _num(text: str) -> float | None: - try: - return float(text.replace(",", "")) - except ValueError: - return None - - -def _check_table(app, path, header, want: dict, tols: dict) -> bool: - """want: key (first column) -> {column: number}. Every key once, numbers within tolerance.""" - got = load_csv(app, path) - if got is None or got[0] != header: - return False - seen = {} - for row in got[1]: - key = row.get(header[0], "") - if key in seen: - return False - seen[key] = row - if set(seen) != set(want): - return False - for key, cols in want.items(): - for col, value in cols.items(): - n = _num(seen[key].get(col, "")) - if n is None or abs(n - value) > tols[col] + 1e-9: - return False - return True - - -# ---------------------------------------------------------------- cmp_channels (media) - -CHANNELS = ["field-notes", "studio-live", "kitchen-lab", "night-shift", "map-room"] - - -def _clock(seconds: int) -> str: - h, rem = divmod(seconds, 3600) - m, s = divmod(rem, 60) - return f"{h}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}" - - -def build_channels(level: int, rng: random.Random) -> Built: - chans = rng.sample(CHANNELS, 3) - rows = [] - for i in range(13): - ch = chans[i % 3] - secs = rng.randint(4 * 60, 95 * 60) - views = rng.randint(800, 60000) - rows.append([f"V{rng.randint(10000, 99999)}", ch, secs, views]) - for r in rng.sample(rows, 2): - r[3] = None # views not reported yet - rng.shuffle(rows) - want = {} - for ch in chans: - mine = [r for r in rows if r[1] == ch] - total_h = round(sum(r[2] for r in mine) / 3600, 2) - counted = [r for r in mine if r[3] is not None] - wm = round(sum(r[2] / 60 * r[3] for r in counted) / sum(r[3] for r in counted), 2) - want[ch] = {"total_hours": total_h, "weighted_minutes": wm} - files = {"videos.csv": to_csv(["video_id", "channel", "duration", "views"], - [[r[0], r[1], _clock(r[2]), "" if r[3] is None else f"{r[3]:,}"] for r in rows])} - header = ["channel", "total_hours", "weighted_minutes"] - - def verify(app: str) -> bool: - return _check_table(app, "channel_stats.csv", header, want, {"total_hours": 0.011, "weighted_minutes": 0.011}) - - instruction = ( - "Summarise /app/videos.csv per channel. duration is H:MM:SS or MM:SS; views may use thousands " - "separators and is blank when not yet reported. Write /app/channel_stats.csv with header " - "channel,total_hours,weighted_minutes and one row per channel: total_hours is the summed duration of all " - "the channel's videos in hours, weighted_minutes is the view-weighted mean duration in minutes over the " - "videos that have views. Round both to 2 decimals." - ) - oracle = to_csv(header, [[c, f"{v['total_hours']:.2f}", f"{v['weighted_minutes']:.2f}"] for c, v in want.items()]) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="channel_stats.csv", kind="custom", verify=verify, render=lambda: oracle), - notes={"expected": want}) - - -# ---------------------------------------------------------------- cmp_rainfall (science, units) - -TO_MM = {"mm": 1.0, "cm": 10.0, "in": 25.4} -STATIONS = ["ridge", "harbor", "orchard", "quarry", "delta"] - - -def _rain_summary(stations, latest, scale_on=None, rejected=frozenset()): - """latest: (station, date) -> mm. scale_on(station, date) -> multiplier. None if a station - has no wet day.""" - want = {} - for st in stations: - vals = [v * (scale_on(s, d) if scale_on else 1.0) for (s, d), v in latest.items() - if s == st and (s, d) not in rejected] - wet = [v for v in vals if v > 0] - if not wet: - return None - total = sum(vals) - want[st] = {"total_mm": round(total, 1), "wet_days": len(wet), "mean_mm_per_wet_day": round(total / len(wet), 2), - "exact_total": total} - return want - - -def _rain_check(app: str, header, want) -> bool: - """Totals within half a unit of the exact value (either rounding of an exact half passes); the - mean may be computed from the exact or the rounded total.""" - got = load_csv(app, "rainfall.csv") - if got is None or got[0] != header or len(got[1]) != len(want): - return False - seen = set() - for row in got[1]: - w = want.get(row["station"]) - try: - total, wet, mean = float(row["total_mm"]), float(row["wet_days"]), float(row["mean_mm_per_wet_day"]) - except ValueError: - return False - if w is None or row["station"] in seen or wet != w["wet_days"]: - return False - exact = w["exact_total"] - if abs(total - exact) > 0.05 + 1e-6 or abs(mean - exact / wet) > 0.005 + 0.05 / wet + 1e-6: - return False - seen.add(row["station"]) - return seen == set(want) - - -def _rain_differs(a, b) -> bool: - return any(abs(a[s]["total_mm"] - b[s]["total_mm"]) > 0.051 or a[s]["wet_days"] != b[s]["wet_days"] - or abs(a[s]["mean_mm_per_wet_day"] - b[s]["mean_mm_per_wet_day"]) > 0.011 for s in a) - - -def build_rainfall(level: int, rng: random.Random) -> Built: - """L1: unit conversion and corrections. L2 adds a gauge replaced mid-week (a new calibration - scale from its install date) and QC decisions that reject some days' readings.""" - while True: - stations = rng.sample(STATIONS, 3) - rows = [] - for st in stations: - for day in range(1, 8): - if rng.random() < 0.35: - mm = 0.0 - else: - mm = rng.uniform(0.4, 30) - unit = rng.choice(["mm", "mm", "cm", "in"]) - amount = round(mm / TO_MM[unit], 2) - rows.append([st, f"2026-04-{day:02d}", amount, unit]) - rng.shuffle(rows) - # Corrections: a later row for the same station and date replaces the earlier one. - for r in rng.sample(rows, 3): - unit = rng.choice(["mm", "cm", "in"]) - rows.append([r[0], r[1], round(rng.uniform(0.0, 25) / TO_MM[unit], 2), unit]) - latest = {} - for r in rows: - latest[(r[0], r[1])] = r[2] * TO_MM[r[3]] - if level == 1: - want = _rain_summary(stations, latest) - if want is not None: - break - continue - # L2: replacement gauges and QC rejections, drawn after the L1 draws. - replaced = rng.sample(stations, rng.randint(1, 2)) - gauges = [[st, "2026-04-01", "1.00"] for st in stations] - installs = {} - for st in replaced: - day = f"2026-04-{rng.randint(3, 6):02d}" - scale = rng.choice([0.88, 0.92, 1.06, 1.12]) - installs[st] = (day, scale) - gauges.append([st, day, f"{scale:.2f}"]) - rng.shuffle(gauges) - wet_keys = [k for k, v in latest.items() if v > 0] - rejected = set(map(tuple, rng.sample(wet_keys, 2))) - kept = [k for k in latest if k not in rejected] - qc = [[s, d, "reject"] for s, d in sorted(rejected)] + [[s, d, "ok"] for s, d in rng.sample(kept, 2)] # sorted: set order varies by process - rng.shuffle(qc) - - def scale_on(st, date, installs=installs): - return installs[st][1] if st in installs and date >= installs[st][0] else 1.0 - - def scale_all(st, date, installs=installs): - return installs[st][1] if st in installs else 1.0 - - want = _rain_summary(stations, latest, scale_on, rejected) - naive = [_rain_summary(stations, latest, None, rejected), _rain_summary(stations, latest, scale_on), - _rain_summary(stations, latest, scale_all, rejected)] - if want is not None and all(n is not None and _rain_differs(n, want) for n in naive): - break - files = {"readings.csv": to_csv(["station", "date", "amount", "unit"], [[r[0], r[1], f"{r[2]:g}", r[3]] for r in rows])} - header = ["station", "total_mm", "wet_days", "mean_mm_per_wet_day"] - - def verify(app: str) -> bool: - return _rain_check(app, header, want) - - if level == 1: - instruction = ( - "Gauge readings for one week are in /app/readings.csv (units mm, cm or in; 1 in = 25.4 mm). When a " - "station has more than one row for a date, the later row in the file is a correction and replaces the " - "earlier ones. Write /app/rainfall.csv with header station,total_mm,wet_days,mean_mm_per_wet_day and " - "one row per station: weekly total in mm (1 decimal), days with rain above 0 mm, and total divided by " - "wet days (2 decimals)." - ) - else: - files["gauges.csv"] = to_csv(["station", "installed", "scale"], gauges) - files["qc.csv"] = to_csv(["station", "date", "decision"], qc) - files["METHOD.md"] = ( - "# Weekly rainfall method\n\n" - "1. Convert every reading to mm (1 cm = 10 mm, 1 in = 25.4 mm).\n" - "2. If a station has several rows for one date, the last row in the file is a correction and replaces the rest.\n" - "3. Multiply each day's reading by the scale of the station's gauge in service that day: the gauges.csv\n" - " row with the latest `installed` date on or before it.\n" - "4. A day whose decision in qc.csv is `reject` has no valid reading: leave it out of the total and the wet days.\n" - ) - instruction = ( - "Compute weekly rainfall per station from /app/readings.csv, /app/gauges.csv and /app/qc.csv following " - "/app/METHOD.md. Write /app/rainfall.csv with header station,total_mm,wet_days,mean_mm_per_wet_day and " - "one row per station: total in mm (1 decimal), days with a valid reading above 0 mm, and total divided " - "by those wet days (2 decimals)." - ) - oracle = to_csv(header, [[s, f"{v['total_mm']:.1f}", v["wet_days"], f"{v['mean_mm_per_wet_day']:.2f}"] - for s, v in want.items()]) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="rainfall.csv", kind="custom", verify=verify, render=lambda: oracle), - notes={"expected": want}) - - -FAMILIES = [ - Family("cmp_channels", "media", "Per-channel runtime and view-weighted duration", build_channels, (1,)), - Family("cmp_rainfall", "science", "Weekly rainfall with unit conversion and corrections", build_rainfall, (1, 2)), -] diff --git a/components/skillsdesk/upstream/terminal_desk/families/compute2.py b/components/skillsdesk/upstream/terminal_desk/families/compute2.py deleted file mode 100644 index 642b557da7840a75bcda1c61713bb26d7443b852..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/compute2.py +++ /dev/null @@ -1,241 +0,0 @@ -"""Compute from data, second batch: cumulative meters with a rollover, course grades, FIFO cost, -smoothed sensor exceedances and a loan schedule. Where a task states a rounding rule the grader -holds to it; where it does not, any correct rounding of the exact value passes.""" - -import json -import random -from decimal import ROUND_HALF_UP, Decimal - -from .base import Artifact, Built, Family -from .util import json_equal, load_csv, load_json, to_csv - -# ---------------------------------------------------------------- cmp_meter - -def build_meter(level: int, rng: random.Random) -> Built: - while True: - meters, rows, want = rng.sample(["M-A1", "M-B7", "M-C3", "M-D9"], 2), [], {} - for k, m in enumerate(meters): - reading = rng.randint(97500, 99500) if k == 0 else rng.randint(10000, 80000) # the first meter wraps - daily = {} - for day in range(1, 8): - if day > 1: - daily[day] = rng.randint(120, 900) - reading = (reading + daily[day]) % 100000 - rows.append([m, f"2026-02-{day:02d}T23:59", f"{reading:05d}"]) - peak = max(daily.values()) - want[m] = {"total_kwh": sum(daily.values()), - "peak_day": f"2026-02-{max(daily, key=daily.get):02d}" if list(daily.values()).count(peak) == 1 else None} - wrapped = any(int(a[2]) > int(b[2]) for a, b in zip(rows, rows[1:]) if a[0] == b[0] == meters[0]) - if wrapped and all(w["peak_day"] for w in want.values()): - break - rng.shuffle(rows) - files = {"readings.csv": to_csv(["meter", "read_at", "register_kwh"], rows), - "NOTE.txt": "Registers are 5 digits and wrap from 99999 back to 00000. Each reading is taken at the end of its day.\n"} - - def verify(app: str) -> bool: - return json_equal(load_json(app, "usage.json"), want) - - instruction = ( - "Each meter in /app/readings.csv has one end-of-day register reading per day (see /app/NOTE.txt). A day's " - "usage is that day's reading minus the previous day's, so the first day has no usage. Write /app/usage.json " - "as {meter: {\"total_kwh\": integer, \"peak_day\": \"YYYY-MM-DD\" of the highest daily usage}}." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="usage.json", kind="custom", verify=verify, - render=lambda: json.dumps(want) + "\n"), - notes={"expected": want}) - - -# ---------------------------------------------------------------- cmp_grades - -def build_grades(level: int, rng: random.Random) -> Built: - students = rng.sample(["ana", "ben", "cho", "dev", "eva", "fox", "gil"], 5) - rows, exact = [], {} - for s in students: - quizzes = [rng.randint(40, 100) for _ in range(4)] - hw_scores = [rng.randint(50, 100) for _ in range(3)] - hw_late = [rng.randint(0, 3) if rng.random() < 0.35 else 0 for _ in range(3)] - exam = rng.randint(45, 100) - for i, q in enumerate(quizzes): - rows.append([s, f"quiz{i + 1}", q, 0]) - for i, (h, late) in enumerate(zip(hw_scores, hw_late)): - rows.append([s, f"hw{i + 1}", h, late]) - rows.append([s, "exam", exam, 0]) - q = sum(sorted(quizzes)[1:]) / 3 - hw = sum(max(0, h - 10 * late) for h, late in zip(hw_scores, hw_late)) / 3 - exact[s] = 0.3 * q + 0.3 * hw + 0.4 * exam - rng.shuffle(rows) - files = {"scores.csv": to_csv(["student", "item", "score", "days_late"], rows), - "SYLLABUS.md": ("Final grade = 30% quiz average (drop each student's lowest quiz) + 30% homework average + " - "40% exam. Homework loses 10 points per day late, never below 0. All scores are out of 100.\n")} - header = ["student", "final"] - - def verify(app: str) -> bool: - got = load_csv(app, "finals.csv") - if got is None or got[0] != header or len(got[1]) != len(exact): - return False - try: - seen = {r["student"]: float(r["final"]) for r in got[1]} - except ValueError: - return False - return set(seen) == set(exact) and all(abs(seen[s] - v) <= 0.05 + 1e-6 for s, v in exact.items()) - - instruction = ( - "Compute final grades from /app/scores.csv using the rules in /app/SYLLABUS.md. Write /app/finals.csv with " - "header student,final and one row per student, final rounded to 1 decimal." - ) - oracle = to_csv(header, [[s, f"{v:.1f}"] for s, v in exact.items()]) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="finals.csv", kind="custom", verify=verify, render=lambda: oracle), - notes={"expected": exact}) - - -# ---------------------------------------------------------------- cmp_fifo - -def build_fifo(level: int, rng: random.Random) -> Built: - while True: - events, lots, cogs, spanned = [], [], 0, False - on_hand = 0 - for day in range(1, 13): - if rng.random() < 0.45 or on_hand < 10: - qty, cost = rng.randint(10, 40), rng.randint(300, 900) # cents per unit - events.append([f"2026-03-{day:02d}", "buy", qty, f"{cost / 100:.2f}"]) - lots.append([qty, cost]) - on_hand += qty - else: - qty = rng.randint(5, min(on_hand, 35)) - events.append([f"2026-03-{day:02d}", "sell", qty, ""]) - on_hand -= qty - left = qty - spanned |= qty > lots[0][0] - while left: - take = min(left, lots[0][0]) - cogs += take * lots[0][1] - lots[0][0] -= take - left -= take - if lots[0][0] == 0: - lots.pop(0) - sells = sum(e[1] == "sell" for e in events) - if sells >= 3 and spanned: - break - want = {"cogs": cogs / 100, "units_on_hand": on_hand, "inventory_value": sum(q * c for q, c in lots) / 100} - files = {"movements.csv": to_csv(["date", "type", "qty", "unit_cost"], events)} - - def verify(app: str) -> bool: - got = load_json(app, "fifo.json") - if not isinstance(got, dict) or set(got) != set(want): - return False - return (json_equal(got["units_on_hand"], want["units_on_hand"]) and json_equal(got["cogs"], want["cogs"], 0.005) - and json_equal(got["inventory_value"], want["inventory_value"], 0.005)) - - instruction = ( - "Value the stock movements in /app/movements.csv first-in, first-out: each sale uses up the oldest remaining " - "purchased units first, at their purchase cost. Write /app/fifo.json as {\"cogs\": cost of all units sold, " - "\"units_on_hand\": integer, \"inventory_value\": cost of the units left}, money to 2 decimals." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="fifo.json", kind="custom", verify=verify, - render=lambda: json.dumps(want) + "\n"), - notes={"expected": want}) - - -# ---------------------------------------------------------------- cmp_smooth - -def build_smooth(level: int, rng: random.Random) -> Built: - while True: - sensors = rng.sample(["T1", "T2", "T3", "T4"], 3) - limit = rng.choice([60, 65, 70]) - rows, want = [], {} - for s in sensors: - vals = [round(rng.uniform(limit - 15, limit + 8), 1) for _ in range(12)] - for k in rng.sample(range(1, 11), 2): - vals[k] = round(limit + rng.uniform(20, 40), 1) # single-sample spikes - for i, v in enumerate(vals): - rows.append([s, i, v]) - med = [sorted(vals[i - 1:i + 2])[1] for i in range(1, len(vals) - 1)] - want[s] = sum(m > limit for m in med) - raw = {s: sum(r[2] > limit for r in rows if r[0] == s) for s in sensors} - if any(raw[s] != want[s] for s in sensors) and any(want.values()): - break - rows.sort(key=lambda r: (r[0], r[1])) - files = {"samples.csv": to_csv(["sensor", "seq", "temp_c"], rows), - "METHOD.md": (f"Smooth each sensor with a 3-sample rolling median: for every sample that has a neighbour on " - f"both sides (by seq), take the median of it and its two neighbours. The first and last samples " - f"get no smoothed value. Count smoothed values strictly above {limit} C.\n")} - - def verify(app: str) -> bool: - return json_equal(load_json(app, "exceedances.json"), want) - - instruction = ( - "Count temperature exceedances per sensor in /app/samples.csv after smoothing as described in /app/METHOD.md. " - "Write /app/exceedances.json as {sensor: count}." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="exceedances.json", kind="custom", verify=verify, - render=lambda: json.dumps(want) + "\n"), - notes={"expected": want}) - - -# ---------------------------------------------------------------- cmp_loan - -def _cents(x: Decimal) -> Decimal: - return x.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) - - -def build_loan(level: int, rng: random.Random) -> Built: - principal = Decimal(rng.randint(30, 400) * 100) - annual = Decimal(rng.choice(["4.8", "5.25", "6", "7.2", "3.9"])) - months = rng.choice([6, 9, 12]) - r = annual / Decimal(1200) - payment = _cents(principal * r / (1 - (1 + r) ** -months)) - balance, sched = principal, [] - for m in range(1, months + 1): - interest = _cents(balance * r) - pay = payment if m < months else balance + interest # last payment clears the balance - principal_part = pay - interest - balance -= principal_part - sched.append({"month": m, "payment": str(pay), "interest": str(interest), "balance": str(balance)}) - want = {"monthly_payment": str(payment), "total_interest": str(sum(Decimal(s["interest"]) for s in sched)), "schedule": sched} - files = {"loan.json": json.dumps({"principal": str(principal), "annual_rate_pct": str(annual), "months": months}) + "\n", - "RULES.md": ("Monthly rate = annual_rate_pct / 1200. Payment = principal * r / (1 - (1 + r)^-months), rounded " - "half up to cents. Each month: interest = balance * r rounded half up to cents; balance falls by " - "payment - interest. The final payment is whatever clears the balance (balance + interest), so the " - "last balance is exactly 0.00. Money values are strings with 2 decimals.\n")} - - def verify(app: str) -> bool: - got = load_json(app, "schedule.json") - if not isinstance(got, dict) or set(got) != set(want) or not isinstance(got["schedule"], list): - return False - try: - norm = lambda v: str(Decimal(str(v)).quantize(Decimal("0.01"))) # noqa: E731 - if norm(got["monthly_payment"]) != want["monthly_payment"] or norm(got["total_interest"]) != want["total_interest"]: - return False - if len(got["schedule"]) != months: - return False - for g, w in zip(got["schedule"], sched): - if set(g) != set(w) or int(g["month"]) != w["month"]: - return False - if any(norm(g[k]) != w[k] for k in ("payment", "interest", "balance")): - return False - except (ArithmeticError, ValueError, TypeError): - return False - return True - - instruction = ( - "Build the repayment schedule for the loan in /app/loan.json following /app/RULES.md exactly. Write " - "/app/schedule.json as {\"monthly_payment\": money, \"total_interest\": money, \"schedule\": [{\"month\": n, " - "\"payment\": money, \"interest\": money, \"balance\": money after that payment}, ...]}." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="schedule.json", kind="custom", verify=verify, - render=lambda: json.dumps(want, indent=1) + "\n"), - notes={"expected": want}) - - -FAMILIES = [ - Family("cmp_meter", "industrial", "Daily usage from wrapping meter registers", build_meter, (1,)), - Family("cmp_grades", "office", "Final grades with dropped quiz and late penalty", build_grades, (1,)), - Family("cmp_fifo", "finance", "FIFO cost of goods sold", build_fifo, (1,)), - Family("cmp_smooth", "science", "Exceedances after rolling-median smoothing", build_smooth, (1,)), - Family("cmp_loan", "finance", "Loan schedule with stated half-up rounding", build_loan, (1,)), -] diff --git a/components/skillsdesk/upstream/terminal_desk/families/constraints.py b/components/skillsdesk/upstream/terminal_desk/families/constraints.py deleted file mode 100644 index 677db7f604f01e9cec34883cbb478ecf7006c27d..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/constraints.py +++ /dev/null @@ -1,209 +0,0 @@ -"""Follow several constraints: build a roster or pick a load that satisfies every stated rule. - -Many answers can be correct, so the verifiers check the rules instead of one expected file. -""" - -import itertools -import json -import random - -from .base import Artifact, Built, Family -from .util import load_csv, load_json, to_csv - -# ---------------------------------------------------------------- plan_shifts (scheduling) - -PEOPLE = ["Ada", "Bram", "Cleo", "Dev", "Esme", "Femi", "Gus", "Hana", "Ines", "Jon"] -SKILLS = ["forklift", "first_aid", "cashier"] -DAYS = ["mon", "tue", "wed"] - - -def _solve_roster(shifts, staff, limit_greedy=False): - """Backtracking search; with limit_greedy, take the first eligible people in file order only.""" - load = {p: 0 for p in staff} - days = {p: set() for p in staff} - out = {} - - def ok(p, s): - st = staff[p] - return (s["skill"] in st["skills"] and s["id"] not in st["off"] and load[p] < st["max"] - and s["day"] not in days[p]) - - def place(i): - if i == len(shifts): - return True - s = shifts[i] - cands = [p for p in staff if ok(p, s)] - combos = [tuple(cands[: s["need"]])] if limit_greedy else itertools.combinations(cands, s["need"]) - for combo in combos: - if len(combo) < s["need"]: - continue - for p in combo: - load[p] += 1 - days[p].add(s["day"]) - out[s["id"]] = combo - if place(i + 1): - return True - for p in combo: - load[p] -= 1 - days[p].discard(s["day"]) - del out[s["id"]] - return False - - return dict(out) if place(0) else None - - -def build_shifts(level: int, rng: random.Random) -> Built: - """L1: three days, seven people. L2: the same rules on a smaller week (two days, five people).""" - n_people, days = (7, DAYS) if level == 1 else (5, DAYS[:2]) - for _ in range(500): - names = rng.sample(PEOPLE, n_people) - staff = {p: {"skills": set(rng.sample(SKILLS, rng.randint(1, 2))), "max": 0, "off": set()} for p in names} - shifts = [] - for d in days: - for part in ("early", "late"): - shifts.append({"id": f"{d}-{part}", "day": d, "skill": rng.choice(SKILLS), "need": rng.randint(1, 2)}) - for p in names: - staff[p]["max"] = 3 - plan = _solve_roster(shifts, staff) - if plan is None: - continue - worked = {p: [s for s, ps in plan.items() if p in ps] for p in names} - for p in names: - staff[p]["max"] = max(1, len(worked[p])) - free = [s["id"] for s in shifts if s["id"] not in worked[p]] - staff[p]["off"] = set(rng.sample(free, min(len(free), rng.randint(1, 3)))) - if _solve_roster(shifts, staff) is None or _solve_roster(shifts, staff, limit_greedy=True) is not None: - continue - break - else: - raise RuntimeError("no roster instance") - oracle = _solve_roster(shifts, staff) - files = { - "staff.csv": to_csv(["name", "skills", "max_shifts", "unavailable"], - [[p, ";".join(sorted(s["skills"])), s["max"], ";".join(sorted(s["off"]))] - for p, s in staff.items()]), - "shifts.csv": to_csv(["shift_id", "day", "needs_skill", "headcount"], - [[s["id"], s["day"], s["skill"], s["need"]] for s in shifts]), - "RULES.md": ("# Rostering rules\n\n" - "1. Every shift gets exactly `headcount` different people.\n" - "2. Everyone on a shift has the shift's `needs_skill`.\n" - "3. Nobody works a shift listed in their `unavailable` column.\n" - "4. Nobody works more than `max_shifts` shifts in total.\n" - "5. Nobody works two shifts on the same day.\n"), - } - header = ["shift_id", "staff"] - - def verify(app: str) -> bool: - got = load_csv(app, "roster.csv") - if got is None or got[0] != header: - return False - by_shift = {s["id"]: [] for s in shifts} - for row in got[1]: - sid, person = row.get("shift_id", ""), row.get("staff", "") - if sid not in by_shift or person not in staff: - return False - by_shift[sid].append(person) - load, days = {p: 0 for p in staff}, {p: [] for p in staff} - for s in shifts: - people = by_shift[s["id"]] - if len(people) != s["need"] or len(set(people)) != len(people): - return False - for p in people: - if s["skill"] not in staff[p]["skills"] or s["id"] in staff[p]["off"]: - return False - load[p] += 1 - days[p].append(s["day"]) - return all(load[p] <= staff[p]["max"] and len(days[p]) == len(set(days[p])) for p in staff) - - instruction = ( - "Build next week's roster. People are in /app/staff.csv (skills and unavailable shifts are separated by " - "';'), shifts in /app/shifts.csv, and every rule in /app/RULES.md must hold. Write /app/roster.csv with " - "header shift_id,staff and one row per person per shift. Any roster that satisfies every rule is accepted." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="roster.csv", kind="custom", verify=verify, - render=lambda: to_csv(header, [[s, p] for s, ps in oracle.items() for p in ps])), - notes={"oracle": oracle}) - - -# ---------------------------------------------------------------- plan_load (selection under rules) - -def build_load(level: int, rng: random.Random) -> Built: - while True: - items = [] - for i in range(11): - items.append({"id": f"P-{i + 1:02d}", "kg": rng.randint(2, 38), "value": rng.randint(15, 320), - "hazmat": rng.random() < 0.25, "priority": False}) - for it in rng.sample([x for x in items if not x["hazmat"]], 2): - it["priority"] = True - cap = int(sum(x["kg"] for x in items) * rng.uniform(0.35, 0.45)) - must = [x for x in items if x["priority"]] - base_kg = sum(x["kg"] for x in must) - if base_kg >= cap: - continue - pool = [x for x in items if not x["hazmat"] and not x["priority"]] - best, best_set = -1, None - for r in range(len(pool) + 1): - for combo in itertools.combinations(pool, r): - kg = base_kg + sum(x["kg"] for x in combo) - if kg <= cap: - v = sum(x["value"] for x in combo) - if v > best: - best, best_set = v, combo - # Greedy by value per kg must miss the optimum, so the task needs a real search. - greedy, kg = 0, base_kg - for x in sorted(pool, key=lambda x: -x["value"] / x["kg"]): - if kg + x["kg"] <= cap: - kg += x["kg"] - greedy += x["value"] - if greedy < best: - break - optimum = best + sum(x["value"] for x in must) - chosen = sorted(x["id"] for x in list(must) + list(best_set)) - by_id = {x["id"]: x for x in items} - rows = [[x["id"], x["kg"], x["value"], "yes" if x["hazmat"] else "no", "yes" if x["priority"] else "no"] - for x in items] - rng.shuffle(rows) - files = { - "items.csv": to_csv(["item_id", "weight_kg", "value", "hazmat", "priority"], rows), - "MANIFEST.md": (f"# Flight AX-{rng.randint(100, 999)}\n\nMode: air. Cargo capacity: {cap} kg.\n\n" - "- Hazmat items may not fly.\n- Every priority item must be loaded.\n" - "- Among loads that follow these rules, load the one with the greatest total value.\n"), - } - - def verify(app: str) -> bool: - got = load_json(app, "load.json") - if not isinstance(got, dict) or set(got) != {"items", "total_value", "total_weight_kg"}: - return False - ids = got["items"] - if not isinstance(ids, list) or not all(isinstance(i, str) for i in ids): - return False - if ids != sorted(ids) or len(set(ids)) != len(ids) or not set(ids) <= set(by_id): - return False - picked = [by_id[i] for i in ids] - kg = sum(x["kg"] for x in picked) - value = sum(x["value"] for x in picked) - if any(x["hazmat"] for x in picked) or not all(x["id"] in ids for x in must) or kg > cap: - return False - if value != optimum: - return False - tv, tw = got["total_value"], got["total_weight_kg"] - return (not isinstance(tv, bool) and isinstance(tv, (int, float)) and tv == value - and not isinstance(tw, bool) and isinstance(tw, (int, float)) and tw == kg) - - instruction = ( - "Choose the cargo for the flight described in /app/MANIFEST.md from /app/items.csv. Follow every rule in " - "the manifest. Write /app/load.json as exactly {\"items\": [item ids sorted ascending], \"total_value\": " - "number, \"total_weight_kg\": number} for the chosen load." - ) - oracle = {"items": chosen, "total_value": optimum, "total_weight_kg": sum(by_id[i]["kg"] for i in chosen)} - return Built(instruction=instruction, files=files, - artifact=Artifact(path="load.json", kind="custom", verify=verify, - render=lambda: json.dumps(oracle) + "\n"), - notes={"oracle": oracle, "capacity": cap}) - - -FAMILIES = [ - Family("plan_shifts", "office", "Weekly roster under skill, availability and load rules", build_shifts, (1, 2)), - Family("plan_load", "industrial", "Highest-value cargo under capacity and eligibility rules", build_load, (1,)), -] diff --git a/components/skillsdesk/upstream/terminal_desk/families/constraints2.py b/components/skillsdesk/upstream/terminal_desk/families/constraints2.py deleted file mode 100644 index 9edbd65687c33ced78950c1af1212668b03f3abd..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/constraints2.py +++ /dev/null @@ -1,310 +0,0 @@ -"""Follow several constraints, second batch. Two training-only stepping stones for the roster task -(repair a nearly correct roster; complete a partly assigned one), then course selection, packing -onto the fewest disks and delivery-day planning. Every grader checks the result against the rules; -no tool sequence is required.""" - -import csv -import io -import itertools -import json -import random - -from . import constraints -from .base import Artifact, Built, Family -from .util import load_csv, load_json, to_csv - - - -def _roster_inputs(rng: random.Random): - """Staff, shifts and a valid roster from the plan_shifts generator (three-day week).""" - built = constraints.build_shifts(1, rng) - staff = {r["name"]: {"skills": set(filter(None, r["skills"].split(";"))), "max": int(r["max_shifts"]), - "off": set(filter(None, r["unavailable"].split(";")))} - for r in csv.DictReader(io.StringIO(built.files["staff.csv"]))} - shifts = [{"id": r["shift_id"], "day": r["day"], "skill": r["needs_skill"], "need": int(r["headcount"])} - for r in csv.DictReader(io.StringIO(built.files["shifts.csv"]))] - return built.files, staff, shifts, built.notes["oracle"] - - -def _roster_ok(rows, staff, shifts) -> bool: - by_shift = {s["id"]: [] for s in shifts} - for sid, person in rows: - if sid not in by_shift or person not in staff: - return False - by_shift[sid].append(person) - load, days = {p: 0 for p in staff}, {p: [] for p in staff} - for s in shifts: - people = by_shift[s["id"]] - if len(people) != s["need"] or len(set(people)) != len(people): - return False - for p in people: - if s["skill"] not in staff[p]["skills"] or s["id"] in staff[p]["off"]: - return False - load[p] += 1 - days[p].append(s["day"]) - return all(load[p] <= staff[p]["max"] and len(days[p]) == len(set(days[p])) for p in staff) - - -def _violations(rows, staff, shifts) -> int: - """How many single rows break a per-row rule (skill, availability).""" - skill = {s["id"]: s["skill"] for s in shifts} - return sum(1 for sid, p in rows if skill[sid] not in staff[p]["skills"] or sid in staff[p]["off"]) - - -HEADER = ["shift_id", "staff"] - - -def _read_roster(app: str): - got = load_csv(app, "roster.csv") - if got is None or got[0] != HEADER: - return None - return [(r["shift_id"], r["staff"]) for r in got[1]] - - -# ---------------------------------------------------------------- plan_roster_fix (stepping stone) - -def build_roster_fix(level: int, rng: random.Random) -> Built: - while True: - files, staff, shifts, oracle = _roster_inputs(rng) - rows = [(s, p) for s, ps in oracle.items() for p in ps] - broken = list(rows) - k = rng.randrange(len(broken)) - sid = broken[k][0] - wrong = [p for p in staff if p not in oracle[sid] and - (next(s["skill"] for s in shifts if s["id"] == sid) not in staff[p]["skills"] or sid in staff[p]["off"])] - if not wrong: - continue - broken[k] = (sid, rng.choice(wrong)) - if not _roster_ok(broken, staff, shifts) and _violations(broken, staff, shifts) == 1: - break - files = dict(files) - files["roster.csv"] = to_csv(HEADER, [list(r) for r in broken]) - - def verify(app: str) -> bool: - got = _read_roster(app) - return got is not None and _roster_ok(got, staff, shifts) - - instruction = ( - "/app/roster.csv is a draft roster that breaks the rules in /app/RULES.md somewhere. People are in " - "/app/staff.csv (skills and unavailable shifts separated by ';') and shifts in /app/shifts.csv. Correct " - "/app/roster.csv in place so every rule holds (header shift_id,staff, one row per person per shift). Any " - "valid roster is accepted." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="roster.csv", kind="custom", verify=verify, - render=lambda: to_csv(HEADER, [list(r) for r in rows])), - notes={"oracle": oracle}) - - -# ---------------------------------------------------------------- plan_roster_fill (stepping stone) - -def build_roster_fill(level: int, rng: random.Random) -> Built: - files, staff, shifts, oracle = _roster_inputs(rng) - rows = [(s, p) for s, ps in oracle.items() for p in ps] - fixed = sorted(rng.sample(rows, max(1, len(rows) // 2))) - files = dict(files) - files["assigned.csv"] = to_csv(HEADER, [list(r) for r in fixed]) - - def verify(app: str) -> bool: - got = _read_roster(app) - return got is not None and set(fixed) <= set(got) and _roster_ok(got, staff, shifts) - - instruction = ( - "Finish next week's roster. /app/assigned.csv holds assignments already agreed; keep all of them and fill " - "the rest so every rule in /app/RULES.md holds, using /app/staff.csv (';'-separated skills and unavailable " - "shifts) and /app/shifts.csv. Write the complete roster to /app/roster.csv with header shift_id,staff." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="roster.csv", kind="custom", verify=verify, - render=lambda: to_csv(HEADER, [list(r) for r in rows])), - notes={"oracle": oracle, "fixed": fixed}) - - -# ---------------------------------------------------------------- plan_courses - -SLOTS = ["mon9", "mon11", "tue9", "tue14", "wed10", "thu9", "thu14", "fri11"] - - -def build_courses(level: int, rng: random.Random) -> Built: - while True: - codes = [f"{rng.choice(['MAT', 'BIO', 'CHE', 'PHY', 'STA'])}{rng.randint(100, 399)}" for _ in range(10)] - if len(set(codes)) < 10: - continue - done = set(rng.sample(codes, 3)) - courses = {} - for c in codes: - others = [x for x in codes if x != c] - courses[c] = {"credits": rng.choice([3, 4, 5]), "slot": rng.choice(SLOTS), - "prereq": sorted(rng.sample(others, rng.choice([0, 0, 1]))), "offered": rng.random() < 0.85} - required = [c for c in codes if c not in done and courses[c]["offered"]][:1] - lo, hi = 12, 17 - - def ok(sel): - sel = list(sel) - if any(c in done or not courses[c]["offered"] for c in sel): - return False - if any(not set(courses[c]["prereq"]) <= done for c in sel): - return False - if len({courses[c]["slot"] for c in sel}) != len(sel): - return False - return lo <= sum(courses[c]["credits"] for c in sel) <= hi and set(required) <= set(sel) - - options = [c for c in codes if c not in done] - valid = [sel for r in range(2, 6) for sel in itertools.combinations(options, r) if ok(sel)] - blocked = any(not set(courses[c]["prereq"]) <= done for c in options) - if 1 <= len(valid) <= 12 and blocked: - break - files = {"courses.csv": to_csv(["code", "credits", "slot", "prerequisites", "offered"], - [[c, v["credits"], v["slot"], ";".join(v["prereq"]), "yes" if v["offered"] else "no"] - for c, v in courses.items()]), - "transcript.txt": "Completed:\n" + "\n".join(sorted(done)) + "\n", - "PLAN_RULES.md": (f"- Take every course in required.txt.\n- Only courses offered this term that you have not " - f"completed.\n- Every prerequisite must already be completed (not taken this term).\n- No two " - f"courses in the same slot.\n- Total credits between {lo} and {hi} inclusive.\n"), - "required.txt": "\n".join(required) + "\n"} - - def verify(app: str) -> bool: - got = load_json(app, "plan.json") - if not isinstance(got, dict) or set(got) != {"courses"} or not isinstance(got["courses"], list): - return False - sel = got["courses"] - return all(isinstance(c, str) and c in courses for c in sel) and len(set(sel)) == len(sel) and ok(sel) - - instruction = ( - "Choose this term's courses from /app/courses.csv for a student whose completed courses are in " - "/app/transcript.txt, following every rule in /app/PLAN_RULES.md. Write /app/plan.json as {\"courses\": " - "[codes]}. Any selection that satisfies every rule is accepted." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="plan.json", kind="custom", verify=verify, - render=lambda: json.dumps({"courses": list(valid[0])}) + "\n"), - notes={"valid_selections": len(valid)}) - - -# ---------------------------------------------------------------- plan_disks - -def build_disks(level: int, rng: random.Random) -> Built: - while True: - cap = rng.choice([100, 120, 150]) - files_ = {f"{rng.choice(['raw', 'img', 'log', 'db'])}_{i}.tar": rng.randint(15, cap - 10) for i in range(8)} - names = list(files_) - best = None - for disks in range(1, 6): - for assign in itertools.product(range(disks), repeat=len(names)): - if len(set(assign)) != disks: - continue - load = [0] * disks - for n, d in zip(names, assign): - load[d] += files_[n] - if max(load) <= cap: - best = (disks, assign) - break - if best: - break - greedy, bins = 0, [] - for n in sorted(names, key=lambda n: files_[n]): # smallest first, first fit - for b in bins: - if sum(files_[x] for x in b) + files_[n] <= cap: - b.append(n) - break - else: - bins.append([n]) - if best and len(bins) > best[0]: - break - need, assign = best - oracle = {} - for n, d in zip(names, assign): - oracle.setdefault(f"disk{d + 1}", []).append(n) - files = {"archives.csv": to_csv(["file", "size_gb"], [[n, s] for n, s in files_.items()]), - "README.txt": f"Each backup disk holds {cap} GB. A file cannot be split across disks.\n"} - - def verify(app: str) -> bool: - got = load_json(app, "disks.json") - if not isinstance(got, dict) or len(got) != need: - return False - placed = [] - for disk, items in got.items(): - if not isinstance(items, list) or not items or any(i not in files_ for i in items): - return False - if sum(files_[i] for i in items) > cap: - return False - placed += items - return sorted(placed) == sorted(names) - - instruction = ( - "Pack the archive files in /app/archives.csv onto as few backup disks as possible (capacity in " - "/app/README.txt). Write /app/disks.json as {disk name: [file names]} with one entry per disk used; every " - "file exactly once." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="disks.json", kind="custom", verify=verify, - render=lambda: json.dumps(oracle) + "\n"), - notes={"disks_needed": need}) - - -# ---------------------------------------------------------------- plan_delivery - -DAYS = ["mon", "tue", "wed", "thu", "fri"] - - -def build_delivery(level: int, rng: random.Random) -> Built: - while True: - cap = {d: rng.choice([300, 400, 500]) for d in DAYS} - orders, plan, load = [], {}, {d: 0 for d in DAYS} - for i in range(10): - day = rng.choice(DAYS) - w = rng.randint(40, 180) - if load[day] + w > cap[day]: - continue - load[day] += w - deadline = DAYS[rng.randint(DAYS.index(day), 4)] - closed = sorted(rng.sample([d for d in DAYS if d != day], rng.randint(0, 2))) - oid = f"D{300 + i}" - orders.append({"id": oid, "kg": w, "deadline": deadline, "closed": closed}) - plan[oid] = day - if len(orders) < 8: - continue - # The easy answer (each order on its earliest open day) must overload some day. - early = {d: 0 for d in DAYS} - for o in orders: - first = next(d for d in DAYS if d not in o["closed"]) - early[first] += o["kg"] - if any(early[d] > cap[d] for d in DAYS): - break - files = {"orders.csv": to_csv(["order", "weight_kg", "deliver_by", "customer_closed"], - [[o["id"], o["kg"], o["deadline"], ";".join(o["closed"])] for o in orders]), - "van.json": json.dumps({"capacity_kg_per_day": cap}, indent=1) + "\n"} - by = {o["id"]: o for o in orders} - - def verify(app: str) -> bool: - got = load_csv(app, "delivery_plan.csv") - if got is None or got[0] != ["order", "day"] or len(got[1]) != len(orders): - return False - load_ = {d: 0 for d in DAYS} - seen = set() - for r in got[1]: - o, d = by.get(r["order"]), r["day"] - if o is None or r["order"] in seen or d not in DAYS or d in o["closed"] or DAYS.index(d) > DAYS.index(o["deadline"]): - return False - seen.add(r["order"]) - load_[d] += o["kg"] - return all(load_[d] <= cap[d] for d in DAYS) - - instruction = ( - "Plan this week's deliveries. Each order in /app/orders.csv must go out on one weekday (mon-fri) no later " - "than deliver_by and not on a day its customer is closed (';'-separated); the van's weight limit per day is " - "in /app/van.json. Write /app/delivery_plan.csv with header order,day. Any plan that follows every rule is accepted." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="delivery_plan.csv", kind="custom", verify=verify, - render=lambda: to_csv(["order", "day"], [[k, v] for k, v in plan.items()])), - notes={"oracle": plan}) - - -FAMILIES = [ - Family("plan_roster_fix", "office", "Correct a draft roster that breaks one rule", build_roster_fix, (1,)), - Family("plan_roster_fill", "office", "Complete a partly agreed roster", build_roster_fill, (1,)), - Family("plan_courses", "office", "Course selection under prerequisites, slots and credits", build_courses, (1,)), - Family("plan_disks", "software", "Pack archives onto the fewest disks", build_disks, (1,)), - Family("plan_delivery", "industrial", "Delivery days under deadlines, closures and capacity", build_delivery, (1,)), -] diff --git a/components/skillsdesk/upstream/terminal_desk/families/evidence.py b/components/skillsdesk/upstream/terminal_desk/families/evidence.py deleted file mode 100644 index 6c71c98d28c0d8aa528a47e2d7b402140d5ee0d0..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/evidence.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Find and combine evidence: read several files, join records by ID, report the exceptions.""" - -import datetime as dt -import json -import random - -from .base import Artifact, Built, Family -from .util import load_csv, load_json, to_csv - -# ---------------------------------------------------------------- ev_backorder (inventory) - -SKUS = ["BOLT-M6", "GASKET-40", "VALVE-12", "HOSE-3M", "CLAMP-20", "SEAL-8"] -WAREHOUSES = ["WH-EAST", "WH-WEST", "WH-NORTH"] - - -def _allocate(orders, stock, cancelled, by_time=True, receipts=(), receipts_at_start=False, aliases=None): - """Backordered order ids. Receipts become available at their arrival time (before an order - placed in the same minute) or, with receipts_at_start, before everything.""" - left = {w: dict(s) for w, s in stock.items()} - aliases = aliases or {} - events = [((("0000" if receipts_at_start else r["arrives"]), 0, ""), "receipt", r) for r in receipts] - seq = sorted(orders, key=lambda o: (o["placed"], o["id"])) if by_time else list(orders) - events += [((o["placed"], 1, o["id"]) if by_time else ("", 1, i), "order", o) for i, o in enumerate(seq)] - if by_time: - events.sort(key=lambda e: e[0]) - else: - events = [e for e in events if e[1] == "receipt"] + [e for e in events if e[1] == "order"] - back = [] - for _, kind, x in events: - if kind == "receipt": - left[x["wh"]][x["sku"]] = left[x["wh"]].get(x["sku"], 0) + x["qty"] - continue - if x["id"] in cancelled: - continue - sku = aliases.get(x["sku"], x["sku"]) - have = left[x["wh"]].get(sku, 0) - if have >= x["qty"]: - left[x["wh"]][sku] = have - x["qty"] - else: - back.append(x["id"]) - return sorted(back) - - -def _stamp(rng): - return f"2026-03-{rng.randint(2, 6):02d} {rng.randint(8, 17):02d}:{rng.choice([0, 15, 30, 45]):02d}" - - -def build_backorder(level: int, rng: random.Random) -> Built: - """L1: orders, stock, cancellations. L2 adds stock receipts that arrive during the week and - orders written with legacy SKU codes that map to current codes.""" - while True: - whs = rng.sample(WAREHOUSES, 2) - skus = rng.sample(SKUS, 4) - stock = {w: {s: rng.randint(4, 14) for s in skus} for w in whs} - legacy = {f"OLD-{s.split('-')[0][:3]}{rng.randint(10, 99)}": s for s in rng.sample(skus, 2)} if level >= 2 else {} - by_new = {v: k for k, v in legacy.items()} - orders = [] - for i in range(14): - # Draw order matches the pilot (L1) exactly; L2's extra draws come after. - o = {"id": f"O-{1001 + i}", "placed": _stamp(rng), "wh": rng.choice(whs), - "sku": rng.choice(skus), "qty": rng.randint(2, 9)} - if level >= 2 and o["sku"] in by_new and rng.random() < 0.6: - o["sku"] = by_new[o["sku"]] - orders.append(o) - rng.shuffle(orders) - cancelled = set(rng.sample([o["id"] for o in orders], 2)) - receipts = [] - if level >= 2: - for _ in range(3): - receipts.append({"wh": rng.choice(whs), "sku": rng.choice(skus), "qty": rng.randint(4, 10), - "arrives": _stamp(rng)}) - want = _allocate(orders, stock, cancelled, receipts=receipts, aliases=legacy) - naive = [ - _allocate(orders, stock, cancelled, by_time=False, receipts=receipts, aliases=legacy), - _allocate(orders, stock, set(), receipts=receipts, aliases=legacy), - ] - if level >= 2: - naive += [ - _allocate(orders, stock, cancelled, aliases=legacy), # ignores receipts - _allocate(orders, stock, cancelled, receipts=receipts, receipts_at_start=True, aliases=legacy), - _allocate(orders, stock, cancelled, receipts=receipts), # ignores legacy codes - ] - if 2 <= len(want) <= (5 if level == 1 else 6) and all(n != want for n in naive): - break - orders_csv = to_csv(["order_id", "placed", "warehouse", "sku", "qty"], - [[o["id"], o["placed"], o["wh"], o["sku"], o["qty"]] for o in orders]) - policy = ( - "# Allocation policy\n\n" - "- Orders are allocated in the order they were placed: earliest `placed` first, ties broken by order_id.\n" - "- Cancelled orders (listed in cancellations.txt) are ignored and take no stock.\n" - "- An order ships only if its warehouse still holds its full quantity of that SKU; there are no partial\n" - " shipments. Otherwise the order is backordered and takes nothing.\n" - "- Stock never moves between warehouses.\n" - ) - files = { - "orders.csv": orders_csv, - "stock.json": json.dumps(stock, indent=1) + "\n", - "cancellations.txt": "\n".join(sorted(cancelled)) + "\n", - } - if level >= 2: - policy += ( - "- Stock in receipts.csv becomes available at its `arrives` time; an order placed in the same minute\n" - " can use it, an earlier order cannot.\n" - "- Some orders still use retired SKU codes; sku_aliases.csv maps each to its current code.\n" - ) - files["receipts.csv"] = to_csv(["warehouse", "sku", "qty", "arrives"], - [[r["wh"], r["sku"], r["qty"], r["arrives"]] for r in receipts]) - files["sku_aliases.csv"] = to_csv(["old_sku", "current_sku"], [[k, v] for k, v in legacy.items()]) - files["POLICY.md"] = policy - - def verify(app: str) -> bool: - got = load_json(app, "backorders.json") - if not isinstance(got, dict) or set(got) != {"backordered"} or not isinstance(got["backordered"], list): - return False - items = got["backordered"] - return all(isinstance(x, str) for x in items) and len(items) == len(set(items)) and sorted(items) == want - - sources = ("opening stock per warehouse in /app/stock.json and cancellations in /app/cancellations.txt" - if level == 1 else - "opening stock in /app/stock.json, deliveries in /app/receipts.csv, cancellations in " - "/app/cancellations.txt and SKU renames in /app/sku_aliases.csv") - instruction = ( - f"Work out which orders are backordered today. The orders are in /app/orders.csv, {sources}; follow " - "the rules in /app/POLICY.md. Write /app/backorders.json as {\"backordered\": [order ids]} listing every " - "backordered order id, sorted ascending, and nothing else." - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="backorders.json", kind="custom", verify=verify, - render=lambda: json.dumps({"backordered": want}) + "\n"), - notes={"expected": want}, - ) - - -# ---------------------------------------------------------------- ev_calibration (lab) - -def _d(day: int) -> str: - return (dt.date(2026, 1, 1) + dt.timedelta(days=day)).isoformat() - - -def build_calibration(level: int, rng: random.Random) -> Built: - while True: - insts = [f"SPEC-{n:02d}" for n in rng.sample(range(1, 40), 5)] - windows = [] # (inst, from_day, to_day, status) - bare = insts[-1] # never calibrated - for inst in insts[:-1]: - start = rng.randint(0, 20) - for _ in range(rng.randint(1, 2)): - length = rng.randint(25, 45) - windows.append((inst, start, start + length, "active")) - start = start + length + rng.randint(3, 12) - revoked = rng.choice(range(len(windows))) - windows[revoked] = windows[revoked][:3] + ("revoked",) - runs = [] - for i in range(15): - inst = rng.choice(insts) - own = [w for w in windows if w[0] == inst] - pick = rng.random() - if own and pick < 0.25: - w = rng.choice(own) - day = rng.choice([w[1], w[2]]) # boundary day - elif own and pick < 0.45: - w = rng.choice(own) - day = w[2] + rng.randint(1, 3) # just after a window - else: - day = rng.randint(0, 110) - runs.append((f"S-{301 + i}", inst, day)) - - def valid(inst, day): - return any(w[0] == inst and w[3] == "active" and w[1] <= day <= w[2] for w in windows) - - bad = [(s, inst, _d(day)) for s, inst, day in runs if not valid(inst, day)] - boundary_ok = any(valid(inst, day) and any(w[0] == inst and day in (w[1], w[2]) for w in windows) - for _, inst, day in runs) - on_revoked = any(windows[revoked][0] == inst and windows[revoked][1] <= day <= windows[revoked][2] - for _, inst, day in runs) - on_bare = any(inst == bare for _, inst, _ in runs) - if 3 <= len(bad) <= 7 and boundary_ok and on_revoked and on_bare: - break - rng.shuffle(windows) - models = {i: rng.choice(["UV-2600", "FTIR-4100", "NIR-900"]) for i in insts} - files = { - "instruments.csv": to_csv(["instrument_id", "model"], [[i, models[i]] for i in sorted(insts)]), - "calibrations.csv": to_csv(["instrument_id", "valid_from", "valid_to", "status"], - [[w[0], _d(w[1]), _d(w[2]), w[3]] for w in windows]), - "runs.csv": to_csv(["sample_id", "instrument_id", "run_date", "absorbance"], - [[s, inst, _d(day), f"{rng.uniform(0.05, 1.9):.3f}"] for s, inst, day in runs]), - } - header = ["sample_id", "instrument_id", "run_date"] - want = {tuple(r) for r in bad} - - def verify(app: str) -> bool: - got = load_csv(app, "invalid_runs.csv") - if got is None or got[0] != header: - return False - rows = [tuple(r.get(h, "") for h in header) for r in got[1]] - return len(rows) == len(set(rows)) and set(rows) == want - - instruction = ( - "QA needs the sample runs that were measured on an instrument without a valid calibration. Runs are in " - "/app/runs.csv and calibration records in /app/calibrations.csv. A run is valid only when its run_date " - "falls inside an active calibration window of the same instrument (valid_from and valid_to inclusive). " - "Write every invalid run to /app/invalid_runs.csv with header sample_id,instrument_id,run_date (one row " - "per run, any order)." - ) - return Built( - instruction=instruction, - files=files, - artifact=Artifact(path="invalid_runs.csv", kind="custom", verify=verify, - render=lambda: to_csv(header, [list(r) for r in sorted(want)])), - notes={"expected": sorted(want)}, - ) - - -FAMILIES = [ - Family("ev_backorder", "office", "Backordered orders from orders, stock and cancellations", build_backorder, (1, 2)), - Family("ev_calibration", "science", "Runs outside a valid instrument calibration", build_calibration, (1,)), -] diff --git a/components/skillsdesk/upstream/terminal_desk/families/evidence2.py b/components/skillsdesk/upstream/terminal_desk/families/evidence2.py deleted file mode 100644 index d2e61a7e0b7009bc70228d65aa7fa358f57cfe14..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/evidence2.py +++ /dev/null @@ -1,291 +0,0 @@ -"""Find and combine evidence, second batch: partial deliveries, badge access with inherited zones, -duplicate customers, bank reconciliation, and the first release that fixed each issue.""" - -import json -import random - -from .base import Artifact, Built, Family -from .util import json_equal, load_csv, load_json, to_csv - -# ---------------------------------------------------------------- ev_deliveries - -def build_deliveries(level: int, rng: random.Random) -> Built: - while True: - pos = {} - for i in range(7): - po = f"PO-{rng.randint(100, 999)}{i}" - pos[po] = {f"PART-{rng.randint(10, 99)}": rng.randint(5, 40) for _ in range(rng.randint(1, 3))} - deliveries, got = [], {po: {p: 0 for p in lines} for po, lines in pos.items()} - for _ in range(14): - po = rng.choice(list(pos)) - part = rng.choice(list(pos[po])) - qty = rng.randint(1, pos[po][part]) - status = rng.choice(["received", "received", "received", "rejected"]) - deliveries.append([f"DN{rng.randint(1000, 9999)}", po.lower() if rng.random() < 0.2 else po, part, qty, status]) - if status == "received": - got[po][part] += qty - want = {} - for po, lines in pos.items(): - short = {p: q - min(q, got[po][p]) for p, q in lines.items() if got[po][p] < q} - if short: - want[po] = dict(sorted(short.items())) - over = any(got[po][p] > q for po, lines in pos.items() for p, q in lines.items()) - if 2 <= len(want) <= 6 and len(want) < len(pos) and not over: - break - po_rows = [[po, p, q] for po, lines in pos.items() for p, q in lines.items()] - rng.shuffle(po_rows) - rng.shuffle(deliveries) - files = {"purchase_orders.csv": to_csv(["po", "part", "qty_ordered"], po_rows), - "delivery_notes.csv": to_csv(["note", "po", "part", "qty", "status"], deliveries)} - - def verify(app: str) -> bool: - return json_equal(load_json(app, "outstanding.json"), want) - - instruction = ( - "Find what is still outstanding on the purchase orders in /app/purchase_orders.csv given the deliveries in " - "/app/delivery_notes.csv (PO numbers may be lower-case; only status received counts). Write " - "/app/outstanding.json as {po: {part: qty still missing}} for every PO with anything missing; leave fully " - "delivered POs and parts out." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="outstanding.json", kind="custom", verify=verify, - render=lambda: json.dumps(want) + "\n"), - notes={"expected": want}) - - -# ---------------------------------------------------------------- ev_badges - -ZONES = ["lobby", "lab", "server", "vault", "roof", "dock"] - - -def build_badges(level: int, rng: random.Random) -> Built: - while True: - zones = rng.sample(ZONES, 5) - roles = {"visitor": {zones[0]}, "staff": {zones[0], zones[1]}, "engineer": {zones[2]}, "security": {zones[3]}} - inherits = {"engineer": "staff", "security": "staff"} - - def allowed(role): - out = set(roles[role]) - while role in inherits: - role = inherits[role] - out |= roles[role] - return out - - people = {f"B{rng.randint(1000, 9999)}": rng.choice(list(roles)) for _ in range(6)} - swipes, bad = [], [] - for i in range(16): - badge = rng.choice(list(people) + ["B0000"]) - zone = rng.choice(zones) - t = f"2026-05-14T{8 + i // 2:02d}:{rng.randint(0, 59):02d}" - swipes.append([t, badge, zone]) - if badge not in people or zone not in allowed(people[badge]): - bad.append([t, badge, zone]) - inherited_ok = any(b in people and inherits.get(people[b]) and z in roles["staff"] and z not in roles[people[b]] - for _, b, z in swipes) - if 3 <= len(bad) <= 8 and inherited_ok: - break - files = {"badges.csv": to_csv(["badge", "role"], [[b, r] for b, r in people.items()]), - "roles.json": json.dumps({"zones": {r: sorted(z) for r, z in roles.items()}, "inherits": inherits}, indent=1) + "\n", - "swipes.csv": to_csv(["time", "badge", "zone"], swipes)} - header = ["time", "badge", "zone"] - want = {tuple(r) for r in bad} - - def verify(app: str) -> bool: - got = load_csv(app, "violations.csv") - if got is None or got[0] != header: - return False - rows = [tuple(r[h] for h in header) for r in got[1]] - return len(rows) == len(set(rows)) and set(rows) == want - - instruction = ( - "List badge swipes into zones the badge holder may not enter. /app/badges.csv maps badges to roles; " - "/app/roles.json gives each role's zones and which role it inherits from (a role may enter its own zones " - "and all zones of the roles it inherits, transitively); unknown badges may enter nothing. Write " - "/app/violations.csv with header time,badge,zone, one row per offending swipe." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="violations.csv", kind="custom", verify=verify, - render=lambda: to_csv(header, [list(r) for r in sorted(want)])), - notes={"expected": sorted(want)}) - - -# ---------------------------------------------------------------- ev_dupes - -FIRST = ["Maria", "John", "Aisha", "Wei", "Pablo", "Sara", "Kofi", "Lena"] -LAST = ["Garcia", "Smith", "Khan", "Zhang", "Ruiz", "Berg", "Mensah", "Novak"] - - -def build_dupes(level: int, rng: random.Random) -> Built: - while True: - rows, owner = [], {} - people = [(f, l) for f, l in zip(rng.sample(FIRST, 6), rng.sample(LAST, 6))] - n = 0 - for f, l in people: - email = f"{f[0].lower()}.{l.lower()}@mail.example" - phone = f"555{rng.randint(1000000, 9999999)}" - for k in range(rng.choice([1, 1, 2, 3])): - n += 1 - cid = f"C{100 + n}" - e = rng.choice([email, email.upper(), f" {email}"]) if k == 0 or rng.random() < 0.6 else "" - ph = rng.choice([phone, f"({phone[:3]}) {phone[3:6]}-{phone[6:]}", f"{phone[:3]}.{phone[3:6]}.{phone[6:]}"]) - if e == "" and rng.random() < 0.3: - ph = "" - rows.append([cid, f"{f} {l}", e, ph]) - owner[cid] = (email if e else None, phone if ph else None) - # Same person = same normalised email, or same phone digits (transitively). - parent = {c: c for c in owner} - - def find(c): - while parent[c] != c: - c = parent[c] - return c - - for a in owner: - for b in owner: - if a < b and ((owner[a][0] and owner[a][0] == owner[b][0]) or (owner[a][1] and owner[a][1] == owner[b][1])): - parent[find(b)] = find(a) - groups = {} - for c in owner: - groups.setdefault(find(c), []).append(c) - want = sorted(sorted(g, key=lambda c: int(c[1:])) for g in groups.values() if len(g) > 1) - via_phone = any(len(g) > 1 and len({owner[c][0] for c in g if owner[c][0]}) <= 1 and - any(owner[c][0] is None for c in g) for g in groups.values()) - if 2 <= len(want) <= 5 and via_phone: - break - rng.shuffle(rows) - files = {"customers.csv": to_csv(["customer_id", "name", "email", "phone"], rows)} - - def verify(app: str) -> bool: - got = load_json(app, "duplicates.json") - if not isinstance(got, dict) or set(got) != {"groups"} or not isinstance(got["groups"], list): - return False - try: - norm = sorted(sorted(g, key=lambda c: int(c[1:])) for g in got["groups"]) - except (TypeError, ValueError, IndexError): - return False - return norm == want - - instruction = ( - "Find duplicate customers in /app/customers.csv. Two records are the same customer if their emails match " - "(ignoring case and surrounding spaces) or their phone numbers have the same digits; this is transitive. " - "Blank emails or phones match nothing. Write /app/duplicates.json as {\"groups\": [[customer ids], ...]} " - "with every group of two or more records." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="duplicates.json", kind="custom", verify=verify, - render=lambda: json.dumps({"groups": want}) + "\n"), - notes={"expected": want}) - - -# ---------------------------------------------------------------- ev_bankrec - -def build_bankrec(level: int, rng: random.Random) -> Built: - while True: - ledger, bank = [], [] - for i in range(10): - amt = rng.choice([-1, 1]) * rng.randint(500, 250000) - day = rng.randint(1, 26) - ledger.append([f"L{i + 1:02d}", f"2026-08-{day:02d}", amt]) - r = rng.random() - if r < 0.7: - bank.append([f"BK{rng.randint(100, 999)}{i}", f"2026-08-{min(28, day + rng.randint(0, 2)):02d}", amt]) - elif r < 0.85: - bank.append([f"BK{rng.randint(100, 999)}{i}", f"2026-08-{min(28, day + rng.randint(4, 6)):02d}", amt]) - for j in range(2): - bank.append([f"BKX{j}", f"2026-08-{rng.randint(1, 28):02d}", rng.choice([-1, 1]) * rng.randint(500, 9000)]) - rng.shuffle(bank) - # Match each ledger entry, in ledger order, to the earliest unmatched bank line with the same amount - # dated 0-3 days after it. - used, unmatched_l = set(), [] - for lid, ld, amt in ledger: - cands = sorted((bd, bid) for bid, bd, ba in bank if bid not in used and ba == amt and 0 <= int(bd[-2:]) - int(ld[-2:]) <= 3) - if cands: - used.add(cands[0][1]) - else: - unmatched_l.append(lid) - unmatched_b = sorted(bid for bid, _, _ in bank if bid not in used) - # A ledger entry whose bank line exists but was booked too late must be present. - late = any(lid in unmatched_l and any(ba == amt and int(bd[-2:]) - int(ld[-2:]) > 3 for _, bd, ba in bank) - for lid, ld, amt in ledger) - if late and 1 <= len(unmatched_l) <= 5 and len(unmatched_b) >= 2: - break - fmt = lambda c: f"{c / 100:.2f}" # noqa: E731 - files = {"ledger.csv": to_csv(["entry", "date", "amount"], [[a, b, fmt(c)] for a, b, c in ledger]), - "statement.csv": to_csv(["line", "booked", "amount"], [[a, b, fmt(c)] for a, b, c in bank])} - want = {"unmatched_ledger": sorted(unmatched_l), "unmatched_bank": unmatched_b} - - def verify(app: str) -> bool: - return json_equal(load_json(app, "reconciliation.json"), want) - - instruction = ( - "Reconcile /app/ledger.csv with the bank /app/statement.csv. Take ledger entries in file order; match each " - "to the earliest-booked unmatched statement line with exactly the same amount booked 0 to 3 days after the " - "ledger date. Write /app/reconciliation.json as {\"unmatched_ledger\": [entry ids], \"unmatched_bank\": " - "[line ids]}, both sorted." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="reconciliation.json", kind="custom", verify=verify, - render=lambda: json.dumps(want) + "\n"), - notes={"expected": want}) - - -# ---------------------------------------------------------------- ev_fixedin - -def _ver(v: str) -> tuple: - return tuple(int(x) for x in v.split(".")) - - -def build_fixedin(level: int, rng: random.Random) -> Built: - while True: - versions = [] - major, minor, patch = 1, rng.randint(2, 8), 0 - for _ in range(6): - r = rng.random() - if r < 0.5: - patch += 1 - elif r < 0.85: - minor, patch = minor + 1, 0 - else: - major, minor, patch = major + 1, 0, 0 - versions.append(f"{major}.{minor}.{patch}") - issues = [f"ISS-{rng.randint(100, 999)}" for _ in range(8)] - notes, first = {}, {} - for v in versions: - fixed = rng.sample(issues, rng.randint(1, 3)) - notes[v] = fixed - for iss in fixed: - if iss not in first or _ver(v) < _ver(first[iss]): - first[iss] = v - asked = rng.sample(issues, 5) - want = {iss: first.get(iss) for iss in asked} - reopened = sum(1 for i in asked if sum(i in f for f in notes.values()) > 1) - lexical = {i: min((v for v in versions if i in notes[v]), default=None) for i in asked} - if reopened and None in want.values() and lexical != want: - break - files = {"issues.txt": "\n".join(asked) + "\n"} - for v in rng.sample(versions, len(versions)): - lines = [f"# Release {v}", "", "## Fixed"] + [f"- {i}: {rng.choice(['crash on save', 'slow export', 'typo in menu', 'login loop'])}" - for i in notes[v]] - files[f"changelog/{v}.md"] = "\n".join(lines) + "\n" - - def verify(app: str) -> bool: - return json_equal(load_json(app, "fixed_in.json"), want) - - instruction = ( - "For each issue in /app/issues.txt, find the earliest release whose notes in /app/changelog/ list it as " - "fixed (an issue can appear in several releases; compare versions numerically, so 1.10.0 is after 1.9.2). " - "Write /app/fixed_in.json as {issue: version} with null for issues never fixed." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="fixed_in.json", kind="custom", verify=verify, - render=lambda: json.dumps(want) + "\n"), - notes={"expected": want}) - - -FAMILIES = [ - Family("ev_deliveries", "industrial", "Outstanding quantities on purchase orders", build_deliveries, (1,)), - Family("ev_badges", "security", "Badge swipes outside inherited zone rights", build_badges, (1,)), - Family("ev_dupes", "office", "Duplicate customers by email or phone, transitively", build_dupes, (1,)), - Family("ev_bankrec", "finance", "Ledger to bank statement reconciliation", build_bankrec, (1,)), - Family("ev_fixedin", "software", "First release that fixed each issue", build_fixedin, (1,)), -] diff --git a/components/skillsdesk/upstream/terminal_desk/families/repair.py b/components/skillsdesk/upstream/terminal_desk/families/repair.py deleted file mode 100644 index 49a7f318285dae38ce34555cab1d39559ae46be8..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/repair.py +++ /dev/null @@ -1,426 +0,0 @@ -"""Repair and verify: fix code against a specification, a failing test and hidden checks. - -fix_toolkit is adapted from Terminal Desk v2's sw_fix (dnakhla, Apache-2.0; see NOTICE): the -grader runs hidden cases against the edited module as nobody, on a copy. fix_report gives a broken -report script; the grader runs the repaired script on a second, hidden input. -""" - -import json -import os -import random -import shutil -import tempfile - -from ..core import shell -from .base import Artifact, Built, Family -from .util import json_equal, load_json, read_artifact, to_csv - -# ---------------------------------------------------------------- fix_toolkit - -FUNCS = { - "median": { - "src": '''def median(values): - """Median of a non-empty list of numbers; for an even count, the mean of the two middle values.""" - s = sorted(values) - n = len(s) - mid = n // 2 - if n % 2 == 1: - return s[mid] - return (s[mid - 1] + s[mid]) / 2 -''', - "bugs": [("return (s[mid - 1] + s[mid]) / 2", "return s[mid]"), ("s = sorted(values)", "s = list(values)")], - "gen": lambda r: ([r.randint(-40, 40) for _ in range(r.randint(1, 9))],), - }, - "clamp": { - "src": '''def clamp(x, lo, hi): - """Limit x to the closed range [lo, hi] (lo <= hi).""" - if x < lo: - return lo - if x > hi: - return hi - return x -''', - "bugs": [(" return hi\n", " return lo\n"), ("if x < lo:", "if x <= lo + 1:")], - "gen": lambda r: (r.randint(-20, 20), r.randint(-10, 0), r.randint(1, 10)), - }, - "moving_average": { - "src": '''def moving_average(values, k): - """Means of every window of k consecutive values, in order: len(values) - k + 1 results.""" - return [sum(values[i:i + k]) / k for i in range(len(values) - k + 1)] -''', - "bugs": [("range(len(values) - k + 1)", "range(len(values) - k)"), ("sum(values[i:i + k]) / k", "sum(values[i:i + k]) / len(values)")], - "gen": lambda r: (lambda v: (v, r.randint(1, len(v))))([r.randint(0, 50) for _ in range(r.randint(3, 10))]), - }, - "percent_change": { - "src": '''def percent_change(old, new): - """Percent change from old to new (old != 0), rounded to 2 decimals.""" - return round((new - old) / old * 100, 2) -''', - "bugs": [("(new - old) / old", "(new - old) / new"), ("round((new - old) / old * 100, 2)", "round((new - old) / old, 2) * 100")], - "gen": lambda r: (r.randint(1, 500), r.randint(1, 500)), - }, - "chunk": { - "src": '''def chunk(items, size): - """Split items into consecutive lists of length size; the last list may be shorter.""" - return [items[i:i + size] for i in range(0, len(items), size)] -''', - "bugs": [("range(0, len(items), size)", "range(0, len(items) - size + 1, size)"), ("items[i:i + size]", "items[i:i + size - 1] or items[i:i + 1]")], - "gen": lambda r: ([r.randint(0, 9) for _ in range(r.randint(0, 12))], r.randint(2, 5)), - }, - "is_leap": { - "src": '''def is_leap(year): - """True for Gregorian leap years.""" - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) -''', - "bugs": [("(year % 100 != 0 or year % 400 == 0)", "year % 100 != 0"), ("year % 4 == 0 and", "year % 4 == 0 or")], - "gen": lambda r: (r.choice([r.randint(1582, 2400), r.choice([1600, 1700, 1800, 1900, 2000, 2100, 2400])]),), - }, - "dedupe": { - "src": '''def dedupe(items): - """Remove repeats, keeping the first occurrence of each item, in original order.""" - seen = set() - out = [] - for item in items: - if item not in seen: - seen.add(item) - out.append(item) - return out -''', - "bugs": [(" if item not in seen:\n seen.add(item)\n out.append(item)\n return out", " seen.add(item)\n return sorted(seen)"), (" out.append(item)\n return out", " out.insert(0, item)\n return out")], - "gen": lambda r: ([r.randint(0, 6) for _ in range(r.randint(0, 10))],), - }, - "overlap": { - "src": '''def overlap(a_start, a_end, b_start, b_end): - """Length of the overlap of [a_start, a_end] and [b_start, b_end]; 0 when they do not overlap.""" - return max(0, min(a_end, b_end) - max(a_start, b_start)) -''', - "bugs": [("max(0, min(a_end, b_end) - max(a_start, b_start))", "abs(min(a_end, b_end) - max(a_start, b_start))"), ("min(a_end, b_end) - max(a_start, b_start)", "min(a_end, b_end) - min(a_start, b_start)")], - "gen": lambda r: (lambda a, b: (a, a + r.randint(0, 10), b, b + r.randint(0, 10)))(r.randint(0, 15), r.randint(0, 15)), - }, - "word_count": { - "src": '''def word_count(text): - """Count words case-insensitively. A word is a run of letters a-z. Returns {word: count}.""" - counts = {} - for word in re.findall(r"[a-z]+", text.lower()): - counts[word] = counts.get(word, 0) + 1 - return counts -''', - "bugs": [("text.lower()", "text"), ('r"[a-z]+"', 'r"[a-z]+ "')], - "gen": lambda r: (" ".join(r.choice(["Red", "red", "blue", "Blue", "GREEN", "green,", "red.", "x-ray"]) for _ in range(r.randint(1, 8))),), - }, - "to_seconds": { - "src": '''def to_seconds(clock): - """Seconds in a 'H:MM:SS' or 'MM:SS' string.""" - total = 0 - for part in clock.split(":"): - total = total * 60 + int(part) - return total -''', - "bugs": [('clock.split(":")', 'reversed(clock.split(":"))'), ("total * 60 + int(part)", "total * 100 + int(part)")], - "gen": lambda r: (r.choice([f"{r.randint(0, 9)}:{r.randint(0, 59):02d}:{r.randint(0, 59):02d}", f"{r.randint(0, 59):02d}:{r.randint(0, 59):02d}"]),), - }, -} - -HEADER = '"""toolkit: small helpers used by the reporting jobs."""\n\nimport re\n\n\n' - -HARNESS = r''' -import json, sys -sys.path.insert(0, sys.argv[1]) -cases = json.loads(sys.stdin.read()) -out = {} -try: - import toolkit -except BaseException as exc: - print("@@RESULT@@" + json.dumps({"import_error": type(exc).__name__})) - raise SystemExit(0) -for name, arglists in cases.items(): - res = [] - for args in arglists: - try: - res.append(getattr(toolkit, name)(*args)) - except BaseException as exc: - res.append({"__error__": type(exc).__name__}) - out[name] = res -print("@@RESULT@@" + json.dumps(out, default=repr)) -''' - - -def _compile(src: str): - ns: dict = {} - exec("import re\n" + src, ns) # noqa: S102 - our own fixed templates - return next(v for k, v in ns.items() if callable(v) and k != "re" and not k.startswith("__")) - - -def _jsonable(x): - return json.loads(json.dumps(x)) - - -def _same(a, b) -> bool: - if isinstance(a, float) or isinstance(b, float): - try: - return abs(float(a) - float(b)) <= 1e-9 - except (TypeError, ValueError): - return False - if isinstance(a, list) and isinstance(b, list): - return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b)) - if isinstance(a, dict) and isinstance(b, dict): - return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a) - return type(a) is type(b) and a == b - - -def _differs(good, bad, args) -> bool: - try: - b = bad(*args) - except Exception: - return True - return not _same(_jsonable(good(*args)), _jsonable(b)) - - -def build_fix(level: int, rng: random.Random) -> Built: - n_funcs, n_bugs = 4, 2 - names = rng.sample(sorted(FUNCS), n_funcs) - buggy = set(rng.sample(names, n_bugs)) - shown = rng.choice(sorted(buggy)) # the one bug with a failing visible test - sources, good_sources, hidden, tests = [], [], {}, [] - for name in names: - spec = FUNCS[name] - good = _compile(spec["src"]) - src = spec["src"] - bad = None - if name in buggy: - old, new = rng.choice(spec["bugs"]) - assert old in src, (name, old) - src = src.replace(old, new, 1) - bad = _compile(src) - sources.append(src) - good_sources.append(spec["src"]) - cases = [spec["gen"](rng) for _ in range(40)] - if bad is not None: - diffs = [c for c in cases if _differs(good, bad, c)] - while len(diffs) < 3: - c = spec["gen"](rng) - if _differs(good, bad, c): - diffs.append(c) - cases.append(c) - hidden[name] = (_jsonable([list(c) for c in cases]), _jsonable([good(*c) for c in cases])) - # Visible tests: two passing cases for correct functions, one failing case for `shown`. - if name == shown: - c = next(c for c in cases if _differs(good, bad, c)) - tests.append((name, c, good(*c))) - elif name not in buggy: - for c in cases[:2]: - tests.append((name, c, good(*c))) - module = HEADER + "\n\n".join(sources) - test_lines = [ - "import os, sys, unittest", - "sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'src'))", - "import toolkit", - "", - "", - "class ToolkitTest(unittest.TestCase):", - ] - for i, (name, args, want) in enumerate(tests): - test_lines += [ - f" def test_{name}_{i}(self):", - f" self.assertEqual(toolkit.{name}(*{list(args)!r}), {want!r})", - "", - ] - test_lines += ["", 'if __name__ == "__main__":', " unittest.main()", ""] - readme = ( - "toolkit.py feeds the nightly reports. Each function's docstring is its specification.\n" - "Run the tests from /app with: python3 -m unittest discover -s tests -v\n" - ) - readme += "The visible tests are incomplete: a function can be wrong and still pass them.\n" - - def verify(app: str) -> bool: - data = read_artifact(app, "src/toolkit.py") # regular file only, no symlinks - if data is None: - return False - tmp = tempfile.mkdtemp(prefix="tdchk-") - try: - os.chmod(tmp, 0o755) - src_dir = os.path.join(tmp, "src") - os.mkdir(src_dir) - with open(os.path.join(src_dir, "toolkit.py"), "wb") as fh: - fh.write(data) - with open(os.path.join(tmp, "harness.py"), "w") as fh: - fh.write(HARNESS) - shell.give_to_nobody(tmp) - payload = json.dumps({n: args for n, (args, _) in hidden.items()}) - _, text = shell.run(["python3", "-I", os.path.join(tmp, "harness.py"), src_dir], tmp, stdin_text=payload) - lines = [ln for ln in text.splitlines() if ln.startswith("@@RESULT@@")] - if not lines: - return False - got = json.loads(lines[-1][len("@@RESULT@@"):]) - return all(name in got and _same(got[name], want) for name, (_, want) in hidden.items()) - finally: - shell.kill_nobody() - shutil.rmtree(tmp, ignore_errors=True) - - oracle = HEADER + "\n\n".join(good_sources) - instruction = ( - f"src/toolkit.py has {n_funcs} functions, and {'one does not do what its docstring says' if n_bugs == 1 else f'{n_bugs} do not do what their docstrings say'}. Fix the module in place in /app/src/toolkit.py so that every function matches its " - "docstring, and keep the function names and signatures. The tests in tests/ are visible but incomplete: " - "the grader runs hidden tests against the edited file." - ) - return Built( - instruction=instruction, - files={"src/toolkit.py": module, "tests/test_toolkit.py": "\n".join(test_lines), "README.md": readme}, - artifact=Artifact(path="src/toolkit.py", kind="custom", verify=verify, render=lambda: oracle), - notes={"oracle_files": {"src/toolkit.py": oracle}, "buggy": sorted(buggy)}, - ) - - - - -# ---------------------------------------------------------------- fix_report - -REGIONS = ["north", "south", "coast", "valley", "metro"] - -REPORT_PY = '''"""Summarise shipments per region. Usage: python3 report.py """ - -import csv -import json -import sys - - -def main(src, dst): - totals = {} - with open(src, newline="") as fh: - for row in csv.DictReader(fh): - if row["status"] == "Void": - continue - region = row["region"] - cost = float(row["cost"]) - weight = float(row["weight_kg"]) - t = totals.setdefault(region, {"shipments": 0, "cost": 0.0, "weight": 0.0}) - t["shipments"] += 1 - t["cost"] += cost - t["weight"] += weight - out = {} - for region, t in totals.items(): - out[region] = { - "shipments": t["shipments"], - "total_cost": round(t["cost"], 2), - "cost_per_kg": round(t["cost"] / t["shipments"], 3), - } - with open(dst, "w") as fh: - json.dump(out, fh, indent=1, sort_keys=True) - - -if __name__ == "__main__": - main(sys.argv[1], sys.argv[2]) -''' - -REPORT_FIXED = (REPORT_PY.replace('row["status"] == "Void"', 'row["status"].strip().lower() == "void"') - .replace('float(row["cost"])', 'float(row["cost"].replace("$", "").replace(",", ""))') - .replace('t["cost"] / t["shipments"]', 't["cost"] / t["weight"]')) - -SPEC = """# Shipment report - -report.py summarises a shipments CSV per region: - - python3 report.py data/shipments.csv out/summary.json - -Input columns: shipment_id, region, weight_kg, cost, status. -- cost is in dollars and may be written like "$1,234.50". -- Rows whose status is void (any capitalisation) are cancelled and must be left out entirely. - -Output: a JSON object keyed by region; each value is - {"shipments": count of shipments, "total_cost": summed cost rounded to 2 decimals, - "cost_per_kg": summed cost divided by summed weight_kg, rounded to 3 decimals} - -Finance reported that the nightly job crashes and that its earlier numbers looked wrong. -""" - - -def _shipments(rng: random.Random, n: int): - regions = rng.sample(REGIONS, 3) - rows = [] - for i in range(n): - cost = round(rng.uniform(40, 4200), 2) - cost_txt = rng.choice([f"{cost:.2f}", f"${cost:,.2f}", f"${cost:,.2f}", f"{cost:,.2f}"]) - status = rng.choice(["delivered", "delivered", "in_transit", "void", "VOID", "Void"]) if i % 3 == 0 else "delivered" - rows.append([f"SH-{rng.randint(1000, 9999)}", regions[i % 3], f"{rng.uniform(0.5, 120):.1f}", cost_txt, status]) - if not any(r[4].lower() == "void" for r in rows): - rows[0][4] = "void" - if not any("," in r[3] for r in rows): - rows[1][3] = "$1,250.00" - rng.shuffle(rows) - return rows - - -def _summary(rows) -> dict: - totals = {} - for sid, region, weight, cost, status in rows: - if status.strip().lower() == "void": - continue - t = totals.setdefault(region, [0, 0.0, 0.0]) - t[0] += 1 - t[1] += float(cost.replace("$", "").replace(",", "")) - t[2] += float(weight) - return {r: {"shipments": t[0], "total_cost": round(t[1], 2), "cost_per_kg": round(t[1] / t[2], 3)} - for r, t in totals.items()} - - -SHIP_HEADER = ["shipment_id", "region", "weight_kg", "cost", "status"] - - -def build_report(level: int, rng: random.Random) -> Built: - rows = _shipments(rng, 12) - hidden_rows = _shipments(rng, 15) - want = _summary(rows) - hidden_want = _summary(hidden_rows) - hidden_csv = to_csv(SHIP_HEADER, hidden_rows) - files = {"report.py": REPORT_PY, "README.md": SPEC, "data/shipments.csv": to_csv(SHIP_HEADER, rows)} - - def run_script(app: str): - script = read_artifact(app, "report.py") - if script is None: - return None - tmp = tempfile.mkdtemp(prefix="tdrep-") - try: - os.chmod(tmp, 0o755) - with open(os.path.join(tmp, "report.py"), "wb") as fh: - fh.write(script) - with open(os.path.join(tmp, "in.csv"), "w") as fh: - fh.write(hidden_csv) - shell.give_to_nobody(tmp) - shell.run(["python3", "-I", "report.py", "in.csv", "out.json"], tmp) - return load_json(tmp, "out.json") - finally: - shell.kill_nobody() - shutil.rmtree(tmp, ignore_errors=True) - - def same(got, expected) -> bool: - if not isinstance(got, dict) or set(got) != set(expected): - return False - for region, e in expected.items(): - g = got[region] - if not isinstance(g, dict) or set(g) != set(e) or not json_equal(g["shipments"], e["shipments"]): - return False - if not json_equal(g["total_cost"], float(e["total_cost"]), 0.005): - return False - if not json_equal(g["cost_per_kg"], float(e["cost_per_kg"]), 0.0005): - return False - return True - - def verify(app: str) -> bool: - return same(load_json(app, "out/summary.json"), want) and same(run_script(app), hidden_want) - - instruction = ( - "The nightly shipment report in /app/report.py is broken. /app/README.md is its specification. Repair " - "/app/report.py so it follows the specification for any input of that format, then run it on " - "/app/data/shipments.csv to write /app/out/summary.json. The grader checks out/summary.json and also runs " - "your report.py on a different shipments file." - ) - return Built(instruction=instruction, files=files, - artifact=Artifact(path="out/summary.json", kind="custom", verify=verify, - render=lambda: json.dumps(want, indent=1, sort_keys=True) + "\n"), - notes={"expected": want, "oracle_files": {"report.py": REPORT_FIXED}}) - - -FAMILIES = [ - Family("fix_toolkit", "software", "Repair a helper module against hidden tests", build_fix, (1,)), - Family("fix_report", "office", "Repair a broken report script and rerun it", build_report, (1,)), -] diff --git a/components/skillsdesk/upstream/terminal_desk/families/repair2.py b/components/skillsdesk/upstream/terminal_desk/families/repair2.py deleted file mode 100644 index a6777158841c3b5a4b6e0b30bdedf7cce0d818ba..0000000000000000000000000000000000000000 --- a/components/skillsdesk/upstream/terminal_desk/families/repair2.py +++ /dev/null @@ -1,431 +0,0 @@ -"""Repair and verify, second batch. Four modules graded on hidden cases (pagination, log parsing, -unit conversion, business days) and two scripts rerun on hidden input (deduplication, merging two -sorted exports). Hidden runs happen as nobody on a copy.""" - -import datetime as dt -import json -import random - -from .base import Artifact, Built, Family -from .util import json_equal, load_csv, read_artifact, run_hidden, to_csv - -HARNESS = r''' -import json, sys -sys.path.insert(0, ".") -cases = json.load(open("cases.json")) -try: - mod = __import__(sys.argv[1]) -except BaseException as exc: - print("@@OUT@@" + json.dumps({"import_error": type(exc).__name__})) - raise SystemExit(0) -out = [] -for fn, args in cases: - try: - out.append(getattr(mod, fn)(*args)) - except BaseException as exc: - out.append({"error": type(exc).__name__}) -print("@@OUT@@" + json.dumps(out, default=repr)) -''' - - -def _close(got, want) -> bool: - """Exact structure; floats within a relative 1e-9 (implementations may order operations differently).""" - if isinstance(want, float) and not isinstance(got, bool) and isinstance(got, (int, float)): - return abs(got - want) <= 1e-9 * max(1.0, abs(want)) - if isinstance(want, list): - return isinstance(got, list) and len(got) == len(want) and all(_close(g, w) for g, w in zip(got, want)) - if isinstance(want, dict): - return isinstance(got, dict) and set(got) == set(want) and all(_close(got[k], want[k]) for k in want) - return json_equal(got, want) - - -def _module_task(module: str, broken: str, fixed: str, cases: list, tests: str, instruction: str) -> Built: - ns: dict = {} - exec(fixed, ns) # noqa: S102 - our own reference implementation - want = [] - for fn, args in cases: - try: - want.append(ns[fn](*args)) - except Exception as exc: # the specification says which inputs raise - want.append({"error": type(exc).__name__}) - want = json.loads(json.dumps(want, default=repr)) - path = f"{module}.py" - - def verify(app: str) -> bool: - src = read_artifact(app, path) - if src is None: - return False - text, _ = run_hidden({path: src, "cases.json": json.dumps(cases), "h.py": HARNESS}, - ["python3", "-I", "h.py", module], []) - lines = [ln for ln in text.splitlines() if ln.startswith("@@OUT@@")] - return bool(lines) and _close(json.loads(lines[-1][7:]), want) - - return Built(instruction=instruction, files={path: broken, f"test_{module}.py": tests}, - artifact=Artifact(path=path, kind="custom", verify=verify, render=lambda: fixed), - notes={"oracle_files": {path: fixed}}) - - -# ---------------------------------------------------------------- fix_paginate - -PAGINATE_FIXED = '''"""Pagination helpers. Pages are numbered from 1.""" - - -def page_count(total, per_page): - """Number of pages needed for total items, per_page per page; 0 items need 0 pages.""" - return (total + per_page - 1) // per_page - - -def page(items, number, per_page): - """The items on page `number`; an empty list for a page past the end. number < 1 raises ValueError.""" - if number < 1: - raise ValueError("pages start at 1") - start = (number - 1) * per_page - return items[start:start + per_page] -''' - -PAGINATE_BROKEN = PAGINATE_FIXED.replace("return (total + per_page - 1) // per_page", "return total // per_page + 1") \ - .replace("start = (number - 1) * per_page", "start = number * per_page - per_page + 1") - - -def build_paginate(level: int, rng: random.Random) -> Built: - cases = [["page_count", [0, 10]], ["page_count", [10, 10]], ["page", [list(range(5)), 0, 2]]] - for _ in range(30): - n, per = rng.randint(0, 40), rng.randint(1, 9) - cases.append(["page_count", [n, per]] if rng.random() < 0.4 else - ["page", [list(range(n)), rng.randint(1, n // per + 2), per]]) - tests = ("import unittest\nfrom paginate import page_count, page\n\n\nclass T(unittest.TestCase):\n" - " def test_count(self):\n self.assertEqual(page_count(25, 10), 3)\n\n\n" - "if __name__ == '__main__':\n unittest.main()\n") - return _module_task("paginate", PAGINATE_BROKEN, PAGINATE_FIXED, cases, tests, - "Users report missing and duplicated rows between pages. Fix /app/paginate.py in place so both " - "functions follow their docstrings (keep names and signatures). /app/test_paginate.py is " - "incomplete; the grader runs hidden cases, including edge cases.") - - -# ---------------------------------------------------------------- fix_logline - -LOGLINE_FIXED = r'''"""Parse one access-log line: - [