diff --git a/docs/releases/2026-11-16-unattended-prompts-validation.json b/docs/releases/2026-11-16-unattended-prompts-validation.json new file mode 100644 index 0000000..6ff4a78 --- /dev/null +++ b/docs/releases/2026-11-16-unattended-prompts-validation.json @@ -0,0 +1,257 @@ +{ + "schema_version": 1, + "created": "2026-11-16T14:36:55.137608+08:00", + "base_commit": "e4875b4eca1bc487514d479df15f2a4ac92df5e3", + "branch": "codex/unattended-prompt-defaults", + "full_suite": { + "path": "F:\\CbbUnattended-20261116\\full-final.xml", + "sha256": "8717cf87707b525a17eb2a3a292677360eade0d374e7d6eb42a6c2d07209d520", + "tests": 1937, + "failures": 0, + "errors": 0, + "skipped": 0 + }, + "red_original_no_timeout": { + "path": "F:\\CbbUnattended-20261116\\red.xml", + "sha256": "b0c46ca9c76ce41f9c9053ec94a08d416a3b18d775f3d9e3af1d469ac96b1225", + "tests": 3, + "failures": 3, + "errors": 0, + "skipped": 0 + }, + "button_and_prompt_integration": { + "path": "F:\\CbbUnattended-20261116\\integration-final.xml", + "sha256": "002f68c353fdf3a6e5eacfd2596df8b15f30a8a76ef3c262d2da3fc64e35a202", + "tests": 100, + "failures": 0, + "errors": 0, + "skipped": 0 + }, + "first_full_run": { + "path": "F:\\CbbUnattended-20261116\\full-suite.xml", + "sha256": "a6d2d5fe0d240ede5a90fff7b8f4c70635c12b82ef3423185c8ee975db17bf53", + "tests": 1935, + "failures": 6, + "errors": 2, + "skipped": 0 + }, + "first_full_run_explanation": "Four notification tests expected the old OK button; two recovery-summary paths recreated the Close button and invalidated countdown. Fixed redundant recreation and aligned notification clicks; failed evidence retained.", + "static_api_trial": { + "final_design": "Explicit QMessageBox object; no application event interception.", + "rejected": "Static Qt question interception caused timer ownership/slot errors in experiments; rejected and replaced before final integration." + }, + "default_timeout_ms": 3000, + "defaults": { + "submitted_verify_check_management_recovery": "confirm", + "unknown_owner": "skip", + "uncertain_pcb_readwrite": "skip", + "version": "last_user_saved_if_enabled_else_cancel", + "native_cancel": "confirm", + "save_before_close": "save", + "force_terminate": "cancel", + "notification": "close" + }, + "compileall_passed": true, + "diff_check_passed": true, + "independent_review": "Final read-only rereview found no remaining actionable issues.", + "files_sha256": { + "src/cbb_refresh_verify/application.py": "62b9b013563a216d020c8366cccb8f949b02afa72dc63c26940804441cc23057", + "src/cbb_refresh_verify/backup_recovery.py": "1d7ef08ef53ca7a0971cdacb0908d9bb06d067b06dc2329fa58722ce9068921d", + "src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a", + "src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35", + "src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9", + "src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3", + "src/cbb_refresh_verify/desktop_worker.py": "27d751816552d215dd8ee9cd67941d824f7b4493120ead7c3f87e5eba5ec4a92", + "src/cbb_refresh_verify/diagnostic_open.py": "d6c49ffe5a9969d95edbbc896d47a7e100f248380a287f99ba7bb8b92dbb3072", + "src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b", + "src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56", + "src/cbb_refresh_verify/dialog_probe.py": "d61f0c955c961980c9635940eefb9c7947c1fe90b4b6fd844720df41ddb0aa0e", + "src/cbb_refresh_verify/dialog_rules.py": "3189b476f7ff4678b59212ed7b4081164e038a7cf7662cd895f9019cb3c1edc5", + "src/cbb_refresh_verify/dialog_supervisor.py": "15c415c2d2e916f0b64ba04416164ff3b50996d70b22d3b4ac2226b5547ac247", + "src/cbb_refresh_verify/failed_session.py": "7e6f7fa5ebcf2d49f00c5efc5f5d26412704b68e9122e476ac1f672009a98c09", + "src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98", + "src/cbb_refresh_verify/icdb_ownership.py": "7bf2342c1efa34a2ebcbf27964a40a490220f7146fbb6ef957b8d8dd1e511f03", + "src/cbb_refresh_verify/icdb_recovery.py": "358c0e9a004f1e0b2127513286e1dffd94b0180a8b7314aa9655462f570b6360", + "src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed", + "src/cbb_refresh_verify/library_lock.py": "6836ec8ac21e788eb75326ff44cb31ad4bdfb5f381bd35cdf33e6b34c7fca89e", + "src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195", + "src/cbb_refresh_verify/library_reader.py": "d4007caa361edd467773e49f721e02671d5a9bcb30741769a57349850b12c438", + "src/cbb_refresh_verify/maintenance_entry.py": "3b93c25f69d7a961facd8004e20e155a84cc18f06d57b741a9055786ed058990", + "src/cbb_refresh_verify/management.py": "7ead9bfffeb44201e44f73d9f039590f091e9a456982f2110dca8ec3695f8803", + "src/cbb_refresh_verify/management_transaction.py": "32c53caaead05d5db3a31d3e30721e65434e5837095dc0a7812f825603aa37a0", + "src/cbb_refresh_verify/mentor_adapter.py": "1fc8c98d5508120e03bf001a42dd3e0da7b165eb18c90f1aed83147d17db8638", + "src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116", + "src/cbb_refresh_verify/models.py": "9e8209a8b006df923f1d07ccab64bbcfe5d674c4fc5f5426bfbc9b11da4ee105", + "src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94", + "src/cbb_refresh_verify/native_backup.py": "7276fa3d9298e85550151cf0c7191d84bd08a18a72df5d854a3c38f1a88b001d", + "src/cbb_refresh_verify/native_engineering_identity.py": "8c0fc144707d68a9b85f6da50ef950f1f6e7fee248acbf34d19b707d51212be0", + "src/cbb_refresh_verify/native_export_guard.py": "523cdf44db8e1665634feadba963ccf26777dc8942fb2eb604d2c30bbe92cbb6", + "src/cbb_refresh_verify/native_management.py": "eb2ec311489eaf5deb06893a54a02469c9b2bb9baccbdd6563bae295aafcf363", + "src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49", + "src/cbb_refresh_verify/native_repair.py": "9f024dcb5e3a76369191033474fefd30787b6ae350c315f3cf38e92e5a1f3e98", + "src/cbb_refresh_verify/native_repair_ui.py": "3eb2af181befea94af8b3b3131edff09589f340bcba777abbe3b67fd31b80393", + "src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f", + "src/cbb_refresh_verify/operation_lifecycle.py": "3838c5a501711d16f578c45ebbc6f960872b0c3ba6bbda9a597f994ef746cef6", + "src/cbb_refresh_verify/operation_queue.py": "a6932d8bc68ac436091f6d362557c66d274ec52d0f295a22f014a3396845c79f", + "src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903", + "src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5", + "src/cbb_refresh_verify/pcb_open_consent.py": "fd56dfe0b537408745127d80ea68cc59d3f333954af76bac7a7b324d66badc65", + "src/cbb_refresh_verify/pcb_restore_prompt.py": "a488ab48845173f463042c17ad1e719fe37a4bcf98a660f06453eef171b0e7bb", + "src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4", + "src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63", + "src/cbb_refresh_verify/reimport_recovery.py": "ef148549751fa47518f5f2ca8f32ba25794ec5f22e0de545476ea33f89a3f0bf", + "src/cbb_refresh_verify/residual_sessions.py": "4ac500b33b209611d54eb496c6c30727ba159742d625431ceea84471a5fc3442", + "src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e", + "src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367", + "src/cbb_refresh_verify/scoped_manifest.py": "9318bf0f929d23c18466a25d83a4a9903822093c123aae10510061788c6d0ab7", + "src/cbb_refresh_verify/session_record.py": "2bc3cff365008864584138a4ff13538bb6b2f90d981e7d008a1300f9102c6e7e", + "src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196", + "src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8", + "src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2", + "src/cbb_refresh_verify/verify_runner.py": "3027ef7fc1ef6365ff36ae0c83389d869b92ffcd96985d10275bca4dc9483e3f", + "src/cbb_refresh_verify/write_admission.py": "c5f879bd5cb70a5dedfc64349c8758bf370daa4240491addd2aecd344f3a935c", + "src/cbb_refresh_verify/__init__.py": "75942b10cc5c09f19d5f31bedd0395361642336f52bc9e9872d8483e3b9882f9", + "src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0", + "src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599", + "src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "8a80f584347f3fdefc089169894712746fee85f079b029578f008d6aecec8d90", + "src/cbb_refresh_verify/ui/icdb_check_task.py": "ade3bf414aa29b42f4c1535c613b2cacb2735f6abc7900e6da25999390a5891d", + "src/cbb_refresh_verify/ui/main_window.py": "f72062cb3d97cbd38f6390b9483e0f3aab619dec0bb2292c02d32b7fc5cd84b9", + "src/cbb_refresh_verify/ui/management_dialog.py": "57698f42112b120899dac26c40d2aafb4b5ba719660a302c0460361a7d50609a", + "src/cbb_refresh_verify/ui/pcb_open_dialog.py": "1b9689d555d221567263b6b587250b51a11bef276c35d64393e1b3d13803c625", + "src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "11479db5520310af37824e083cb678d69d4cfd12f70dcd29ccb906b929e3d9bd", + "src/cbb_refresh_verify/ui/residual_release_dialog.py": "a0bdcc091778d508c43a6af96bd6423b25cd029c92b6bcff22d459d09a030d06", + "src/cbb_refresh_verify/ui/timed_prompt.py": "71db65febd0aff9117dcee42dde5151a7f13a3337794c77031cf5585f0397d97", + "src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888", + "src/cbb_refresh_verify/ui/write_owner_dialog.py": "65dc3c8287f4ac5dc767797c13e192f6bd916f9051570a33a2b18f4f8334c3b3", + "src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "tests/button_simulation.py": "3278868565853001103557d5f7ada42b11b05c03feb9032deed0327b6609de2b", + "tests/test_abnormal_shutdown.py": "0abdeaf51e2ffc3f771e09aefa9ec647a72b7f64757c9f3851926fbd392cbbcd", + "tests/test_all_buttons.py": "a075cfdf3223b754be351db54844f94a8538519c38a12b1b575ec483c544d57c", + "tests/test_application.py": "bba12187fca6fee0f4f8862182bb40d939e2995016af2cdbb3fd756f6a99135d", + "tests/test_automation_license.py": "45e9c75d0d3e1a76f997f7da4cc87b5eb1b05a4ea2356408725742eac8a09ffb", + "tests/test_background_icdb.py": "df9bd9e8252e0dee4527dc6a740c0c33e76d1fb06a79b816cc15809d95716e44", + "tests/test_background_queue_regressions.py": "132866bfccc9a7ac5cb234f97aaf6a290e2e4ef949f31e2f70b0f3eafeb99046", + "tests/test_backup_recovery.py": "efd88c0c00440ac915b147c2e6dee8044ca805b03f90ab9f171cbde1db11cb9b", + "tests/test_backup_recovery_dialog.py": "24a120e45dee151bc71a2e1a05345936c5063bf0f57a277af02ef3a6bfd753f9", + "tests/test_batch_blockers.py": "4387293d3a5820fab630e3c5fe1b424f61ba6947773e5a61125d840433c5c62a", + "tests/test_batch_item_yield.py": "ed4be6d1e854b18d054a75c92171cd46b6b64411c2f74e9a3caf31fba3c7366b", + "tests/test_batch_status.py": "c1f9af0c7c6f3171b3726fb53346f480b13b8d9cd88111a9c12e2fae2392bbff", + "tests/test_batch_status_faults.py": "314e890c9aee439c8a75b4dfd605685240c74f6212da975fd50526bd70b4a0ff", + "tests/test_desktop_worker.py": "671d616f04a01d74508b328e3b6fc8f6c7191a91de0dcaa486aa98a3718353ff", + "tests/test_diagnostic_open.py": "b44f8f7b171602ad2691ea2e064ac9fe94f2fabb9fcc2eb6760cc1dd365b9423", + "tests/test_dialog_agent.py": "8c746e47d55637ca18d7cc998f324a0c2e0a5214dcfe8fcb6458c060619c211c", + "tests/test_dialog_models.py": "6902cf5c292458340fb48241b34875e111a0113d706cd82775934a7f72bab7b9", + "tests/test_dialog_probe.py": "55c98f6102957a27a96dcfd4f4bf3af499b5055225b77ef93b7b332dfd4ac472", + "tests/test_dialog_rules.py": "96bf36493da770679e9207e96b3088ef7f471aea22e17c254f33326ffef0d7f9", + "tests/test_dialog_startup_budget.py": "6f23c01836e4894ae82c3345a2383c4f8eb0517056c5b953c43100acd0fc3739", + "tests/test_dialog_supervisor.py": "4c1b00050127a65b0a8cf1c7a94fd673431ea3f04b76033a463804d0468ad2d9", + "tests/test_extended_safety.py": "7450816abba89aba1f4739f819f43631def82701fe07481279db2b3f3ed96cf6", + "tests/test_external_owner_release.py": "675ddbab4a97e86febac3003b9083c259295534941aa0463488a5a1206cfaf92", + "tests/test_failed_startup.py": "eca757ea46a4c0aa4fb0368ff53f26822af71612d251ecd87132686fe3c3794b", + "tests/test_failure_lifecycle.py": "dfeac56744a44e6f4c7898516749ca478f53d7c7f08b3843a05ef7f448c469a7", + "tests/test_icdb_address.py": "cbdc07e5043349c796a4ea1ce3d4989062094cd28929a9ef7d42c5ba75b77907", + "tests/test_icdb_batch_check.py": "79b4a8d9576449bde64f06bfd4d30b82ce6fe93e055c238eb1f239e75b472579", + "tests/test_icdb_open_check.py": "1f3750169755d0553bac3e0f8bec244038b84f9cd970e17c9f6eb67dee0e3dba", + "tests/test_icdb_recovery.py": "298ddac4b79b4400efc99ff27c58ca49fffea1f401a31071451b2fdaca59036e", + "tests/test_import_without_export_gate.py": "2f249412736cbe84f0c82db82403212739b7c53355f87cd053587ccdb722b175", + "tests/test_incident_safety.py": "52f3ccb04db8971bf38628c2bd334d4fd79795e97de6538f6f66cb35f7123ece", + "tests/test_independent_operations.py": "4ba5798df3346bce74c3703c158f1dce1d1ba14df748606fcaf900c8568753e0", + "tests/test_integration.py": "9e9d30692607c889e1e3744a63c79c68e3af7d4c86804e0bcebe48e68765086c", + "tests/test_late_release_continuation.py": "34c62a628cbc08f4e8b9a1919c13f17772a2d26d1996fae34a35f814725b00e2", + "tests/test_library_lock.py": "3d65bd941faa441404045ce0140ea3ea5e58fb7d410b7b76bb9f03a9ea03d3af", + "tests/test_library_reader.py": "b39a1dc9d99c2463b744141e3c3489cd49ac4a637e7835559a9c3fe9cbafbb58", + "tests/test_lifecycle_supervision.py": "cfe29f1e73c6ef38d11e185e211b6e2fb60247f53a44e99dd1e2f8cf7a009faa", + "tests/test_maintenance_diagnosis.py": "0849aef555475a03b061eacf499f261fb75f2e727f35dba3cbceafac92e2a638", + "tests/test_maintenance_entry.py": "5ed3cda8e0c829fb2964e27f1bdc6fa8ee8dcde93ec63338959bf754b62d6a0b", + "tests/test_maintenance_owner_scope.py": "7cf64dc7f2b126684dcac6e619cbd87eca3d85ec2fc1f70f057154679dad6026", + "tests/test_maintenance_review.py": "ba807fd8c25c1b52cf2443d8bcf2f57539819715c0bc6c358d31d8542c2e7ce5", + "tests/test_maintenance_startup_gate.py": "4f69d33218483a658b51b2012ae8bfa83aff8a787152a38b19dadc4c0d3ffe36", + "tests/test_maintenance_ui.py": "9c604714b0742503dbd55b243161a01f4ae62fa0cae7c4cddec7a2b8c81d07ab", + "tests/test_management.py": "cad0fb43eca9e7022a33a5e9ff0a408465b262fd304b146cdc85c28265f2e74f", + "tests/test_management_diagnostics.py": "671a9d7c112ededbee332db9b6fbab786fb37e9367d992f902f3ab2c9f60880b", + "tests/test_management_native_transaction.py": "7ca227aae6426c4d0d998edfd8620ec18905aaf212f0be20ceba97b1cde3a9a4", + "tests/test_management_probe_guards.py": "ae9be3dbd7c6a616478b7d4ea3498c428ff94a985089fe798463c5cab456f151", + "tests/test_management_retry_blockers.py": "124dbef291dbe331ba0c3e7de1665c910ea43e37b1563429b387f0f2233953ee", + "tests/test_management_source.py": "16e608ed9c8b0aa81cf08d49f165a33a1403c4ea7f2a5be44e8cfc8cb49850ad", + "tests/test_management_supervision.py": "2dcadd6551a94c52e5d4e74285959f10144a89c48af87e508abaea945652d1f6", + "tests/test_management_ui.py": "3d02dd00f20227aba6eeff40b9c49e34c93f81b02a02370fb0fa6848a1981413", + "tests/test_manual_backup_ui.py": "c1d3f7363a18ad3a690854d503199aa703c0a11ef937c933b025fd9b98083ed7", + "tests/test_mentor_paths.py": "a05a91812a74b58e76f36d581216ee43969d2576b8a8e7d1cde3e301c52cf4c1", + "tests/test_native_add_failures.py": "ceedd60e030628b1af149d08d16216d5f7158a63686729bb357c148da86fb0ec", + "tests/test_native_backup.py": "43ec0c6b14b53864553feaf5d9fb498b37866f24edc486c0749160d3f803db5f", + "tests/test_native_engineering_identity.py": "a1adcf6883a9b55c2c37d9f491faf40dd4928f4d8db675419fd288dd31552c69", + "tests/test_native_export_guard.py": "f8ec4fa1058af55008e9628f79f2dc70b6e551f36815a812d10bfdf955cada51", + "tests/test_native_inspection_release_regressions.py": "8f7bb0b2b641d437872f1dd1d0c2547c2522c81e3c0351c31a7125f751d91927", + "tests/test_native_management.py": "badf33d4d00104c7e96e336777fb3e49690cc9db5ce1b071f98520aa5b6668f1", + "tests/test_native_management_fields.py": "9917ca0910e19bd809c86d0120c652145261528ace33c3b805f5663442c4a973", + "tests/test_native_occupancy.py": "56293dbe24bd3cd4f74cf8208e933faab7d737e5a5684a5d38838d063c3aef6d", + "tests/test_native_repair.py": "113185ced72d8f4f4eafca99054d97fe80a504d1c6cc91aaf86f55cea1b7e138", + "tests/test_navigation_tabs.py": "d7d5bbfc752f73c1b1d4615ffafc1266e772d96f3f3ba3d82c4b4baf678b292d", + "tests/test_network_path.py": "f52624391ae78e9b913dace2b1a9a2875a5855f86dc9e12c324ef493e6c7817b", + "tests/test_network_release_safety.py": "caef536d0a40b2eb848c1b8ab095ab374af247c03dd44acf8a70f0f500db6dac", + "tests/test_operation_lifecycle.py": "c0ce6c86b73021a8b162ae9e67a10aeec8a27a98e382fd82e1449a451a9a8c3c", + "tests/test_operation_queue.py": "8137528603f015695ed4d60a0c8fa8e7bf0a1c4659f8dc2a181291f5d500e6a1", + "tests/test_owner_probe.py": "deb757e022980f11ef48e57a2fd002ee3e90ec647a4666a0c4d4427313b6f725", + "tests/test_packaging.py": "87a6d04419775c0c5c806e0e569a48d7ef199a0bff8736b211443a1f471e7e8a", + "tests/test_packaging_status_bridge.py": "cbfaeac070a1494a1d8609fc25e9a779a63354c8914b4c6c57fdc7c31b70d472", + "tests/test_pcb_bridge.py": "527fb63147a203a2e9419da989aff600d3e461580989e39e8ede3a8cc57b901a", + "tests/test_pcb_open_consent.py": "ec94b5b73790d7e0caf7140783e73e4a32a21b787f80a427e96fc7083f33535a", + "tests/test_pcb_restore_prompt.py": "a005691d0296587e520e20c4430e9e55227d767c8e910e950a9f2e93aeccb2c7", + "tests/test_pcb_version_choice.py": "0825c28333e4ed4f5a63847b6f5bb11143e922c7203d2770ce9c78fc8edec20f", + "tests/test_post_repair_consent.py": "bf417b378255386dc97ad8efdf5003b0691aa5d69da9d9256aa367dc16a2d4bb", + "tests/test_post_verify_diagnostics.py": "212857e56581998a3a3cd53635030b68a089fc4d630a8b0ee7ef3f137090dcc4", + "tests/test_private_desktop_discovery.py": "5361493313ae6864e252cdb9f2c72e71b39264a1c022beb4cf0c04c143cdd91e", + "tests/test_readonly_status_policy.py": "3ed40d7bdf2d3e6f70b38803b89a8b982336556444b45c6ba6b0a7c6df52a97f", + "tests/test_reimport_recovery.py": "2c0ecf52cd6c393f572c11b5d998a78ef538f7a277668cdc329a03e267074650", + "tests/test_residual_release_dialog.py": "1d5efa03cfe013770e2b81e1fcfb669142f5d6a07957110e56a3cc5eeb57c4a3", + "tests/test_residual_sessions.py": "2c51ed1dc95a3afa7ebb24027963dfa9d13aba9c407e508e22ccc6e9f762dfeb", + "tests/test_review313_residual_isolation.py": "52a8024ed4e2a7fed219fe46cacdf76fa971166feedd557206716ef7f6d3c914", + "tests/test_review326_dispatch_and_receipts.py": "ce4d529246da1c4d53c3dec70ef49542165064404301dec3e32851df62492ecf", + "tests/test_review326_queue_guidance.py": "305662f79251669685a618bdd35d524ef2b37eaece4428bb58ae4c5b65abb8ac", + "tests/test_review345_ui_cli.py": "795e7e4f9bda8874c6a65a08863cab19f4adb3412287276ee2960588f0fd2fa8", + "tests/test_review348_release_comparison.py": "ceccdb3d6f7bc6cb65562c059f13aa2bc5d89d98c6f64b0f11d9b943ebbde165", + "tests/test_review381_queue_release.py": "e0d62424cbf70ec9573db78ede0a4c6534775399194eed4c6b28ba8d468307be", + "tests/test_review391.py": "304d46d63af87ea4a9bca83834b77cc44c5c9addf7b0f3752431304ee612568c", + "tests/test_review414_export_and_audit.py": "ec785c2656bed97de6c8467885f2ad0877b55ee872b02928744d399e8767d8a0", + "tests/test_review414_open_and_queue.py": "db065207dacaccd0bd80af52c1f1edaf36a278e7cf2dce7c9b44bc51dd0e1cec", + "tests/test_review414_write_admission.py": "732a3683c2e27331cd5a9645e062e22613f848cac1a12745744fe249b48a9ffe", + "tests/test_review430.py": "7350f3883ddb9be48cc66fa7b0f612e1b45acf2298c80a7faa3da1f05d6d4c83", + "tests/test_review_319.py": "831fd34d426abb4436b9132bfb7ed754994155a34ac60a59378dee0964b54d28", + "tests/test_review_backend_followup.py": "2f3f51a72ecd05fc33c6b5a8dddaecfd12d2b50df423c87b4c18d1e52b2609bd", + "tests/test_review_foreign_release_evidence.py": "cbf2af02418f6bd3ec720a7a7658cf97f06d1a6e12009fdff2a99f465711591e", + "tests/test_review_management_ui_followup.py": "746602a84c3ba9cb041c5dd354b39d344355b71a3666b27a47eb9aee231e171c", + "tests/test_review_release_followup.py": "8779bde7aaaf59ecf362990afe1d9e7ed4ecb1f6fd7653c08bffbdc296200837", + "tests/test_runtime_timing.py": "7152cd8fedfe165e769dadc1238c347d9f4d3e93cd57f6ed991e14d959e720f7", + "tests/test_safety.py": "ccf5febaf0a974d5e5357398a6946d3f121e07a6247c2f0dc5b71d86b39cac52", + "tests/test_save_helper_identity.py": "178a68c4a9a8c618dad3d8393e816dd1d2a16aef8d1fb9984117fe9dc8d06add", + "tests/test_save_helper_runtime.py": "00b092ec799da4bca424e1ee63a83bee783c81dbcdc20b7526fda8b45bb4b72a", + "tests/test_scan_isolation.py": "cab02bfe55ed515f889d3fcba6e6880344f482cc3a78a072b543b7a871cf92ab", + "tests/test_scoped_manifest.py": "fe9b2047d2c43812e851dd89ff250a2e5907dda89b3f5d9ae0a4dc4c5f452eac", + "tests/test_session_record.py": "6b51b19adfb232275195da7ff1ba91a5ce5e296f9424a7a1a29fc67ecfdfb108", + "tests/test_status_bridge.py": "fe1c0632d4d5fd5a1caf221903d4cfe38eda62aaa4298e3438735e31b8459ab2", + "tests/test_status_bridge_server.py": "7d8cd72d69afae0f96ebbd9bb3be2ae3c222f01108e45ab51a09e54d4d8527cc", + "tests/test_ui.py": "ec0aad6d58b81a42129709b4cbeda9e754be48c6107a5b12384f75170c983463", + "tests/test_ui_batch_safety.py": "12a8d82d4aedbeee315a02a49ec0e9888547ad4abd63e181e7f392b2a39e26dc", + "tests/test_ui_filters.py": "d542e3d6fbc8cff64229b31ea8d0ed14ae0fe0c2c03b6a6eefed2f57dfbe77c9", + "tests/test_ui_lease_lifecycle.py": "18ea8af868373fa795a4911754be55068fe75833ce35579c1212fd7f4713f149", + "tests/test_unattended_prompts.py": "9dff94c678af95b796dfc068bb478de720547dad0b341a63195ca97710f2c4af", + "tests/test_verify_diagnostics.py": "b6431194e9f4c86a42110cac0d5f712c27b063f43b4ce820327aded81602908c", + "tests/test_verify_probe.py": "aeb65b5bd2df14e8a8f3ba5501855b5946e6f8a22f0d26960c00ff1b0daea56b", + "tests/test_verify_runner.py": "e58619f55873302c39129ce50e50fb25173a96ab309d975aa4f47f0bd3459fbb", + "tests/test_verify_worker_stability.py": "eae03400c2e3c8a0bc339c8dc05d890403c6bfb4c6d70d0361bc1b882b47d618", + "tests/support/runtime_lifecycle_frozen_boundaries.py": "bf98533a1c06ccf4453d20b3804323779719e697141b8dc64fa679960a979cfd", + "tests/support/runtime_lifecycle_frozen_fixture.py": "b87761c06a300f0d93bce864d3d31e045f2135324b2a9a42f8682ccbff09ad22", + "tests/support/runtime_lifecycle_frozen_smoke.py": "65b530d1e18b35918595eddc7cedeb31ff204cc785b1dc3c0d8c0b87f4aba0a5" + }, + "production_logs_read": false, + "mentor_started": false, + "production_library_modified": false, + "published": false, + "automatic_icdb_repair": false, + "limits": [ + "Only confirmation-message waiting is changed; global busy/queue/I-O locking design remains unresolved.", + "Native write, real occupancy and exact process/window checks still govern continuation.", + "Native Mentor unattended end-to-end, Windows 10 and cross-machine SMB not accepted.", + "File selection and configuration forms require valid input; unknown native prompts are not guessed." + ] +} diff --git a/docs/releases/2026-11-16-unattended-prompts.md b/docs/releases/2026-11-16-unattended-prompts.md new file mode 100644 index 0000000..d454d3e --- /dev/null +++ b/docs/releases/2026-11-16-unattended-prompts.md @@ -0,0 +1,47 @@ +# 无人值守弹窗默认动作 + +从 beta.3 主分支 `e4875b4` 开始的本地修改。此记录不是云端发布公告。 + +## 之前修复为何仍有阻塞 + +此前以局部失败案例逐处增加保护,未完整验证各层的组合。界面 busy、原生队列、库租约、历史检查点和会话释放共同决定能否继续;释放动作还可能等待被阻塞的同一队列。 +“发生错误”“本任务仍占资源”“外部占用”“界面正在执行”几种状态未充分分开,导致恢复入口也被保护条件禁用。 +单项失败后继续的用例通过,只覆盖了可返回的失败;没有覆盖首次读库带锁、取消、换库、释放及关闭的完整闭环。 + +本轮只消除确认弹窗无限等待,并给出明确默认动作;全局队列及锁的结构问题仍需单独修复。 + +## 默认动作 + +所有下列消息框显示倒计时,在可见且无人选择时 3 秒后执行指定默认动作。 +手动选择、关闭窗口会停止本轮倒计时;不会在窗口消失后执行旧操作。 + +| 场景 | 默认动作 | +| --- | --- | +| 已点击执行的普通校验、ICDB 批量检查 | 确认开始 | +| 已预览并提交的新增、替换、移除 | 确认执行;原有逐项检查及人工备份提示仍在 | +| 已选择完整来源的备份恢复确认 | 确认执行;副本验证及安装前检查仍在 | +| 已明确请求的原生取消 | 确认发出原生取消请求 | +| 已进入释放流程的“关闭前保存” | 保存后关闭;不默认放弃未保存内容 | +| 未知原生客户端占用确认 | 跳过本项,不给未知客户端授予写入许可,不取消整批 | +| PCB 提示上次未正常关闭或仍被占用 | 跳过本项;实际释放成功后才能执行下一项 | +| 原生历史版本选择 | 沿用用户此前明确偏好的“最后手动保存”;该候选不可用时取消本项,不改选自动保存 | +| 强制结束客户端 | 取消,不自动强杀 | +| 结果通知、原生详情通知 | 关闭;记录仍保留 | + +选文件及填写来源等配置窗口需要有效输入,不猜测工程路径。 +未识别的原生弹窗不猜按钮,也不使用鼠标前台抢占。 + +## 证据与边界 + +OpenChoice / RestoreChoice 保留一次选择,新增 `decision_origin=user/timeout_default`;原生 PCB 选择记录与动作载荷写明来源。 +未知客户端超时默认跳过,不生成“用户已确认无人使用”的许可;逐项结果保留超时原因。 +所有原生身份、窗口按钮、地址记录、文件占用、保存和释放证明照常执行。 +倒计时不会解除真实资源占用,也不代表 ICDB 已修复或工程 READY。 + +测试包括实际等待 3 秒、人工提前改选、首选版本不可用、窗口隐藏/关闭后计时失效、一次性决策以及选择来源。 +测试不使用生产日志,不启动生产 Mentor 工程。 + +最终全量 1937 项、逐按钮及弹窗集成 100 项通过,编译及差异检查通过。 +首轮全量发现通知框重复创建标准按钮导致计时对象失效,已删除重复创建;首轮失败证据保留。 +完整散列和测试记录见 `2026-11-16-unattended-prompts-validation.json`。 +当前仅本地源码提交,没有重新冻结、推送或更新生产发布包。 diff --git a/docs/releases/2026-11-17-issue15-acceptance-matrix.md b/docs/releases/2026-11-17-issue15-acceptance-matrix.md new file mode 100644 index 0000000..dd0fa02 --- /dev/null +++ b/docs/releases/2026-11-17-issue15-acceptance-matrix.md @@ -0,0 +1,132 @@ +# Issue 15 acceptance matrix + +Refs #15. The final grouped review wave is implemented at `c1e2596` (B14). The complete suite passed **2,418 tests in 594.83 seconds**, actual exit code 0, with zero failures, errors or skips. Actual B13 ordinary Verify/Stop with automatic candidate-owned cleanup and cross-owner queued Versions passed; actual B13 CBB recovery passed source and target verification. B14 preserves explicit ordinary release promotion of an existing cold observer; that narrow change has source/real-process coverage and updated frozen checks. Native cases retain B13 identities. The final scoped independent review passed for 32dcd80..8869093: I1-I3 addressed; zero Critical/Important/Minor findings. This is a technical review, not field acceptance or merge/release approval. + +## Executable bindings + +Each case retains its actual executable hash. Rebuilds checked all packaged modules/resources and repeated the affected operation plus common frozen smoke; earlier passes are not relabelled as tests of the newest executable. + +| Build | Code commit | Executable SHA-256 | +|---|---|---| +| B1 | eaff46e | `24201dac278ea91fbc7f1b50146a10e024d4c4bf0da14ec5ecbeedbac65104a0` | +| B2 | fd50805 | `a75414653a399cfc76633cad25544d57749ab5a8b49ef227d0a0833f8828257f` | +| B3 | e0bb243 | `aae0039bfcdcb21ea3d25156920a4124a510a10ac499049604550eddc2ab7645` | +| B4 | de81bbf | `f87e403ee5a4891cff82649f5fef573cd304e5052aa3954faaaf43fd94b2ae88` | +| B5 | 4402486 | `b52b8689dc66cfccbf94d578a23de3021fc6857933d9bea38b77038c3711d721` | +| B6 | d5d1a3d | `f60e2eef44462f590ad81c94c0d2479cd017d519a7e176b34ee45258aae14690` | +| B7 | 845ae58 | `dcdcd33e7909c8d1d3b616ef722734f630ea2f793e7bd162e7e8e722978baf9b` | +| B8 | 7cc65f7 | `e1ba9e057d8147fcf451dd419d63660d507a29c96402b174f8824ed6a8ec159d` | +| B9 | a3f69de | `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083` | +| B10 | 701e5cd | `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` | +| B11 | 8818fa9 | `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98` | +| B12 | 906cfc0 | `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc` | +| B13 | 5e9509e | `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` | +| B14 | c1e2596 | `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c` | + +B9 ZIP SHA-256: `4c589bae6bf7b68732cd7ebe373b2924016c71f6731fd661c1cd0fd848427438`. All 68 packaged modules and required assets/scripts/bridges/icons match the source; all 242 extracted files match the build. Its five pre-cancelled worker entry routes and common GUI/worker/owner-probe/dialog-agent smoke passed without launching Mentor. B8 is separately archived with ZIP SHA-256 `795010cc0b54b995eced859cac1513bf105092e484a44b1231955801deed879f`; B5 retains ZIP SHA-256 `176c7cda89c2a2706f969fa6dca513d2760615491aaf70c19fe7a0688abe471a`. + +B10 ZIP SHA-256: `d4bd42416ea8d12a249ff1d9c8854eb76d2f81bb7ff869ff43dd92a331c647a0`; 68 modules/resources and 242 extracted files match, five pre-cancelled entries and common smoke passed. Only the residual-session module changed from B9. Earlier actual cases retain their original hashes. + +B11 ZIP SHA-256: `34b3646b27afae22ec43a415ca19bbd32a91c0a4c941d37d6289c76cea9ca730`; the same module/resource/file checks, five cancelled entries and common smoke passed. Its only source-module change from B10 records each acknowledged Tip per cleanup intent. Immediate/delayed Tip states with/without prior Close passed focused source tests; no new actual Mentor Tip replay is claimed. The harmless real Win32 adapter probe belongs to the B10 source stage; its unchanged adapter preserves hidden MDI siblings and sends no action with an extra document. + +B14 ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`; 68 modules/resources, 242 extracted files, five cancelled entries and common smoke passed. B13 actual native cases retain their original hashes. B12 failed late ordinary cancellation remains archived with its exact identity. + +## Reported issues A–H + +| Issue | Source verification | Actual frozen evidence and limits | +|---|---|---| +| A: cancellation leaves startup prompts/clients | Exact ownership, known prompts, cooperative cancellation, admission and shutdown coverage; late Tip after first Close, held identity, delayed launcher, no second Close, unknown/document/progress/write negatives; single legacy release intent and observer proof. | **REPRODUCED on B5:** Stop 0.797 s after registered PCB startup returned CANCELLED/safe=false with a late Tip and retained PCB/launcher. Manual Tip OK alone completed the existing close; that remains a failure. B8/B9 automatic release and B9 one-confirmation legacy release passed separately, as detailed below. | +| B: another project's address blocks release | Scoped resources, exclusive Windows handles, fresh proofs and independent-item continuation. | B5 Release UI confirms zero active sessions and released library ownership. Earlier metadata handoffs and a separate bounded file-probe timeout remain failures; no native lock/address was manually deleted. | +| C: Versions conflicts with the parent's lease | Parent/child handoff, worker admission and reopening tests. | B1 official Repair, manual backup, exact-version restore, backup verification and reopening succeeded on the selected copied project. Tool exit alone was not counted as successful repair/restore. | +| D: historical records block unrelated/retried work | Legacy evidence is rechecked; a new confirmed operation requires fresh scoped release proof. | B3 corrected 8212 update succeeded in the same data root after the earlier failed operation. The original failed journal remained unchanged; later recovery and B operations continued. | +| E: optional LM dispatch returns without starting PCB | Bounded dispatch observation, exact target binding and owned-LM cleanup. | The direct native route passed. The exact optional-LM dispatch failure is **NOT REPRODUCED**; Windows 10 is **NOT RUN**. | +| F: Save finishes but library remains pending | Unique project/PCB binding, reference alignment and authoritative READY gate; Save/Close/exit/release are distinct. | B2 B-control first Verify remained PENDING and correctly failed; one explicit retry passed GREEN. B3 recovered 8212 source and installed target both passed GREEN. First-pass noncommit cause remains unconfirmed. | +| G: copied database is inconsistent | Diagnostic routing, manual recovery entry and error precedence; automatic Repair stays disabled. | B1 healthy-control Repair passed. Original complete fault-bearing field snapshot is unavailable: **NOT REPRODUCED**. Constructed-copy result is reported separately below. | +| H: selection/input/results/confirmation gaps | Real Qt controls, immutable requests, stale-view protection, one-shot defaults and large-table filters. | B1 basic controls/Add, B2 wrong-source rejection and concurrent view changes, B3 stop-after-current/recovery/removal/reimport, B4 restart without replay, and B5 diagnostic handoff/Release were exercised. Conditional controls are identified below. | + +## Important native receipts + +These identifiers locate retained local evidence; raw field files, private machine/user identifiers and production paths are not published. + +| Build / operation | Receipt | Observed result | +|---|---|---| +| B1 duplicate A then independent B Add | management-c74c9a2b226e4df382be1447d2c9da95; management-4174be063d7843c69406e6610b4cc084 | Duplicate safely rejected; B UPLOADED with native registration/project/top/Layout confirmed. | +| B1 manual Repair / backup / restore / verify | native-backup-ed65d2630b3c | Actual native success output; uniquely described archive and restore location checked. Archive SHA-256 `429195ff63fd76e3586a348357009e4638c06d2d2c27c38e5cdee63f6966d26a`. | +| B1 Versions reopen | native-backup-de1ef77062a4 | Correct project/backup catalog; normal exit and release. | +| B2 fresh-source diagnostic with external observation | icdb-check-455c02cfba8f / verify-d67aa6df8758 | CHECKED/safe; 261 read-only snapshots show Forward Annotation prompt disappearing and loading progress ending before Close. No manual native action. | +| B2 B ordinary Verify | verify-491e77340ae2; verify-742c401bec4f | First FAIL/PENDING despite completed Save/Close/release; separate explicit retry PASS/GREEN with reusable-cell save confirmation. | +| B3 8212 update and actual stop during Add | management-78e5a9b3f24b4353b778a540c6f67e56 | Stop clicked during exact registered LM NATIVE_CALL. Current item completed Add, authoritative readback and release: UPLOADED/safe. | +| B3 CBB backup recovery | backup-restore-4c7aad5bd125 | Source verify-2c4769255397 and target verify-adad45363659 both PASS/GREEN; installed=true; old Work retained; both COMMITTED/CLOSED/EXITED/RELEASED. | +| B3 B remove and reimport | management-c156db77b0c449a0b0e034891aeaacff; management-15a95455d14541e4a47a3b4b2126c8a7 | REMOVED with authoritative catalog absence, then UPLOADED from the independent source. Auto-verify off. | +| B4 restart | restart-before-06 / restart-after-06 | Operation-root sets unchanged and no native process before explicit Read: no automatic replay. | +| B5 diagnostic intent/ack/Close | icdb-check-8683e232ce83 / verify-755f3af6b650 | CHECKED/safe, 38.437 s; exact intent/ack/Close identity and nonce match; intent precedes Close by 0.125 s. | +| B5 explicit Release | sessions-e4c27855ec69 | UI and durable RELEASE_CONFIRMED agree; zero active sessions, 7.704 s. Exact file-probe helper returned HELD and exited normally; read-only observation sent no target control action. | +| B5 early native Stop — original failure | icdb-check-63f7ee04d30b / verify-719b874e0aaf | Actual Stop 0.797 s after PCB registration, before loaded readiness: CANCELLED at PCB_STARTING, 31.875 s, safe=false, native clients retained. 894 read-only snapshots showed the late Tip. Manual exact Tip OK allowed both clients to exit with no further Close, Save, annotation or force action. | +| B6 early native Stop — loaded-target transition | icdb-check-762d0b790c2c / verify-67752f3332dd | Stop 0.813 s after PCB registration: Tip was automatically dismissed before any Close; target then loaded and showed Forward Annotation. CANCELLED/safe=false, 31.625 s; 892 read-only snapshots. Manual exact Forward No, then one normal target Close after progress ended, exited both clients without Save/annotation/force. This failure prompted the bounded cancelled-diagnostic loaded-target cleanup. | +| B7 late exit after bounded cleanup | icdb-check-ac97c21a1863 / verify-0a4f641d37d3; sessions-98a1beebfb10 | Automatic one Close and late Tip dismissal; native exit followed the original deadline. Original CANCELLED/safe=false remained. A later manual Release obtained fresh proof, so this did not establish automatic observer release. | +| B8 automatic cancellation and prequeued Versions | icdb-check-64348b7f55c5 / verify-505a4f09d4e7; native-backup-073e59195f9b | Versions queued after PCB registration and before Stop; UI terminal 7.125 s. Automatic Tip/Forward No/one Close, natural exit, existing observer RELEASE_CONFIRMED. Queued native client created 2.075 s after proof and catalog loaded. No Release click/manual diagnostic native action; original CANCELLED/safe=false retained. | +| B5-to-B8 legacy release — incomplete workflow | icdb-check-17661d31889d / verify-4b7bc47b39f8; sessions-12c1715f5d7f, sessions-38ed41c344f8, sessions-2cca647d90da | Initial inspection handed off before a plan; Recheck succeeded. First confirmation declined Forward but did not close; second closed PCB/launcher while server remained; third obtained fresh proof. No manual native action, but multiple confirmations were required: not accepted as the intended final workflow. | +| B9 automatic cancellation and prequeued Versions | icdb-check-b05147dc18bc / verify-3abaddb3e141; native-backup-005da267ebfe | Versions queued before Stop/handoff; UI terminal 6.672 s. Automatic Tip/Forward No/one Close; 307 read-only snapshots and kernel exit. Existing observer obtained fresh library RELEASE_CONFIRMED; queued native client created 1.684 s later and catalog loaded. Zero Release clicks/manual diagnostic native actions. Original CANCELLED/safe=false retained; backend duration 12.829 s is distinct from UI timing. | +| B5-to-B9 legacy release — one confirmation | icdb-check-378044ad1122 / verify-d2acda2739c2; sessions-a5a9fe06b7c1 | Real B5 retained loaded target/Forward; old app normally exited. B9 initial inspection succeeded, one normal Confirm, zero Recheck/second confirmation/manual native actions. Forward disappeared after 3.562 s; 210 read-only snapshots show kernel exit. PCB, launcher and server RELEASED, fresh RELEASE_CONFIRMED at 22.634 s; UI agreed and Confirm disabled. Existing cold observer RELEASED; original cancellation result retained. | +| B10 I3 setup — second pending item | management-f25df6a207ca4744ab4a0c23ddabb06c | Legitimate exact-name update from the existing healthy source, auto-verify off; UPLOADED/safe, native catalog/readback. Prepared two pending items without fabricated native failure. Selection made before final refresh was cleared; disabled Verify rejected the harness click; reselection afterward succeeded. | +| B10 ordinary Stop — historical failure | verify-e464474b7bab; batch-20261117-105152-c3e162 | Actual Stop 0.547 s after PCB registration, no Save evidence: first CANCELLED/safe=false, 29.766 s; second SKIPPED with no native job. Later loaded Forward remained. Exact manual No, no-modal/no-progress check and one normal Close required; sessions-4aadbacb8a93 then fresh release. Not unattended PASS; ordinary cleanup does not have diagnostic-only authority. | +| B10 actual Continue, no replay | button-watch-1794884270925407000; verify-f673ac48f600 | Existing summary's three-second Close elapsed before inspection. After main-window Release proof and normal dialog close, production code recreated Continue. Actual button click started only the previously skipped second item, which passed GREEN/safe. First terminal result predates the click and no first-item job was replayed. No in-process method/result injection. | +| B10 actual result Release | button-watch-1794884430968047900; verify-4f959f61fbc4 | One bounded same-scenario timing repeat caught actual result Release and opened its residual plan. Ordinary Stop again retained Forward, 32.844 s; this remains a failure. Exact manual No/normal Close, no Save/force; sessions-6bfdf0a26476 fresh release. | +| B5-to-B10 affected legacy release | icdb-check-92a3c92f6d6c / verify-9f3856153c79; sessions-82cc60b6eacb | Initial inspection succeeded; one Confirm, zero Recheck/manual native actions. Forward disappeared +6.5 s; 278 read-only samples/kernel exit. Intermediate PARTIAL then fresh RELEASE_CONFIRMED +35.387 s under the same intent; all three clients and existing observer RELEASED, UI agreed. Original CANCELLED/safe=false preserved. Entry was loaded Forward; actual Tip replay is not claimed. | +| B12 ordinary Stop — late loaded failure | verify-642171759614 | UI terminal 7.797 s; loaded Forward at 34.406 s after original cleanup deadline. Manual exact No/normal Close required. Failed-run cleanup only; original CANCELLED/safe=false preserved. | +| B13 ordinary Stop / cross-owner queue | verify-71aee0603183; native-backup-b63e7f708fd5 | Actual candidate worker No/one Close before first 30 s deadline; late kernel exit and fresh candidate/independent proofs. UI terminal 7.375 s; real Versions creation 5.220 s after candidate proof and 1.506 s after independent proof, catalog loaded. No Release/manual ordinary native action. Retained-phase No/Close branch not replayed in Mentor. | +| B13 CBB backup recovery | backup-restore-3f98efb14448; source verify-06c8149375e6; target verify-f902921f2440 | Both PASS/GREEN/safe and COMMITTED/CLOSED/EXITED/RELEASED, installed=true; old Work retained, all 366 original source files unchanged, no native intervention. | + +The B2 diagnostic run supports the implemented sole-handler No sequence through observed windows and verified code; there is no separate startup button acknowledgement event. The hidden-owner-chain save branch did not recur on corrected native runs and remains covered by regression tests plus the original captured chain. The original failed diagnostic required manual cleanup and a native crash acknowledgement; that crash was **NOT REPRODUCED** in the subsequent bounded runs. + +## Buttons and misuse scenarios + +| Controls / scenario | Source coverage | Frozen coverage | +|---|---|---| +| Tabs, advanced options, optional LM checkbox, runtime log toggle | Actual source UI and Qt tests | B1 actual navigation/toggles. | +| Library chooser Open/Cancel and Read CBB | Actual chooser/catalog; invalid-input tests | B1 chooser cancellation and catalog; B3 removal/reimport catalog; B4/B5 explicit reload. | +| Select visible, Clear, filter/hidden selection | Actual UI and 381/3,000-row Qt checks | B1/B2 actual controls and view changes; immutable original operation retained. | +| Verify selected / visible non-READY | Actual source native verification and Qt admission | B2 ordinary Verify; B3/B13 recovery target verification; B13 actual ordinary Stop and automatic release. READY exclusion remains enforced. | +| ICDB batch confirmation No/Yes and stop | Actual source checks; Qt stop/continuation | B1/B2 confirmation cancellation and diagnostic runs; B5 acknowledged close; B8/B9 actual startup Stop and automatic queued continuation. Other cancellation timing remains conditional. | +| Manual Repair Cancel/Confirm | Actual native healthy control | B1 native diagnostics/defragmentation; not field-fault recovery proof. | +| Versions / create backup / restore Cancel/Confirm / verify / Close/reopen | Actual exact archive and location | B1 native tool operations and reopening. | +| Add / source chooser / empty input / auto-verify / logs / No/default Yes | Actual source and Qt | B1 duplicate-plus-independent Add; B3 reimport. | +| Same-name update / wrong source / reselection / No/default Yes | Actual source and Qt | B2 mismatch rejected before writing; B3 correct update. | +| Remove / hidden source chooser / No/Yes / result | Actual source and Qt | B3 REMOVED and native catalog absence before reimport. | +| CBB backup recovery / empty input / chooser Cancel / No/Yes | Actual source and Qt | B3 original controls/full sequence; B13 full serial metadata/source-validation/install/target-validation sequence. | +| Management stop-after-current | Two-item Qt/real admission tests verify next item skipped, including failed readback and unknown release | B3 stop during native Add; mandatory current-item readback completed. | +| Queued cancellation / active dialog close | Qt queue, close, hard-cancel and shutdown tests | B10 recovery dialog queued behind an owned diagnostic, Cancel queued clicked, UI CANCELLED/no native admission/no recovery job. Underlying diagnostic verify-96d285ffa450 completed CHECKED/safe. Earlier second management submission/active lower Close remained disabled. | +| Residual sessions / Recheck / Confirm / Close | Qt exact scope, one-intent observer promotion and real Windows proofs | B5 zero-active-session release; B9 initial inspection and one-confirmation release of a real B5 cancelled session; previous failed/multiple confirmations retained. | +| Native details / Save prompt / native Cancel / forced termination | Qt exact ownership/prompt and default-Cancel tests | Disabled with no matching active owned client. No forced native termination claimed. | +| Conditional result recovery/release/resume buttons | Qt target binding, stale results and single continuation | B10 actual result Release and Continue/no-replay receipts above. B10 ordinary retained startup required manual cleanup; B13 automatic ordinary Stop acceptance is recorded separately below. Other fault-dependent recovery branches are not blanket passed. | +| Three-second defaults / manual-vs-deadline / hidden or closed prompts | One-shot Qt timer tests | Actual management/recovery No and timed Yes; full timing competition covered in Qt. | +| Double submission / result remaining open / view changes / restart | Qt and Windows lifecycle tests | Active execute controls disabled; modeless dialogs and view changes observed; B4 no replay. | +| Open logs/evidence / shell errors | Qt dispatch and error reporting | B10 actual Open logs/Open exception clicks opened exact application logs and verify-e464474b7bab folders; complete private Explorer breadcrumbs recorded. Only the two task-created Explorer windows normally closed. No shell-error case is claimed. | + +One B1 harness edit targeted the library textbox while a modeless dialog changed control indices. The immutable original-library operation still completed and the changed view was invalidated. This is retained as a harness/misuse event, not a product search failure. + +## Final-wave evidence and limits + +B14 EXE SHA-256: `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c`. ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`. All 68 packaged product modules/resources and all 242 extracted files match source/build. Five pre-cancelled frozen routes and common GUI/worker/owner-probe/dialog-agent smoke passed. Full-suite log SHA-256: `d9c57b7998e02154fb703f0fe2ba1f37f73dc4687d116c4b6efc0e5ad7e5c30e`; JUnit SHA-256: `4303cc123e90689103cc4135e483ac936b04a052067e952a1861ae167c7811ea`. Native clients and writer/management mutexes were idle before and after the full suite. + +B13 (`5e9509e`) retains EXE `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` and ZIP `7a1da94e05b85873f791cde77907bdc280106768fbf84e5d89066ab8aa57a61b`. A final self-audit found that the new ordinary explicit-release branch bypassed existing cold-observer promotion. Its focused test failed before the two-line ordering correction at `c1e2596`; 110 related tests then passed in 21.96 seconds, including actual harmless worker exit, cold-observer promotion and queue proof. The in-progress B13 full suite was interrupted through its own execution session before editing, and is archived without a completion/JUnit claim. No additional native matrix was run for this narrow B14 delta. + +The three review defects had retained RED evidence: actual MainWindow subprocess exit hung on stalled hash/copy/validation; real recovery callers held the unrelated native channel and could install after abandoned metadata; ordinary cancelled startup failed to clean a later loaded target. B13 related observer coverage passed 232 tests in 34.81 seconds, including an actual two-process mutex/file race between observer and explicit release plus a process restart. These race tests stub the native evidence/action boundary; they are not Mentor window tests. + +B12 (`906cfc0`, EXE `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc`, ZIP `bbe68005469d8b6cf87726200ef85646e442de45d164ab2ac0aec23b51d0bd65`) retained a new failure: ordinary `verify-642171759614` returned its visible cancellation terminal state in 7.797 seconds, but Forward loaded at 34.406 seconds, after the worker cleanup budget. Exact manual No/normal Close was used solely to clear that failed run. A later independent queue-helper attempt was refused with sharing violation 32 before native creation while two releasing observers raced for the coordination lease. Both failures are archived and are not relabelled as B13 passes. + +B13 ordinary `verify-71aee0603183` reached the visible terminal state in 7.375 seconds. Its candidate worker acknowledged Tip at 21.359 seconds, Forward No at 27.422 seconds and one Close at 28.750 seconds; native exit followed the original cleanup deadline. Read-only sampling confirmed kernel exit. The original result remains CANCELLED/safe=false. No Release click or manual ordinary native action occurred. The helper stayed observe-only until the actual candidate produced fresh RELEASED proof, then obtained its own independent fresh proof. Its prequeued real Versions client `native-backup-b63e7f708fd5` was created 5.220 seconds after the candidate proof and 1.506 seconds after the independent proof, loaded the backup catalog and closed normally. This is **cross-owner queue acceptance**, using source-hash-pinned production queue/observer/native-worker modules; it is not survival of work in the same app after global Stop. The candidate itself performed every ordinary No/Close action. + +The B13 native run issued Close within the first worker budget, so the new retained-phase No/Close branch was **NOT REPLAYED in Mentor**. That branch has source guard, real process race/restart and existing real Win32 adapter evidence. No repeated cold-start attempts were used to manufacture a slower launch. + +B13 actual recovery `backup-restore-3f98efb14448` used the current pending original target and healthy independent source A. Its isolated source and installed target both returned PASS/GREEN/safe; native save/close/release completed without intervention. The old Work directory is retained and all 366 original source files are unchanged. The 27,689-file complete validation library copy progressed through the serial metadata path without a false inactivity handoff. + +Separate frozen metadata-exit harness EXE SHA-256: `7490be1988d823944307510f7cfd22c85cf8570c7c25f6ee60d97f542bb72753`. All 68 packaged product modules equal final B14. A disposable I/O stall at each of hash/copy/validation exercised actual MainWindow close and interpreter exit before releasing the stall; no late dispatch occurred and partial copies were retained. This uses an acceptance-only entry, **not stall injection into the candidate EXE**. The earlier B12/B13 harnesses and all RED/setup attempts remain archived. + +The original complete fault-bearing field snapshot remains unavailable (**NOT REPRODUCED**); the constructed partial copy remains **COPY_BLOCKED** and was never opened. Windows 10 and production SMB remain **NOT RUN**. The earlier first-pass B-control PENDING result and explicit retry remain separate outcomes. No merge, publication or issue closure is performed. + +## Constructed copy and remaining limits + +Constructed-copy experiment: **COPY_BLOCKED; inconsistency NOT REPRODUCED** (1 attempt, maximum 3). The healthy control passed normal native Verify. On a separate disposable copy, the documented native property write and stock Save actually ran; ordinary Work copying encountered Windows sharing violation 32 at the 113th attempted file, database/icdb.dat, after 0.470 seconds. The source still completed Save/Close and authoritative PASS/GREEN with released resources. The partial clone was never opened and no native Repair claim is made for it. This fault-creation instrumentation did not modify the frozen product and does not reproduce the original field incident. + +The original field inconsistency remains **NOT REPRODUCED**. Windows 10 and production SMB/network behavior are **NOT RUN**. Initial B-control PENDING results, diagnostic/manual-cleanup failures, metadata handoffs and the bounded file-probe timeout remain visible in the evidence. This report does not authorize merging, release publication or issue closure. diff --git a/docs/releases/2026-11-17-issue15-runtime-unblock.md b/docs/releases/2026-11-17-issue15-runtime-unblock.md new file mode 100644 index 0000000..715258e --- /dev/null +++ b/docs/releases/2026-11-17-issue15-runtime-unblock.md @@ -0,0 +1,114 @@ +# Issue 15 runtime and recovery candidate + +Refs #15. This candidate records local Windows 11 acceptance and its limits; it is not a published release or field-acceptance approval. + +The final grouped review wave is implemented at `c1e2596` (B14). The complete suite passed **2,418 tests in 594.83 seconds**, actual exit code 0, with zero failures, errors or skips. Actual B13 ordinary Verify/Stop with automatic candidate-owned cleanup and cross-owner queued Versions passed; actual B13 CBB recovery passed source and target verification. B14 preserves explicit ordinary release promotion of an existing cold observer; that narrow change has source/real-process coverage and updated frozen checks. Native cases retain B13 identities. The final scoped independent review passed for 32dcd80..8869093: I1-I3 addressed; zero Critical/Important/Minor findings. This is a technical review, not field acceptance or merge/release approval. + +The PR base is main at e4875b4. The branch also includes the previously approved efb8cae three-second confirmation defaults. + +The change separates native task execution, client exit, coordination-lease release, data recovery and eligibility for the next write. A completed independent item no longer inherits another project's address or a stale historical blocker. Unknown ownership still requires fresh proof; the application does not delete native address or lock files. + +## Final grouped review fixes + +- Ordinary pre-document cancellation now requires positive supervisor and worker no-write events, a bound prelaunch log baseline, and exact worker/process/project/private-desktop identity. Potentially mutating supervisor actions and integration admission revoke this authority before dispatch. Proven no-write startup uses one 30-second cleanup budget and the existing five-second UI handoff; unproved ordinary cleanup and active-write waiting retain their existing policies. Ordinary global Stop still cancels its own queue. +- A late loaded ordinary target may enter one separate retained cleanup phase only after its original worker/helpers have exited and fresh complete loaded evidence is available. The existing observer persists the intent and absolute 30-second deadline in the existing session record before any action, under the existing native management mutex. Duplicate observers, explicit release and process restart cannot start it again. Prior No/Tip acknowledgements and the sole Close remain deduplicated. Unknown or multiple documents, changed identities and active writes authorize no action. Cleanup return never establishes release or successful verification; queued writes still use fresh scoped resource proof. +- Manifest hashing/copy/validation now run serially on the existing bounded daemon task. Nested executors no longer keep the Python interpreter alive after real MainWindow closure during stalled metadata I/O. Completed work renews inactivity; cancellation prevents late dispatch and incomplete copies remain available as evidence. +- Backup recovery no longer holds the global native mutex during abandonable metadata work. It retains the exact library lease and completed-work fences. Only the short pair of Work renames, rollback and installed-state update is protected from abandonment; the task registry guard is never held over filesystem operations. Cancellation after that pair cannot start target verification. An OS rename that itself never returns cannot be safely interrupted; the implementation preserves ownership rather than claiming cancellation completed. + +## Implementation + +- Resource release uses exact project/database/library scope and observed process identity. Read-only file probes retain exclusive handles through release commitment. Legacy receipts are rechecked; a proof for one block cannot close another block's session. +- Each UI operation owns its immutable requests, cancellation signal and view revision. Queued work and late callbacks cannot write into a replacement library view. Native writes stay serial; registered worker handles and event admission protect shutdown handoff. +- Fast directory discovery and authoritative native catalog/status reconciliation are separate. Directory-only records are not treated as native entries. READY items remain available for management and are excluded from ordinary verification/maintenance admission. +- Manual Repair and version history open the official tool for the exact selected project/database, including recovery-required projects. The application does not submit Repair automatically or treat tool closure as successful recovery or READY. +- Results and management/recovery/release dialogs remain nonmodal. Three-second defaults preserve one-shot manual priority; unknown occupancy skips, exit saves, and forced termination defaults to cancellation. +- Native acceptance exposed two premature timeouts: successful catalog completion after the metadata deadline, and a progressing complete-library manifest exceeding that deadline. Catalog commit/wait now uses the existing read-only native channel; successful metadata work renews inactivity without changing stalled-I/O limits or native transaction behavior. +- A transient incomplete native-window scan is retried within the original open/close deadlines. Partial snapshots never authorize a control action. Persistent incomplete observation, unknown prompts and identity mismatches still fail closed. +- Same-name update validates the resolved source project name before native removal. A mismatched source remains selectable in the dialog for correction; the UI preview performs no filesystem resolution. The native Add dialog fields are reread immediately before submission. +- Save/Close may close the exact owned Project Integration panel only when all four complete statuses say no changes are pending and the unique Close control is enabled. Native inconsistency/error evidence takes precedence; partial, foreign or pending panels do not authorize closure. +- A new explicitly confirmed recovery attempt can proceed after a fresh release proof for the exact library and block is recorded under that new operation. Old failed journals remain unchanged; default requests, cached proofs and proofs for another target cannot authorize a retry. +- Hidden native worker failures now write compatible result records and tracebacks before exiting. Admission and entered-worker failures remain distinct, existing save evidence is preserved, and exceptions never establish release. This prevents a cancelled frozen worker from blocking on the packaging runtime's error dialog. +- Completed release and occupancy checks now renew the existing metadata inactivity clock. Cancellation and abandoned calls cannot be revived; active native transactions keep their existing continuation rules. This fixes a frozen Add that expired across a successful seven-second release proof followed by two successful occupancy checks before any native write. +- Diagnostic opening waits for an enabled target frame with no visible loading progress. After fresh project/PID evidence, its sole handler declines the exact owned Forward Annotation prompt. A close intent containing the current operation, target identity and nonce requires an exact supervisor acknowledgement after any in-flight dialog poll. The worker then rechecks readiness, prompts, native errors and cancellation before posting Close; acknowledgement consumes the original 30-second close budget. Ordinary Verify retains its own confirmation policy. A nested save prompt is accepted only through the captured, bounded chain of same-process, same-desktop, hidden disabled Expedition dialogs to the exact frame. +- The management dialog's stop-after-current button and active-window close request now stop the batch at the next item boundary. The current item completes its native writes, required directory readback and result bookkeeping. A queued batch can still be cancelled before admission. Global cancellation, shutdown, process identity checks and worker admission remain separate. Real acceptance exposed the former hard-cancel signal interrupting the readback after successful Remove/Add. +- Explicit release renews metadata inactivity after completed process snapshots, owner checks, held-file proofs and durable evidence steps. Multiple successful checks can finish without a false UI handoff; a single stalled step still times out. A late or cancelled proof cannot remove the coordination checkpoint or close the retained lease after its context has been abandoned. +- Actual early Stop reproduced a late Tip arriving after the one normal empty-frame Close. Startup cleanup now retains the original process handle and, within the original timeout, can dismiss that exact known Tip after rechecking the private desktop, empty frame, complete windows and lack of progress/documents/unknown prompts. When Close already hid the frame, only the Tip's direct hidden, disabled owner is inspected; hidden MDI documents also veto the action. The deadline and release Stop signal are rechecked immediately before clicking. It never posts another Close. Normal residual release shares this guarded acknowledgement for already-retained sessions, then waits for exit without forced termination or another Close. PCB exit, launcher exit and resource release remain separate requirements. +- A second actual cancellation race loaded the target after Tip dismissal, while COM/document admission had already stopped. Cancelled diagnostic startup now uses the existing fresh native path/PID logs and exact target MDI identity to decline Forward Annotation and finish one normal Close. Only exact owned No actions are allowed; unknown siblings, foreign identities, visible progress and writes remain protected. The supervisor completes its last poll before creating the cancellation signal, so cleanup is the sole prompt actor and does not wait for a normal-close acknowledgement. Its diagnostic 30-second cleanup budget starts once; an empty-to-loaded transition does not reset it. Cleanup never establishes CHECKED, READY or successful verification. +- Diagnostic cancellation yields to the existing registered observer after a bounded five-second wait; ordinary write waiting is unchanged. If the worker exits before its native clients, the same observer keeps ownership until client exit and fresh scoped release proof. Queue admission waits only for an actual initializing or live observer, so historical caches and unrelated libraries cannot create a permanent wait. The original cancellation result remains historical evidence. Report completion writes only unique application evidence files and can finish while native cleanup continues. +- Normal residual release can recover an older cancelled diagnostic startup using its complete existing registration, terminal worker, exact current native identity/command/private desktop/MDI and absence of Save evidence. That authority permits cleanup only; a missing prelaunch log baseline is never fabricated or treated as successful opening validation. The action rechecks binding immediately before each No or Close and respects a previously recorded close. Partial, foreign, active-write or ambiguous evidence remains blocked. +- One normal Release confirmation gives that proven legacy diagnostic cleanup one 30-second budget, including the known transition after Forward No. It runs in the existing read-only native phase, then the existing registered observer can obtain fresh release proof after late exit without another confirmation. Observer promotion requires the same operation and current Windows user/session; cleanup requires exactly one target MDI document. Ordinary close remains three seconds and ordinary native-write waiting remains unchanged. Pure residual inspection uses metadata-only admission so it remains available during native finalization. + +## Evidence retained locally + +Task 1's durable findings are consolidated here rather than tracking orchestration scratch files. Its final scoped backend coverage was 420 tests after review fixes; those tests cover real Windows exclusive/duplicated handles, scoped receipt trust, cancellation and unknown export ownership. They do not establish real Mentor behavior. Subsequent task evidence and all failed attempts remain in the local acceptance evidence archive; raw field data, process snapshots, host/user identifiers and production paths are not included in this repository report. + +The initial Task 5 full run had 2,111 passes and one obsolete internal test entry. The test now uses the dedicated catalog-only handler while retaining the original mapping-order assertions. A separate regression reproduced child Python importing another editable checkout; test-session configuration now preserves the active worktree in inherited PYTHONPATH without changing machine configuration. + +## Native acceptance recorded so far + +All native operations use complete, hash-verified local copies with main/PCB/database references bound to the selected copied library. Source and frozen runs use independent copies. + +| Source scenario | Observed outcome | +|---|---| +| Native catalog | Four original registered entries and authoritative READY statuses confirmed; fast discovery alone was not accepted. | +| Batch add with first-item name conflict | Existing name rejected safely; independent next source added and confirmed through native catalog/readback. Auto-verify was disabled; the new item remained pending. | +| Manual Repair | Official confirmation cancelled without submission, then explicitly confirmed on the healthy added control. Native diagnostics/defragmentation completed; the native tool also reported a missing optional project file. This is not a reproduced field inconsistency. | +| Manual backup and native restore | A uniquely described manual version was created; exact archive identity and restore location checked. Cancel and committed restore exercised; native restore and backup verification reported success. | +| Versions reopening | Exact restored project reopened successfully; normal close exited with release confirmed. Tool closure alone did not claim repair/restore validation. | +| ICDB check after restore | Initial observation-timeout failure retained; corrected same-button rerun returned CHECKED and safe resource release. It did not claim READY. | +| Release observations | No active clients remained; zero active sessions were reported released while old observation records were cleared. Conditional native save/cancel/force controls remained disabled. | +| Wrong-source same-name update | Earlier attempt exposed a missing name check and retained recovery-required evidence. The corrected UI rejects that source before submission and permits reselection. An audit of 21 major files in three unrelated blocks found no changes. | +| Corrected update after recovery | Exact-name source restored the missing target. A new confirmed update in the original application data root succeeded with a fresh scoped release proof; the old recovery-required journal was preserved. | +| Ordinary verification | Recovered target reached PASS/GREEN with native save committed, document closed, helper exited and resources released, without manual intervention. An earlier different target required manual native panel closure and remains classified as manual intervention. | +| CBB backup recovery | Actual dialog empty-input rejection, chooser cancellation and No/Yes confirmation were exercised. The isolated source validation and installed target verification both passed with GREEN; the old Work directory was retained. No manual native intervention was needed. | +| Automatic Project Integration panel close | The B control's first Verify automatically closed the completed panel and finished Save/Close/release, but authoritative status stayed PENDING and was correctly reported as FAIL. One explicitly requested fresh Verify then confirmed the native reusable-cell save and reached PASS/GREEN. The exact first-pass noncommit cause remains unconfirmed. | + +The first full regression after these changes recorded 2,144 passes and eight fixture failures. Three tests still edited the old project filename, four lifecycle cases used an outdated control-helper signature, and one independent-item test reused a differently named source. The fixture updates preserve the original identity and lifecycle assertions. After the hidden-worker correction and isolation of simulated clients between tests, the full run at that stage passed **2,175 tests in 522.52 seconds**, exit code 0. The previous full regression at code commit 4402486 passed **2,246 tests in 572.82 seconds**, with zero failures, errors or skips and exit code 0. One earlier run was cooperatively interrupted after 2,151 passes when old test doubles contaminated the new entry tests; its stack and interrupted result are retained separately. Compilation and diff checks also passed. + +The previous complete regression at code commit a3f69de passed **2,351 tests in 497.58 seconds**, exit code 0, with zero failures, errors or skips. Log SHA-256: `aa820f1202becd30ee220c8e660fcde0e063d9ed874023ab3487108aedae214d`; JUnit SHA-256: `7d951ad853978e58aabaa481656c15b8610f01fdf9d64f67af0585dda9bc3bbe`. Actual native applications were normally closed and the writer/management mutexes were idle before and after this run. + +The previous candidate B9 is built from code commit a3f69de. All 68 packaged modules, assets, bridge programs, scripts and icon images match; all 242 ZIP-extracted files match the build. Executable SHA-256: `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083`. ZIP SHA-256: `4c589bae6bf7b68732cd7ebe373b2924016c71f6731fd661c1cd0fd848427438`. Five actual pre-cancelled frozen entry routes exited without acknowledgement or termination and wrote the expected results. Common GUI, worker, owner-probe and dialog-agent smoke passed. + +B9 repeated the two affected native cases. Versions was queued after exact diagnostic PCB registration and before Stop. The UI reached its cancellation terminal state in 6.672 seconds; the original result remains CANCELLED/safe=false. Automatic guarded Tip/Forward No/Close cleanup and the existing observer produced fresh library release proof; the queued Versions native client started 1.684 seconds after that proof and loaded its backup catalog. No Release click or manual diagnostic native action occurred. Separately, B5 produced a real cancelled, loaded-target legacy session. B9's initial inspection succeeded and one normal Release confirmation released the PCB, launcher and database server with fresh RELEASE_CONFIRMED proof in 22.634 seconds. The UI agreed and disabled Confirm; no Recheck, second confirmation, manual native action, Save, annotation or forced termination occurred. The old cancellation result was retained. The earlier B8 legacy path required multiple confirmations and is preserved as an incomplete workflow, not a final pass. + +The [acceptance matrix](2026-11-17-issue15-acceptance-matrix.md) records each native case against its actual executable hash. Earlier successful cases remain bound to their original builds; they are not relabelled as new-build tests. The constructed-copy experiment ended with Windows sharing violation 32 at database/icdb.dat during native Save. Its source passed GREEN and released normally; the incomplete clone was never opened. The B5 early Stop returned CANCELLED with retained PCB/launcher and safe_to_continue=false; manual Tip OK alone completed the pending Close. That failure is preserved. The late-Tip fix and its new native acceptance are recorded separately. + +## Limits + +Review round 1 corrected two legacy-cleanup defects. The real residual snapshot adapter now retains hidden MDI document siblings before the exact-one-document guard, and a Tip without any previous Close returns to guarded loaded-target observation within the same deadline. A Tip after an actual Close retains wait-only behavior. The focused regressions first reproduced both failures, then 134 related tests passed; an independent harmless real Win32 window probe confirmed hidden-sibling no-action and the single-document normal Close path. This probe is not Mentor acceptance. + +A delayed Tip dismissal regression then exposed repeated OK posts in the new continuation path. A separate set of Tip handles now limits acknowledgement to once per cleanup intent while retaining the original deadline and Forward handling. Final related coverage passed 180 tests in 29.43 seconds. The first round-1 full run retained 2,355 passes and one failed UI-reopen fixture: it claimed its worker had exited while registering the still-live pytest PID, so the real cold observer correctly blocked admission. The fixture now launches a harmless real worker, exercises actual mutex admission refusal, waits for real process exit and retains the original receipt/reopen assertions; its focused run passed. No product queue bypass or UI timeout increase was introduced. + +B10 is built from `701e5cd`, with EXE SHA-256 `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` and ZIP SHA-256 `d4bd42416ea8d12a249ff1d9c8854eb76d2f81bb7ff869ff43dd92a331c647a0`. All 68 modules/resources and 242 extracted files match; five cancelled frozen entry routes and common smoke passed. Actual B5-to-B10 legacy diagnostic recovery used one confirmation, zero Rechecks/manual native actions, and reached fresh RELEASE_CONFIRMED after an intermediate PARTIAL; final receipt at 35.387 seconds and the UI agreed. This actual native case entered at loaded Forward; both Tip states are covered by focused regression, not claimed as newly replayed Mentor Tip states. + +The final round-1 candidate B11 is built from `8818fa9`: EXE SHA-256 `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98`, ZIP SHA-256 `34b3646b27afae22ec43a415ca19bbd32a91c0a4c941d37d6289c76cea9ca730`. Module/resource equality, all 242 extracted files, five cancelled frozen entries and common smoke passed. Only the residual-session module changed from B10 to add per-intent Tip acknowledgement tracking. B10 native/button receipts remain bound to B10; B11 delayed Tip behavior has source regression coverage, not a new actual Mentor Tip replay. + +The final round-1 complete suite at `8818fa9` passed **2,358 tests in 451.34 seconds**, exit code 0, with zero failures, errors or skips. Log SHA-256: `5544f2e17f84a74e67faa81403a0b13679728c432ab269f2f5050cfe42103831`; JUnit SHA-256: `8e734b1f6298d368b1b059019e419b687c5284c472ad04a999f0b73e2254cd16`. Compilation/diff checks and the post-suite native-process/writer/management idle checks passed. The earlier failing run and test-harness setup failures remain archived. + +The missing frozen controls were exercised on B10: Open logs and Open exception evidence opened the exact current application folders, verified by private-desktop Explorer breadcrumbs; queued CBB recovery was cancelled before admission and created no recovery job; result Release opened the correct residual plan; Continue started only the second previously skipped item, which passed GREEN, without replaying the terminal first item. The first result summary elapsed under its existing three-second Close default. After ordinary main-window Release and normal dialog closure, production code recreated the Continue summary; the observer clicked that actual enabled control without injecting results or calling application methods. One bounded repeat captured result Release within the default window. + +That B10 button exercise exposed the **historical ordinary-verification cancellation defect**: Stop 0.547 seconds after first PCB registration, before any Save, returned CANCELLED/safe=false at PCB_STARTING; the target later loaded Forward Annotation and remained alive. The B10 automatic loaded-startup cleanup required diagnostic-only authority, so it did not clean this ordinary case. Exact manual Forward No and one normal Close after no-modal/no-progress checks were required before fresh release. The bounded result-button repeat reproduced the same retained state. These are failures of unattended ordinary cancellation, not successful automatic cleanup or protected active-Save cases, and remain preserved as failures; the grouped fix and B13 acceptance are recorded below. + +The exact complete fault-bearing field snapshot is unavailable, so the original field inconsistency remains **NOT REPRODUCED**. Any bounded constructed live-copy experiment is reported separately. Windows 10 and production network/SMB behavior are **NOT RUN**. No merge, published release or issue closure is authorized by this candidate report. + +One local B control required a second explicit verification after an initial completed native Save/Close left it PENDING. Both results are retained; automatic retries were not added and the initial failure is not counted as a pass. + +## Final-wave evidence and limits + +B14 EXE SHA-256: `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c`. ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`. All 68 packaged product modules/resources and all 242 extracted files match source/build. Five pre-cancelled frozen routes and common GUI/worker/owner-probe/dialog-agent smoke passed. Full-suite log SHA-256: `d9c57b7998e02154fb703f0fe2ba1f37f73dc4687d116c4b6efc0e5ad7e5c30e`; JUnit SHA-256: `4303cc123e90689103cc4135e483ac936b04a052067e952a1861ae167c7811ea`. Native clients and writer/management mutexes were idle before and after the full suite. + +B13 (`5e9509e`) retains EXE `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` and ZIP `7a1da94e05b85873f791cde77907bdc280106768fbf84e5d89066ab8aa57a61b`. A final self-audit found that the new ordinary explicit-release branch bypassed existing cold-observer promotion. Its focused test failed before the two-line ordering correction at `c1e2596`; 110 related tests then passed in 21.96 seconds, including actual harmless worker exit, cold-observer promotion and queue proof. The in-progress B13 full suite was interrupted through its own execution session before editing, and is archived without a completion/JUnit claim. No additional native matrix was run for this narrow B14 delta. + +The three review defects had retained RED evidence: actual MainWindow subprocess exit hung on stalled hash/copy/validation; real recovery callers held the unrelated native channel and could install after abandoned metadata; ordinary cancelled startup failed to clean a later loaded target. B13 related observer coverage passed 232 tests in 34.81 seconds, including an actual two-process mutex/file race between observer and explicit release plus a process restart. These race tests stub the native evidence/action boundary; they are not Mentor window tests. + +B12 (`906cfc0`, EXE `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc`, ZIP `bbe68005469d8b6cf87726200ef85646e442de45d164ab2ac0aec23b51d0bd65`) retained a new failure: ordinary `verify-642171759614` returned its visible cancellation terminal state in 7.797 seconds, but Forward loaded at 34.406 seconds, after the worker cleanup budget. Exact manual No/normal Close was used solely to clear that failed run. A later independent queue-helper attempt was refused with sharing violation 32 before native creation while two releasing observers raced for the coordination lease. Both failures are archived and are not relabelled as B13 passes. + +B13 ordinary `verify-71aee0603183` reached the visible terminal state in 7.375 seconds. Its candidate worker acknowledged Tip at 21.359 seconds, Forward No at 27.422 seconds and one Close at 28.750 seconds; native exit followed the original cleanup deadline. Read-only sampling confirmed kernel exit. The original result remains CANCELLED/safe=false. No Release click or manual ordinary native action occurred. The helper stayed observe-only until the actual candidate produced fresh RELEASED proof, then obtained its own independent fresh proof. Its prequeued real Versions client `native-backup-b63e7f708fd5` was created 5.220 seconds after the candidate proof and 1.506 seconds after the independent proof, loaded the backup catalog and closed normally. This is **cross-owner queue acceptance**, using source-hash-pinned production queue/observer/native-worker modules; it is not survival of work in the same app after global Stop. The candidate itself performed every ordinary No/Close action. + +The B13 native run issued Close within the first worker budget, so the new retained-phase No/Close branch was **NOT REPLAYED in Mentor**. That branch has source guard, real process race/restart and existing real Win32 adapter evidence. No repeated cold-start attempts were used to manufacture a slower launch. + +B13 actual recovery `backup-restore-3f98efb14448` used the current pending original target and healthy independent source A. Its isolated source and installed target both returned PASS/GREEN/safe; native save/close/release completed without intervention. The old Work directory is retained and all 366 original source files are unchanged. The 27,689-file complete validation library copy progressed through the serial metadata path without a false inactivity handoff. + +Separate frozen metadata-exit harness EXE SHA-256: `7490be1988d823944307510f7cfd22c85cf8570c7c25f6ee60d97f542bb72753`. All 68 packaged product modules equal final B14. A disposable I/O stall at each of hash/copy/validation exercised actual MainWindow close and interpreter exit before releasing the stall; no late dispatch occurred and partial copies were retained. This uses an acceptance-only entry, **not stall injection into the candidate EXE**. The earlier B12/B13 harnesses and all RED/setup attempts remain archived. + +The original complete fault-bearing field snapshot remains unavailable (**NOT REPRODUCED**); the constructed partial copy remains **COPY_BLOCKED** and was never opened. Windows 10 and production SMB remain **NOT RUN**. The earlier first-pass B-control PENDING result and explicit retry remain separate outcomes. No merge, publication or issue closure is performed. diff --git a/docs/releases/2026-11-18-pr16-review-followup.md b/docs/releases/2026-11-18-pr16-review-followup.md new file mode 100644 index 0000000..1234431 --- /dev/null +++ b/docs/releases/2026-11-18-pr16-review-followup.md @@ -0,0 +1,38 @@ +# PR 16 small review follow-up + +Refs #15. Follow-up to review comment 446 on `b4737b5`; this does not authorize +merging, release publication or issue closure. + +- Verify now propagates a registered `TaskHandoff` instead of recording it as a + close error and continuing a second native cleanup. It preserves the cancelled + or failed result as evidence before returning cleanup ownership to the observer. +- Repair runs local worker cleanup even when observer registration or handoff + raises. A live native worker retains its existing observer-owned handles; + `DesktopWorker.close()` does not terminate it or claim resources are released. +- Starting an ICDB check binds the fallback Stop signal to the task's actual + context. The normal global Stop and per-task cancellation policies are unchanged. +- Native Versions/Repair errors now explain that the main PRJ must contain exactly + one nonempty `iCDBDir` using a project-local relative path. Absolute paths, + including absolute paths inside Work, and multiple entries remain unsupported. + No PRJ is rewritten and no native tool is launched for rejected input. + +The previously approved three-second defaults remain: submitted execution +continues; unknown ownership/read-write confirmation skips; version selection +uses the last manual save; exit saves; force termination defaults to cancellation. +This follow-up does not add or change those product decisions. + +## Validation + +The unchanged targeted baseline passed 31 tests. New behavior regressions first +recorded four failures and four passes; after the fixes all eight passed. +Related Verify, Repair, native-entry, observer, ICDB/UI and shutdown regressions +passed **363 tests in 157.24 seconds**, exit code 0. +Compilation and whitespace checks also passed. Independent scoped review found +zero Critical, Important or Minor issues in the follow-up fixes. + +These are source tests with real task contexts and Qt controls; native process +boundaries are replaced where the tests require them. This follow-up does not +claim a new full-suite run, rebuilt frozen package, or actual Mentor acceptance. +The earlier 2,418-test full run and B14 package still belong to source `c1e2596`. +Original field inconsistency, the retained-phase native replay, Windows 10 and +production SMB acceptance remain outstanding as documented in the main matrix. diff --git a/docs/releases/2026-11-18-v0.2.4-beta.4.md b/docs/releases/2026-11-18-v0.2.4-beta.4.md new file mode 100644 index 0000000..f85ab19 --- /dev/null +++ b/docs/releases/2026-11-18-v0.2.4-beta.4.md @@ -0,0 +1,34 @@ +# CBB 刷新校验 v0.2.4-beta.4 + +Refs #15。延续测试版发行,供隔离副本和现场进一步验证。 + +## 本版改动 + +- 分开任务执行、原生客户端退出、资源释放及数据待恢复状态,减少旧记录和无关工程导致的误阻塞。 +- 普通校验启动阶段取消时,只有完整未写入证明和准确归属才能处理已知提示并安全收尾;原结果保留为取消,不改成 READY。 +- 已登记观察者可以持久化接管一次迟到启动的安全收尾;不循环重新打开或自动重放写操作。 +- 文件哈希、复制、校验不再因嵌套线程池阻止程序退出。恢复准备不长期持有全局原生通道,迟到任务不能继续安装。 +- 修正交接异常传递、Repair 本地资源清理、ICDB 停止信号绑定,以及管理窗口销毁后的迟到结果回调。 +- 保留当前图标、三个菜单、READY 操作范围及手动备份政策。版本/Repair 对绝对或多条 iCDBDir 的拒绝原因现在明确显示,不自动修改工程引用。 +- 沿用已确认的 3 秒默认策略;未知占用和读写确认默认跳过,强制终止默认取消。真实原生写入仍受保护。 + +## 发布验证 + +本次源码全量 **2,428 项通过,659.54 秒,退出码 0**;JUnit 零失败、零错误、零跳过。 +管理窗口销毁后的成功/失败回调先复现失败,再通过实际 Qt 信号测试验证修复。 +生命周期模拟测试隔离无关的机器 WMI/文件探测延迟,真实占用、独占句柄、资源证明和原生写入保护测试继续保留。 +新增发布改动经独立限定复核,无 Critical、Important 或 Minor 遗留项。 + +Windows 包使用合并后的 main 提交构建并上传云端;仓库当前未配置云端打包工作流。 +最终源码提交、冻结模块/资源及图标核对、冻结冒烟和 ZIP 校验结果见发行附件 +`release-info.json`、`release-smoke.json` 和 `SHA256SUMS.txt`。 +发布前因 C 盘耗尽中断的一轮,以及后续失败/修订的测试记录均保留,不计为通过。 + +## 使用与范围 + +完整解压 Windows ZIP,运行 `CbbRefreshVerify-Background/CbbRefreshVerify.exe`,保留 `_internal`。 +库写操作前按提示手动备份。程序回滚不能撤销已经完成的中心库写入。 + +自动 ICDB Repair 仍关闭。原现场不一致故障未完整复现;独立接管阶段的原生 No/Close 重放、Windows 10、生产 SMB 尚未验收。 +此前 B13 实际普通取消、后续原生调度与备份恢复的通过记录保留其原始源码/包版本,不能算成本发行包的原生重跑。 +发布测试版不关闭工单 #15,也不代表这些现场边界已经解决。 diff --git a/docs/superpowers/plans/2026-11-16-issue15-runtime-unblock.md b/docs/superpowers/plans/2026-11-16-issue15-runtime-unblock.md new file mode 100644 index 0000000..355a204 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-issue15-runtime-unblock.md @@ -0,0 +1,79 @@ +# 工单 #15 实测问题全量修复实施计划 + +**Goal:** 消除误阻塞,打通手动修复与版本管理,逐项验证工单全部实测问题。 +**Architecture:** 复用会话记录、串行队列和原生适配器;区分任务执行、客户端退出、协调租约释放、数据待恢复及下一项写入资格。范围不明时只隔离受影响资源,不冻结界面或无关库。 +**Tech Stack:** Python 3.12、PySide6、pywin32、Mentor EE7.9.5,不新增依赖。 +**Spec:** 用户在聊天中批准的五节计划;证据及确认/待确认边界见 `F:/CbbIssue15-20261116/analysis.md`。 + +## Global Constraints + +- 基线 efb8cae,独立分支 codex/issue15-runtime-unblock;保留原脏工作区。 +- 自动 ICDB Repair 继续关闭。明确不一致时报告并跳过,提供实际可用的手动 Repair/历史恢复入口。独立项继续。 +- 普通校验确认工程唯一归属后,将主 PRJ 和 PCB PRJ 对齐所选中心库,保留原文件证据;ICDB 检查不修改引用。 +- READY 不进入校验/维护;管理允许 READY。原生写入串行,同名更新 Remove→Add 不被打断。 +- 手动备份政策;不新增自动整库备份。不手删原生锁/地址,不杀用户程序,不抢前台鼠标。 +- 默认确认 3 秒:已提交执行继续;未知占用/PCB 读写确认跳过项;历史版本最后手动保存;退出前保存;强制终止取消。人工优先、仅生效一次。 +- VerifyRequest/VerifyResult 与旧记录兼容。未知旧记录重新核对,不直接采信旧证明。 +- 先失败复现再最小修复,阶段验证后单独提交。源码回归不冒充冻结包或现场原生验收。 +- 验收只用隔离完整副本;不改生产库。未复现原故障必须明确。不得自动合并发布或关闭工单。 + +## Task 1: 会话资源范围、锁与释放证明 + +Owned areas: library_lock/session_record/icdb_ownership/operation_lifecycle/residual_sessions/owner_probe and a bounded file-probe helper/CLI if needed; associated tests. Coordinate shared changes through controller. + +- [ ] 先新增行为回归并见证失败:A 退出而 B 有地址;未知检查点+明确其他工程进程;父句柄保留后子进程获取;迟到观察不能清除新任务;慢 A 探测不挡 B 内存/租约检查。 +- [ ] 在现有会话和释放证明中增补可选 lease_state/resource_scope/blocked_resources/data_recovery_required,记录目标工程、数据库、实际共享依赖和操作身份;旧记录缺范围重新核对。 +- [ ] 分开客户端退出、协调租约释放和数据恢复;已退出任务不因为其他块地址永久占有自己的句柄。不将文件存在/PID文本/地址年龄/端点不可达当作权威占用或可写证明。 +- [ ] release_residual_sessions 传递准确范围;观察项不进入关闭目标、不增加主动释放计数。未知检查点也按实际资源判断,不要求全部 Mentor 进程退出。 +- [ ] 地址不手动删除;有地址且需判定的目标复用 inspection-only 原生判定。真实目标占用/未返回共享写入依旧保护,健康工程不跑额外 ICDB 扫描。 +- [ ] 全局锁只保护快照/提交;进程/文件/网络探测移出锁,提交前核对 lease/operation 身份。 +- [ ] 有阻塞风险的只读文件探测放独立 helper,默认单次最多10秒,支持停止;只能终止纯探测 helper。需要持有证明句柄跨提交时使用握手保持保护,不引入无保护 TOCTOU。 +- [ ] 相关旧回归及真实 Windows 句柄/父子进程试验通过,写阶段记录并提交。 + +## Task 2: 取消、超时、退出与批次继续 + +Owned areas: failed_session/verify_runner/desktop_worker/operation_queue and lifecycle integration/tests. UI adoption delegated to Task 4. + +- [ ] 失败用例覆盖晚到每日提示、读写确认、历史版本取消、PCB先退/启动器后退、COM无文档、慢探测、失败后独立项继续、取消后的新任务。 +- [ ] 正常执行和失败启动收尾复用已知弹窗识别。精确绑定创建身份、工程、私有桌面;未知弹窗不猜按钮。取消收尾最多30秒返回终态或交给独立观察。 +- [ ] 现有队列增补每批不可变任务上下文(operation_id、library/aliases、targets/resources、stop、state),停止事件不跨任务复用;原生写保持串行,事务不能在Remove与Add间让出。 +- [ ] 仅资源相关项受保护;安全业务失败继续,未确认范围的后续项记录跳过并结束汇总,不无限等待。回调绑定任务身份,不覆盖新库。 +- [ ] 准备有界关闭接口:30秒内完成或把原生事务交给有证据监督,禁止线程池析构/文件探测导致无限等。启动和交接记录保障重启可见,不重放写操作。 +- [ ] 运行覆盖测试并提交;向 Task 4 明确队列状态、停止和关闭接口。 + +## Task 3: 版本管理、手动 Repair、工程身份和原生错误 + +Owned areas: native_backup/mentor_adapter/library_manager_verify/verify diagnostics/maintenance_entry/native occupancy; may amend runner stage integration after Task 2. + +- [ ] 先写失败测试:版本 worker 前的父保留租约、子启动/登记失败、无备份、关闭再打开、主/PCB引用不同、旧日志不作新诊断、菜单返回但没PCB。 +- [ ] 版本启动前复核本任务历史租约;使用已有登记/启动门控,先持久登记身份再开原生工具,执行方持实际租约,失败给明确归属与恢复路径。 +- [ ] 提供绑定准确PRJ/数据库的原生 Repair 入口,保留版本与备份UI;自动Repair关闭。不得绕过活跃事务;数据待恢复本身不得禁用手动恢复入口。 +- [ ] 普通校验以同一工程归属确认统一两层PRJ,保留编码/原字节;诊断不修改。重新核对实际打开身份。 +- [ ] 从本轮增量日志提取副本不一致/ICDB/失联及目标DB;只报告“发现问题、未修复”,独立项继续。 +- [ ] LM派发观察上限min(45秒,用户超时),有PCB再进入正常启动计时;无PCB快速失败并正常收尾,默认不启用前台鼠标替代。 +- [ ] 保存成功、关闭、资源释放、权威READY独立记录。仍PENDING不得记通过;历史恢复是版本待核对,原生窗口关闭不冒充Repair成功。 +- [ ] 相关回归与可用的隔离原生路径通过,记录后提交。 + +## Task 4: UI、输入、计数与无人值守集成 + +Owned areas: ui/main_window/child dialogs/library_reader/models/application settings and queue adoption; associated tests. + +- [ ] 先复现排队禁用全界面、首次读库无法取消、迟到跨库回调、模态结果、证据按钮条件错误、坏库输入和计数问题。 +- [ ] 接 Task2 上下文,每任务独立停止/回调。排队不置全局不可操作;搜索筛选、换库、证据、取消排队、释放可用。原生操作排队,重复提交同一快照不重复执行。 +- [ ] 读库失败保留旧表并标失效,禁止旧表写;快速显示目录结果,原生目录复核后台入队。目录发现/原生记录/缺工程分别计数,未复核显示未知。 +- [ ] 空文件、错误后缀、锁路径是目录、权限失败输出稳定分类;快速读不自称验证了原生格式。 +- [ ] 结果QMessageBox显式NonModal、3秒默认关闭,失败/取消有证据即可打开;日志入口打开logs。记忆上次成功读取路径,启动仅回填不自动执行。 +- [ ] 版本/Repair按钮绑定一个可见非READY目标,不能以未校验或数据待恢复直接禁用;真实资源冲突有简短原因。 +- [ ] 全面复核选择/清空/隐藏项、READY资格、状态刷新、每个条件按钮。现有3秒策略完整集成,人工抢先选择/窗口隐藏/计时竞态不得重复动作。 +- [ ] 关闭接Task2有界交接;UI只留必要操作/错误,不写开发说明。 +- [ ] 全部相关Qt测试和381/3000项响应检查通过,记录后提交。 + +## Task 5: 全量回归、真实冻结包验收与PR + +- [ ] 全量pytest、compileall、diff检查、模块/资源/PE图标与冻结包一致性;每次失败保留,修订后重验相应范围。 +- [ ] 逐按钮清单覆盖主窗口、管理、恢复、原生版本/Repair、释放及所有条件按钮;源码Qt与最终冻结包分别执行。 +- [ ] 非规则点击覆盖双击执行、取消重试、检查中排队/换库、隐藏勾选、结果框存在、关闭原生窗口、3秒边界竞争和主程序退出重启。 +- [ ] 真实Windows进程/文件锁覆盖无持有LOCK、父子冲突、外部无关进程、真实目标独占句柄、地址残留和慢/失败查询。不能修改或终止其他任务。 +- [ ] Mentor真实独立副本验证普通校验READY、ICDB批检后独立继续、手动Repair、版本回退后重开、批量新增/同名更新/移除/恢复;原生失败单独列明,不用模拟替代。 +- [ ] 不一致故障必须对应实际原生特征;没有现场一致副本则标未复现,不拿格式损坏替代。Win10/生产网络未测明确保留。 +- [ ] 候选包、逐问题/逐按钮验收表、新PR。未经现场验收不自动合并发布、不关工单。 diff --git a/pyproject.toml b/pyproject.toml index 105bbd0..a333eba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"] build-backend = "setuptools.build_meta" [project] name = "cbb-refresh-verify" -version = "0.2.4b3" +version = "0.2.4b4" requires-python = ">=3.12,<3.13" dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"] diff --git a/src/cbb_refresh_verify/__init__.py b/src/cbb_refresh_verify/__init__.py index 1e4336f..17b1675 100644 --- a/src/cbb_refresh_verify/__init__.py +++ b/src/cbb_refresh_verify/__init__.py @@ -1 +1 @@ -__version__ = "0.2.4b3" +__version__ = "0.2.4b4" diff --git a/src/cbb_refresh_verify/application.py b/src/cbb_refresh_verify/application.py index daf1c35..e1a8192 100644 --- a/src/cbb_refresh_verify/application.py +++ b/src/cbb_refresh_verify/application.py @@ -72,11 +72,71 @@ def _positive_int(value): return number +def _native_worker_entry(mode, request): + """Contain hidden-worker failures so a frozen bootloader cannot show a modal error.""" + import contextlib + import json + import traceback + from .desktop_worker import run_native_worker + state = {'worker_entered': False} + result_name = {'verify': 'outcome.json', 'repair': 'repair-result.json'}.get(mode, 'result.json') + try: + with request.with_name('worker.log').open('a', encoding='utf-8') as log: + with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): + if mode == 'native-backup': + from .native_backup import run_native_backup_worker + return run_native_backup_worker(request, admission_state=state) + if mode == 'management': + from .native_management import catalog_worker_main, management_worker_main + job = json.loads(request.read_text(encoding='utf-8')) + action = catalog_worker_main if job.get('worker_role') == 'catalog_readonly' else management_worker_main + elif mode == 'repair': + from .native_repair_ui import repair_worker_main + action = repair_worker_main + else: + from .mentor_adapter import worker_main + action = worker_main + return run_native_worker(action, request, admission_state=state) + except Exception as error: + trace = traceback.format_exc() + entered = state['worker_entered'] + reason = str(error) + cancelled = not entered and reason.startswith('WORKER_CANCELLED:') + detail = ('VERIFY_CANCELLED: ' if mode == 'verify' and cancelled else '') + reason + path = request.with_name(result_name) + try: + result = json.loads(path.read_text(encoding='utf-8')) + if not isinstance(result, dict): result = {} + except (OSError, ValueError): + result = {} + if mode == 'verify': + result.update(status='CANCELLED' if cancelled else 'FAIL', stderr=detail, + error_stage='worker' if entered else 'admission', safe_to_continue=False) + else: + result.update(success=False, status='FAILED', detail=detail, safe_to_continue=False) + failure = dict(stage='worker' if entered else 'admission', reason=reason, + worker_entered=entered, native_started=None if entered or mode == 'native-backup' else False, + safe_to_continue=False) + # An exception is never a release proof, and existing Save/Close evidence is retained. + for output, value in ((path, result), (request.with_name('worker-failure.json'), failure)): + try: + output.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8') + except OSError: + pass + try: + with request.with_name('worker.log').open('a', encoding='utf-8') as log: + log.write(trace) + except OSError: + pass + return 2 if mode == 'management' else 1 + + def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="CbbRefreshVerify") parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS) parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS) parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--file-probe', type=Path, help=argparse.SUPPRESS) parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS) parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS) parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS) @@ -89,18 +149,18 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS) parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS) args = parser.parse_args(list(argv) if argv is not None else None) + if args.file_probe: + from .file_probe import file_probe_main + return file_probe_main(args.file_probe) if args.owner_probe: from .owner_probe import owner_probe_main return owner_probe_main(args.owner_probe) if args.native_backup_worker: - from .native_backup import native_backup_worker_main - return native_backup_worker_main(args.native_backup_worker) + return _native_worker_entry('native-backup', args.native_backup_worker) if args.management_worker: - from .native_management import management_worker_main - return management_worker_main(args.management_worker) + return _native_worker_entry('management', args.management_worker) if args.repair_worker: - from .native_repair_ui import repair_worker_main - return repair_worker_main(args.repair_worker) + return _native_worker_entry('repair', args.repair_worker) if args.collect_failure_logs: from .verify_diagnostics import failure_logs_main return failure_logs_main(args.collect_failure_logs) @@ -108,11 +168,7 @@ def main(argv: Sequence[str] | None = None) -> int: from .dialog_agent import dialog_agent_main return dialog_agent_main(args.dialog_agent) if args.verify_worker: - from .mentor_adapter import worker_main - import contextlib - with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log: - with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): - return worker_main(args.verify_worker) + return _native_worker_entry('verify', args.verify_worker) context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start") try: if args.batch_lmc: diff --git a/src/cbb_refresh_verify/backup_recovery.py b/src/cbb_refresh_verify/backup_recovery.py index 2770295..b073832 100644 --- a/src/cbb_refresh_verify/backup_recovery.py +++ b/src/cbb_refresh_verify/backup_recovery.py @@ -33,6 +33,7 @@ def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, bloc from .icdb_ownership import database_directories, unreleased_addresses from contextlib import ExitStack import win32con, win32file + from .operation_queue import note_metadata_progress directories = database_directories(library, project, pcb) scope = (Path(project).parent, *directories) def owners(): @@ -61,6 +62,7 @@ def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, bloc unknown = owners() resources() # Never hold exclusive probe handles while waiting for a user. if not unknown: + note_metadata_progress() return if confirmation is None: from .write_admission import WriteAdmissionDeclined @@ -71,6 +73,7 @@ def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, bloc if unknown and not confirmation.confirmed(library, unknown): raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 占用确认后出现新的未知进程,请重新检查。') resources() + note_metadata_progress() def _native_scope_match(command, *, roots=(), files=()): @@ -161,7 +164,7 @@ def _align_library(project, pcb, library): def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None,stop=None): """Validate in copies before changing Work; preserve all recovery evidence.""" - import pythoncom, win32con, win32event + from .operation_queue import check_active, local_commit, note_metadata_progress, QueueCancelled from .network_path import absolute_preserving_drive from .verify_runner import run_verify, read_library_flag_if_available verifier = verifier or run_verify @@ -184,11 +187,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。') if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent): return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。') - mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') - acquired = False library_lock = None release_confirmed = True installed = False + def check(): + check_active() + if stop is not None and stop.is_set(): + raise QueueCancelled('恢复已取消,未提交后续操作。') + def completed(): + check() + note_metadata_progress() record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source), 'library': str(library), 'block': request.block_name, 'installed': False, 'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'} @@ -213,23 +221,25 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c from .com_runtime import initialize_com, uninitialize_com initialized = initialize_com() try: - acquired = win32event.WaitForSingleObject(mutex, 0) in ( - win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) - if not acquired: - return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False) + check() from .library_lock import LibraryLock library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed) library_lock.__enter__() if source.is_relative_to(library_root): raise ValueError('请选择目标中心库之外的独立备份工程。') project, pcb = preflight(replace(request, lmc_file=library)) + completed() source_pcb = _source_check(source, request.block_name, project) + completed() root.mkdir(parents=True, exist_ok=False) idle_check(library, project, pcb) + completed() idle_check(library, source, source_pcb) + completed() validation_base.mkdir(parents=True, exist_ok=True) library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode)) source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode)) + completed() same_drive = root.anchor.casefold() == validation_dir.anchor.casefold() required = (library_size + source_size * 2) if same_drive else 0 if (shutil.disk_usage(root).free < required @@ -241,6 +251,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c library_scope = ManifestScope.library(request.block_name, library.name) original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope, progress=copy_progress('prepare_source', '正在准备验证库:')) + completed() (root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8') staged_library = validation_dir/library.name staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work' @@ -249,8 +260,10 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c if not resolved_work.is_relative_to(validation_dir.resolve()): raise ValueError('验证副本工程路径越界。') shutil.rmtree(resolved_work) + completed() source_manifest = _copy_verified(source.parent, staged_work, progress=copy_progress('prepare_source', '正在准备备份验证工程:')) + completed() (root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8') staged_project = staged_work/source.name staged_pcb = staged_work/source_pcb.relative_to(source.parent) @@ -260,41 +273,55 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='', native_lm_verify=False, interactive_input=False) preflight(validation) + completed() emit('validate_source', '正在副本中打开备份工程并执行原生校验…') + check() release_confirmed = False choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {} if stop is not None:choice_options['stop']=stop source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options) release_confirmed = source_result.safe_to_continue record['source_validation'] = asdict(source_result) + completed() if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN' or not source_result.safe_to_continue): return save(replace(source_result, status='FAIL', stderr= '备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail))) idle_check(library, project, pcb) + completed() idle_check(staged_library, staged_project, staged_pcb) + completed() token = root.name.removeprefix('backup-restore-') work = project.parent.resolve() incoming = work.with_name('Work.restore-' + token) retained = work.with_name('Work.before-restore-' + token) _copy_verified(staged_work, incoming, progress=copy_progress('prepare_source', '正在准备恢复工程:')) + completed() _align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library) + completed() idle_check(library, source, source_pcb) + completed() if _manifest(source.parent) != source_manifest: raise ValueError('备份来源在验证期间发生变化,目标未更改。') + completed() if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest: raise ValueError('目标中心库在验证期间发生变化,停止恢复。') + completed() emit('install', '备份已通过验证,正在保留原工程并恢复…') - work.rename(retained) - try: - incoming.rename(work) - except Exception: - retained.rename(work) - raise - installed = True - record['retained_work'] = str(retained) + check() + with local_commit(): + work.rename(retained) + try: + incoming.rename(work) + except Exception: + retained.rename(work) + raise + installed = True + record['retained_work'] = str(retained) + completed() emit('verify_target', '正在重新打开恢复后的目标工程并校验…') + check() release_confirmed = False final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify', auto_repair=False, native_lm_verify=False, interactive_input=False), @@ -317,7 +344,4 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c if library_lock is not None: library_lock.__exit__(None, None, None) finally: - if acquired: - win32event.ReleaseMutex(mutex) - mutex.Close() uninitialize_com(initialized) diff --git a/src/cbb_refresh_verify/desktop_worker.py b/src/cbb_refresh_verify/desktop_worker.py index 0da9122..f6d4c29 100644 --- a/src/cbb_refresh_verify/desktop_worker.py +++ b/src/cbb_refresh_verify/desktop_worker.py @@ -16,6 +16,225 @@ _automation_clients = [] _automation_clients_lock = threading.Lock() _supervisor_lost = threading.Event() _native_phases = {} +WRITER_MUTEX = r'Local\CbbRefreshVerify795NativeWriter' + + +def assert_native_writer_idle(): + mutex = win32event.CreateMutex(None, False, WRITER_MUTEX) + acquired = False + try: + acquired = win32event.WaitForSingleObject(mutex, 0) in ( + win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) + if not acquired: + raise RuntimeError('NATIVE_WRITER_ACTIVE: 原生事务尚未返回,未启动新的写入。') + finally: + if acquired: win32event.ReleaseMutex(mutex) + mutex.Close() + + +class _RegisteredWriter: + def __init__(self, handle): + import win32api + current = win32api.GetCurrentProcess() + self.handle = win32api.DuplicateHandle(current, handle, current, 0, False, + win32con.DUPLICATE_SAME_ACCESS) + self.returncode = None + + def poll(self): + if self.returncode is None and win32event.WaitForSingleObject(self.handle, 0) == win32con.WAIT_OBJECT_0: + self.returncode = win32process.GetExitCodeProcess(self.handle) + self.handle.Close() + return self.returncode + + +def register_native_writer(process): + handle = getattr(process, 'handle', None) or getattr(process, '_handle', None) + registered = _RegisteredWriter(handle) if handle is not None else process + with _automation_clients_lock: + _automation_clients.append(registered) + return process + + +class _PendingNativeOperation: + """One asynchronously submitted operation, including its native descendants.""" + def __init__(self, job, identities): + import win32api + from .residual_sessions import _handle_identity, _force_ownership + from .session_record import IDENTITY_KEYS + self.record = job + self.job = win32job.CreateJobObject(None, '') # Deliberately no kill-on-close. + self.owners = {} + self.recorded = set() + self.completed = False + self.exited = False + self.lock = threading.Lock() + try: + for identity in identities: + pid = identity['pid'] + handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000 | + win32con.PROCESS_SET_QUOTA | win32con.PROCESS_TERMINATE, False, pid) + try: + actual = dict(pid=pid, **_handle_identity(handle), **_force_ownership(handle, pid)) + if any(actual[key] != identity.get(key) for key in IDENTITY_KEYS): + raise RuntimeError('NATIVE_OPERATION_IDENTITY_CHANGED') + win32job.AssignProcessToJobObject(self.job, handle) + self.owners[pid] = _RegisteredWriter(handle) + self.recorded.add(pid) + finally: + handle.Close() + except Exception: + self._close() + raise # Admission failure is not permission to post Add without protection. + + def _close(self): + for owner in self.owners.values(): + if owner.returncode is None: + owner.handle.Close() + self.job.Close() + self.exited = True + + def complete(self): + with self.lock: + self.completed = True # Only an exact native acknowledgement settles the operation. + + def poll(self): + with self.lock: + return self._poll() + + def _poll(self): + if self.exited: + return 0 + pids = set(win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList)) + fresh = pids-self.recorded + if fresh: + from .session_record import update_worker_state + from .residual_sessions import _process_handle, _handle_identity, _force_ownership + identities = [] + for pid in fresh: + with _process_handle(pid) as handle: + if not win32job.IsProcessInJob(handle, self.job): + continue # The snapshot PID may have been reused outside this job. + identities.append(('native', dict(pid=pid, **_handle_identity(handle), + **_force_ownership(handle, pid)))) + if identities and update_worker_state(self.record, 'UNCONFIRMED', observed_identities=identities): + self.recorded.update(identity['pid'] for _, identity in identities) + # An acknowledged Add does not retain an otherwise idle LM shell. + # Descendants still need observed exit; PID reuse cannot imitate an owner. + idle = {pid for pid, owner in self.owners.items() if owner.poll() is None} if self.completed else set() + if not pids-idle: + self._close() + return 0 + return None + + +def register_pending_native_operation(job, pids): + from .session_record import read_session_record, update_worker_state + pids = set(pids) + if not pids: + raise RuntimeError('NATIVE_OPERATION_OWNER_REQUIRED') + # Retain the creation/image/owner identity in the existing bound journal + # before asynchronous dispatch, so a restarted UI can validate controls. + update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in pids], required=True) + path = Path(job['session_record_path']).with_name('worker-state.json') + record = read_session_record(path, evidence_root=path.parent) + identities = [p for p in record.get('processes', ()) if p['pid'] in pids and p.get('role') == 'native'] + if record['operation_id'] != job['operation_id'] or {p['pid'] for p in identities} != pids: + raise RuntimeError('NATIVE_OPERATION_OWNER_UNCONFIRMED') + operation = _PendingNativeOperation(job, identities) + with _automation_clients_lock: + _automation_clients.append(operation) + return operation + + +@contextmanager +def worker_native_channel(*, lease_handle=None, inspection_only=False): + """The native worker, not its disposable supervisor, owns write exclusion.""" + import win32api + mutex = win32event.CreateMutex(None, False, WRITER_MUTEX) + acquired = False + try: + if inspection_only is not True: + acquired = win32event.WaitForSingleObject(mutex, 0) in ( + win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) + if not acquired: + raise RuntimeError('NATIVE_WRITER_ACTIVE: 原生事务尚未返回。') + yield + finally: + if acquired: + # Only registered Save/Close/Repair clients extend the boundary; + # an idle PCB shell or a business failure is not a pending write. + warned = False + while True: + with _automation_clients_lock: + clients = tuple(_automation_clients) + try: + released = all(client.poll() is not None for client in clients) + except Exception: + released = False + if not warned: + logging.getLogger(__name__).warning('Native writer exit is unconfirmed', exc_info=True) + warned = True + if released: + break + threading.Event().wait(.1) + win32event.ReleaseMutex(mutex) + mutex.Close() + if lease_handle is not None: + win32api.CloseHandle(int(lease_handle)) + + +def run_native_worker(action, request_path, *, admission_state=None): + """Wait for durable parent admission before acquiring the worker barrier.""" + import json + import time + job = json.loads(Path(request_path).read_text(encoding='utf-8')) + gate = Path(job['start_gate']) if job.get('start_gate') else None + if gate is not None: + deadline = time.monotonic()+30 + while not gate.is_file(): + if (job.get('cancel_signal') and Path(job['cancel_signal']).exists() + or time.monotonic() >= deadline): + raise RuntimeError('WORKER_CANCELLED: 未取得启动许可。') + threading.Event().wait(.05) + lease_handle = None + record = None + if job.get('session_record_path'): + from .session_record import read_session_record, process_identity, IDENTITY_KEYS + path = Path(job['session_record_path']) + record = read_session_record(path, evidence_root=path.parent) + identity = process_identity(os.getpid()) + if (record['operation_id'] != job['operation_id'] + or any(record.get(key) != job.get(key) for key in ( + 'operation', 'library', 'block', 'desktop', 'worker_role', 'start_gate_protocol', 'start_gate')) + or not any(p.get('role') == 'worker' and all(p.get(k) == identity[k] for k in IDENTITY_KEYS) + for p in record.get('processes', ()))): + raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED') + lease_handle = record.get('worker_lease_handle') + if job.get('start_gate_protocol') == 'event-v1': + import win32api + handle = record.get('worker_start_handle') if record else None + if not handle: + raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少启动事件。') + try: + deadline = time.monotonic()+30 + while win32event.WaitForSingleObject(int(handle), 50) != win32con.WAIT_OBJECT_0: + if (job.get('cancel_signal') and Path(job['cancel_signal']).exists() + or time.monotonic() >= deadline): + raise RuntimeError('WORKER_CANCELLED: 启动事件未提交。') + finally: + win32api.CloseHandle(int(handle)) + if job.get('worker_role') == 'catalog_readonly': + from .native_management import catalog_worker_main + if action is not catalog_worker_main or job.get('operation') != 'catalog': + raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH') + inspection = (action.__module__ == 'cbb_refresh_verify.native_repair_ui' + and action.__name__ == 'repair_worker_main' and job.get('inspection_only') is True) + with worker_native_channel(lease_handle=lease_handle, inspection_only=inspection): + if job.get('cancel_signal') and Path(job['cancel_signal']).exists(): + raise RuntimeError('WORKER_CANCELLED: 已取消原生启动。') + if admission_state is not None: + admission_state['worker_entered'] = True + return action(request_path) def _phase_pending(phase): @@ -56,6 +275,8 @@ def _record_write_pending(record_path, operation_id=None): def launch_save_helper(command, *, start_gate=None, identity_path=None, operation_id=None, **kwargs): """Register the save client atomically with respect to supervisor loss.""" with _automation_clients_lock: + from .operation_queue import check_active + check_active() if _supervisor_lost.is_set(): raise RuntimeError('VERIFY_CANCELLED: 监督器已退出,未启动新的保存客户端') helper = subprocess.Popen(command, **kwargs) @@ -115,9 +336,12 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients= pending = _record_write_pending(session_record_path, operation_id) # The same gate blocks new calls/helpers after loss. A stale # POSTCALL on disk cannot override an active in-memory call. - if (pending is False and _phase_pending(_native_phases.get(operation_id)) is False - and all(helper.poll() is not None for helper in _automation_clients)): - os._exit(75) # This Python worker only; native children remain untouched. + returned = pending is False and _phase_pending(_native_phases.get(operation_id)) is False + clients = tuple(_automation_clients) + # Polling can publish a job descendant's exact identity. Never + # hold the client registry lock while that journal is updated. + if returned and all(helper.poll() is not None for helper in clients): + os._exit(75) # This Python worker only; native children remain untouched. threading.Event().wait(.2) finally: parent.Close() @@ -160,6 +384,8 @@ class DesktopWorker: startup = win32process.STARTUPINFO() # subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess. startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input) + from .operation_queue import check_active + check_active() self.handle, thread, self.pid, _ = win32process.CreateProcess( command[0], subprocess.list2cmdline(command), None, None, False, win32con.CREATE_NO_WINDOW, None, None, startup) @@ -199,6 +425,8 @@ class DesktopWorker: raise def start_companion(self, command): + from .operation_queue import check_active + check_active() startup = win32process.STARTUPINFO() startup.lpDesktop = startup_desktop_name( self.name, interactive_input=getattr(self, 'interactive_input', False)) @@ -283,7 +511,10 @@ class DesktopWorker: def bind_session(self, job): from .session_record import register_worker_session - register_worker_session(self, job) + from .library_lock import duplicate_worker_lease + lease = (None if job.get('inspection_only') is True else + duplicate_worker_lease(job['library'], self.handle)) + register_worker_session(self, {**job, 'worker_lease_handle': lease}) def native_write_pending(self): return _record_write_pending(getattr(self, 'session_record_path', None)) diff --git a/src/cbb_refresh_verify/diagnostic_open.py b/src/cbb_refresh_verify/diagnostic_open.py index a9c94d1..81d2c88 100644 --- a/src/cbb_refresh_verify/diagnostic_open.py +++ b/src/cbb_refresh_verify/diagnostic_open.py @@ -9,6 +9,7 @@ import ctypes from ctypes import wintypes import heapq import hashlib +import json import ntpath import os from pathlib import Path @@ -138,16 +139,21 @@ def _load_evidence(job, pcb_pid, baseline, *, require_autosave=True): return None -def _target_frame(windows, name): +def _target_frame(windows, name, *, require_ready=True): matches = [] for window in windows: - if not window['class'].casefold().startswith('afx:') or not window.get('enabled', True): + if not window['class'].casefold().startswith('afx:'): + continue + if require_ready and (not window.get('enabled', True) or any( + child['class'].casefold() == 'msctls_progress32' and child.get('visible', False) + for child in window['children'])): continue if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold(): continue mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'} - if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold() - and child['class'].casefold().startswith('afx:') for child in window['children']): + documents = [child for child in window['children'] if child.get('parent') in mdi + and child['class'].casefold().startswith('afx:')] + if len(documents) == 1 and documents[0]['text'].casefold() == name.casefold(): matches.append(window) return matches[0] if len(matches) == 1 else None @@ -170,6 +176,23 @@ def _windows(pid): # Custom controls may have no cached text; missing evidence fails closed. user.GetWindowTextW(hwnd, buffer, len(buffer)) return buffer.value + def owner_chain(hwnd): + import win32service + desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop( + win32api.GetCurrentThreadId()), 2) + chain, seen = [], {hwnd} + for _ in range(8): + hwnd = int(win32gui.GetWindow(hwnd, 4) or 0) + if not hwnd or hwnd in seen: break + seen.add(hwnd) + thread, owner_pid = win32process.GetWindowThreadProcessId(hwnd) + same_desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop(thread), 2) == desktop + chain.append({'hwnd': hwnd, 'pid': owner_pid, 'class': win32gui.GetClassName(hwnd), + 'text': text(hwnd), 'visible': bool(win32gui.IsWindowVisible(hwnd)), + 'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'same_desktop': same_desktop, + 'owner': int(win32gui.GetWindow(hwnd, 4) or 0)}) + if owner_pid != pid or not same_desktop or chain[-1]['visible']: break + return chain result = [] seen = 0 def collect(hwnd, _): @@ -191,10 +214,10 @@ def _windows(pid): raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls') child_cls = win32gui.GetClassName(ch) if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden' - or child_cls.casefold() == 'mdiclient' or child_cls.casefold().startswith('afx:')): + or child_cls.casefold() in ('mdiclient', 'msctls_progress32') or child_cls.casefold().startswith('afx:')): children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch), 'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch), - 'enabled': bool(win32gui.IsWindowEnabled(ch))}) + 'enabled': bool(win32gui.IsWindowEnabled(ch)), 'visible': bool(win32gui.IsWindowVisible(ch))}) return True if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden': win32gui.EnumChildWindows(hwnd, child, None) @@ -205,7 +228,8 @@ def _windows(pid): return True result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption, 'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children, - 'owner': int(win32gui.GetWindow(hwnd, 4) or 0)}) + 'owner': int(win32gui.GetWindow(hwnd, 4) or 0), + 'owner_chain': owner_chain(hwnd) if cls == '#32770' else []}) return True win32api.SetLastError(0) try: @@ -261,6 +285,50 @@ def _cancel(job): raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled') +def _request_close_handoff(job, pcb_pid, frame, session, emit, deadline): + from uuid import uuid4 + intent = dict(pcb_pid=int(pcb_pid), hwnd=frame['hwnd'], operation_id=job['operation_id'], + desktop=job['desktop'], project=job['project'], pcb=job['pcb'], close_id=uuid4().hex) + ack = Path(job['root'])/'diagnostic-close-ack.json' + emit(stage='diagnostic_close_requested', **intent) + def read_ack(): + try: + with ack.open(encoding='utf-8') as stream: + return json.loads(stream.read(8192)) + except (OSError, ValueError): + return None + while True: + _cancel(job) + remaining = deadline-time.monotonic() + if remaining <= 0 or not session.pcb_alive(): + raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: supervisor handoff not acknowledged') + try: + acknowledged = _bounded_call(read_ack, min(2, remaining)) + except TimeoutError as error: + raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: supervisor acknowledgement read timed out') from error + if acknowledged == intent: + return intent + time.sleep(min(.1, max(0, deadline-time.monotonic()))) + + +def _owned_by_frame(window, frame): + if frame is None or window['pid'] != frame['pid']: return False + if window.get('owner') == frame['hwnd']: return True + chain = window.get('owner_chain', ()) + expected, seen = window.get('owner'), {window['hwnd']} + if not chain or len(chain) > 8: return False + for index, owner in enumerate(chain): + if (owner['hwnd'] != expected or owner['hwnd'] in seen or owner['pid'] != frame['pid'] + or owner.get('same_desktop') is not True): return False + seen.add(owner['hwnd']) + if owner['hwnd'] == frame['hwnd']: + return (index == len(chain)-1 and owner['class'] == frame['class'] and owner['text'] == frame['text']) + if (owner['class'] != '#32770' or owner['text'] != 'Expedition PCB' + or owner['visible'] or owner['enabled']): return False + expected = owner['owner'] + return False + + def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''): for window in windows: known_titles = {'expedition pcb', 'expedition pcb - reusable block'} @@ -276,14 +344,21 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold() for child in window['children']) and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7}) - if closing and window.get('owner') == frame['hwnd'] and (standard_save or 'do you want to save the reusable block cell' in text): + forward = (window['class'] == '#32770' and window['text'] == 'Expedition PCB' + and any(child['class'].casefold() == 'static' and child.get('id') == 6172 + and ' '.join(child['text'].split()) == 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?' + for child in window['children']) + and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} in ({6,7}, {6,7,6171})) + if _owned_by_frame(window, frame) and (forward or closing and (standard_save or 'do you want to save the reusable block cell' in text)): targets = [child for child in window['children'] if child['class'].casefold() == 'button' and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'} and child.get('enabled', True)] if len(targets) == 1: + if session is None: return True if window['hwnd'] not in clicked: session.post(targets[0]['hwnd'], 0xF5) clicked.add(window['hwnd']) + if not closing: return True continue raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; ' f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} " @@ -291,6 +366,68 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked return False +def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post, emit, + read_windows=None, identity_check=None): + """Finish only the owned no-write diagnostic startup; never establish PASS. + + Cancellation already ended supervisor polling. Cleanup is its sole prompt + actor and uses the caller's original deadline and single-close state. + """ + from types import SimpleNamespace + read_windows = read_windows or (lambda: _windows(pcb_pid)) + windows = read_windows() + if any(window['pid'] != pcb_pid for window in windows): + raise RuntimeError('STARTUP_PROCESS_UNCONFIRMED') + current = _target_frame(windows, Path(job['pcb']).stem, require_ready=False) + frame = current + if frame is None and closed_frame is not None: + frame = state.get('frame') + if frame is None: + return closed_frame, False + old = state.get('frame') + if old is not None and any(frame[k] != old[k] for k in ('hwnd', 'pid', 'class', 'text')): + raise RuntimeError('STARTUP_DOCUMENT_CHANGED') + if closed_frame is not None and frame['hwnd'] != closed_frame: + raise RuntimeError('STARTUP_DOCUMENT_CHANGED') + if old is None: + # Explicit legacy cleanup supplies already checked registration. It is + # revalidated immediately before every action, never used as open proof. + confirmed = (identity_check is not None or + _load_evidence(job, pcb_pid, job['diagnostic_log_baseline'], require_autosave=False) is not None) + if not confirmed: + return closed_frame, False + state['frame'] = frame + # Validate every window before allowing a known No. An unknown sibling + # must not be hidden by the first recognized modal in enumeration order. + try: + for window in windows: + _pending_prompt([window], closing=closed_frame is not None, frame=frame, + pcb_name=Path(job['pcb']).name) + except RuntimeError as error: + if str(error).startswith('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt'): + return closed_frame, False + raise + actions = [] + def act(hwnd, message): + if read_windows() != windows: + raise RuntimeError('STARTUP_WINDOW_CHANGED: native snapshot changed before action') + if identity_check is not None and not identity_check(): + raise RuntimeError('STARTUP_IDENTITY_UNCONFIRMED: registered cleanup binding changed') + if time.monotonic() >= deadline: + raise RuntimeError('STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached') + post(hwnd, message) + actions.append((hwnd, message)) + if message == 0xF5: + emit(stage='startup_prompt_no', pcb_pid=pcb_pid, hwnd=hwnd, control_id=7) + pending = _pending_prompt(windows, closing=closed_frame is not None, frame=frame, + session=SimpleNamespace(post=act), clicked=state['clicked'], pcb_name=Path(job['pcb']).name) + if (closed_frame is None and not pending + and _target_frame(windows, Path(job['pcb']).stem) is not None): + act(frame['hwnd'], 0x10) + closed_frame = frame['hwnd'] + return closed_frame, bool(actions) + + def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict: """Prove this launch opened its native document, close it, and prove exit. @@ -301,8 +438,23 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No if not isinstance(baseline, dict) or 'started_ns' not in baseline or 'files' not in baseline: raise RuntimeError('DIAGNOSTIC_BASELINE_REQUIRED: snapshot before native launch') session = _NativeSession(job, int(pcb_pid), launcher_process) + def scan(deadline, *, closing=False): + while True: + if not closing: + _cancel(job) + try: + return _windows(int(pcb_pid)) + except RuntimeError as error: + if str(error) != 'DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s': + raise + # Discard the incomplete snapshot; no control action may use it. + emit(stage='diagnostic_window_retry', detail=str(error)) + if time.monotonic() >= deadline: + raise + time.sleep(min(.1, max(0, deadline-time.monotonic()))) try: deadline = time.monotonic() + max(.01, float(job['timeout'])) + startup_clicked = set() while True: _cancel(job) error = _read_bounded(error_reader) if error_reader else None @@ -310,38 +462,44 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No raise RuntimeError(str(error)) if not session.pcb_alive(): raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence') - windows = _windows(int(pcb_pid)) + windows = scan(deadline) if any(window['pid'] != int(pcb_pid) for window in windows): raise RuntimeError('DIAGNOSTIC_PID_MISMATCH') - frame = _target_frame(windows, Path(job['pcb']).stem) + frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False) # Startup splash/control windows are transient. Unknown windows # veto closing only once the target actually has loaded evidence. - pending = (_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name) - if frame is not None else True) evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False) - if frame is not None and not pending else None) - if evidence is not None: + if frame is not None else None) + pending = (_pending_prompt(windows, frame=frame, session=session if evidence else None, + clicked=startup_clicked, pcb_name=Path(job['pcb']).name) if frame is not None else True) + if evidence is not None and not pending and _target_frame(windows, Path(job['pcb']).stem) is not None: emit(stage='diagnostic_native_loaded_candidate', **evidence) break if time.monotonic() >= deadline: raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: current target MDI/path/PID logs missing') time.sleep(.1) - # Re-read the exact PID/frame before the sole close request. - _cancel(job) - windows = _windows(int(pcb_pid)) - _pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name) - current = _target_frame(windows, Path(job['pcb']).stem) - if current is None or current['hwnd'] != frame['hwnd']: - raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed') - session.post(frame['hwnd'], 0x10) - emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd']) + # Finish any in-flight supervisor poll before WM_CLOSE can create a prompt. close_deadline = time.monotonic() + 30 + intent = _request_close_handoff(job, pcb_pid, frame, session, emit, close_deadline) + # Re-read the exact PID/frame after acknowledgement and before the sole close. + _cancel(job) + error = _read_bounded(error_reader) if error_reader else None + if error: raise RuntimeError(str(error)) + windows = scan(close_deadline) + pending = _pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name) + current = _target_frame(windows, Path(job['pcb']).stem) + if (pending or time.monotonic() >= close_deadline or current is None + or any(current[key] != frame[key] for key in ('hwnd', 'pid', 'class', 'text'))): + raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed') + _cancel(job) + session.post(frame['hwnd'], 0x10) + emit(stage='diagnostic_wm_close', **intent) clicked = set() last_pending = '' while session.pcb_alive() or session.launcher_alive(): # Cancellation stops future work; an accepted normal close must # still finish before its queue slot can be safely released. - windows = _windows(int(pcb_pid)) if session.pcb_alive() else [] + windows = scan(close_deadline, closing=True) if session.pcb_alive() else [] previous_clicks = set(clicked) pending_error = None try: diff --git a/src/cbb_refresh_verify/dialog_probe.py b/src/cbb_refresh_verify/dialog_probe.py index bf02987..49b9eb4 100644 --- a/src/cbb_refresh_verify/dialog_probe.py +++ b/src/cbb_refresh_verify/dialog_probe.py @@ -238,11 +238,16 @@ class WindowProbe: process_name = "" controls = tuple(self._win32_control(child) for child in self._children(hwnd)) diagnostics = [] - try: - uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds) - controls = self._merge_controls(controls, uia_records) - except Exception as error: - diagnostics.append(f"UIA_ERROR: {error}") + native_panel = (process_name.casefold() == 'expeditionpcb.exe' + and phase in (DialogPhase.SAVE, DialogPhase.CLOSE) + and gui.GetClassName(hwnd) == '#32770' and gui.GetWindowText(hwnd) == 'Project Integration') + # This native panel's exact control IDs/text are sufficient; its UIA tree can stall Save. + if not native_panel: + try: + uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds) + controls = self._merge_controls(controls, uia_records) + except Exception as error: + diagnostics.append(f"UIA_ERROR: {error}") owner = 0 try: owner = int(gui.GetWindow(hwnd, 4) or 0) # GW_OWNER diff --git a/src/cbb_refresh_verify/dialog_rules.py b/src/cbb_refresh_verify/dialog_rules.py index a92884d..0e19d28 100644 --- a/src/cbb_refresh_verify/dialog_rules.py +++ b/src/cbb_refresh_verify/dialog_rules.py @@ -116,7 +116,7 @@ def _read_document(path: Path) -> list[dict[str, Any]]: return rules -def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[DialogRule, ...]: +def load_rules(default_path: Path, override_path: Path | None = None, *, diagnostic_only=False) -> tuple[DialogRule, ...]: ordered: list[str] = [] raw_by_id: dict[str, dict[str, Any]] = {} for raw in _read_document(default_path): @@ -137,7 +137,12 @@ def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[D else: ordered.append(rule_id) raw_by_id[rule_id] = dict(override) - return tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered) + rules = tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered) + if diagnostic_only: + # The process-bound diagnostic checker declines this prompt after proving the loaded project. + rules = tuple(replace(rule, category='OBSERVE_PROGRESS', action='', channels=(), target=()) + if rule.rule_id == 'forward-annotation-confirm' else rule for rule in rules) + return rules def _semantic_text(snapshot: WindowSnapshot) -> str: @@ -253,6 +258,22 @@ def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecisio channels=('win32_button_click', 'uia_invoke'), target=(('control_id', 7),), postcondition='window_gone', error_code='MENTOR_DATABASE_LOAD_FAILED', detail=' | '.join(snapshot.texts)) + if (snapshot.title == 'Project Integration' and snapshot.phase in (DialogPhase.SAVE, DialogPhase.CLOSE) + and snapshot.process_name.casefold() == 'expeditionpcb.exe' and snapshot.process_role == 'pcb' + and snapshot.window_class == '#32770' and snapshot.owner_hwnd and not snapshot.diagnostics + and not re.search(r'\b(?:errors?|failed|inconsistent)\b', combined)): + idle = {1033: 'No connectivity changes to be forward annotated', + 1032: 'No pending schematic CES changes to load into PCB', + 1035: 'No pending PCB changes to be back annotated', + 1034: 'No pending CES changes to load into PCB'} + complete = all(len(matches := [c for c in snapshot.controls if c.control_id == identifier]) == 1 + and matches[0].class_name == 'Static' and matches[0].name == text for identifier, text in idle.items()) + close = [c for c in snapshot.controls if c.control_id == 2] + if (complete and len(close) == 1 and close[0].class_name == 'Button' + and close[0].name.replace('&', '') == 'Close' and close[0].enabled): + return RuleDecision(rule_id='completed-integration-panel', category='SAFE_CONFIRM', + action='close_completed_integration', channels=('win32_button_click',), + target=(('control_id', 2),), postcondition='window_gone') matches = [rule for rule in rules if _matches(rule, snapshot, include_phase=True)] if matches: best_priority = max(rule.priority for rule in matches) diff --git a/src/cbb_refresh_verify/dialog_supervisor.py b/src/cbb_refresh_verify/dialog_supervisor.py index c7866b8..fcd5658 100644 --- a/src/cbb_refresh_verify/dialog_supervisor.py +++ b/src/cbb_refresh_verify/dialog_supervisor.py @@ -100,9 +100,10 @@ class DialogBackend(Protocol): class AgentDialogBackend: """Adapt the private-desktop JSONL client to the supervisor backend.""" - def __init__(self, client, *, pids=None) -> None: + def __init__(self, client, *, pids=None, before_action=None) -> None: self.client = client self.pids = pids + self.before_action = before_action def observe(self, phase: DialogPhase): if self.pids is None: @@ -111,6 +112,7 @@ class AgentDialogBackend: return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids) def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult: + if self.before_action is not None:self.before_action(snapshot,action) return self.client.perform( hwnd=snapshot.hwnd, fingerprint=stable_fingerprint(snapshot), @@ -123,7 +125,7 @@ class Win32DialogBackend: """Observe and act on dialogs without moving focus, cursor, or desktop.""" def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None, - win32con=None) -> None: + win32con=None, before_action=None) -> None: if win32gui is None: import win32gui as win32gui_module win32gui = win32gui_module @@ -138,6 +140,7 @@ class Win32DialogBackend: self.win32gui = win32gui self.win32process = win32process self.win32con = win32con + self.before_action = before_action def _allowed_pids(self) -> set[int]: values = self.pids() if callable(self.pids) else self.pids @@ -256,6 +259,7 @@ class Win32DialogBackend: return control.control_id def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]: + if self.before_action is not None:self.before_action(snapshot,action) buttons = self._buttons(snapshot) positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load", "是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载") diff --git a/src/cbb_refresh_verify/failed_session.py b/src/cbb_refresh_verify/failed_session.py index 421342d..6c8cdfd 100644 --- a/src/cbb_refresh_verify/failed_session.py +++ b/src/cbb_refresh_verify/failed_session.py @@ -1,5 +1,6 @@ """Close only an idle document whose native identity was already established.""" import json +from contextlib import ExitStack import os from pathlib import Path import time @@ -53,24 +54,79 @@ def _cancel_target(snapshot): return None +def _tip_target(snapshot): + from .dialog_agent import DialogActionExecutor + if snapshot.title != 'Tip of the Day' or snapshot.window_class != '#32770': + return None + target = DialogActionExecutor._target(snapshot, {'control_id': 1}) + return target if target is not None and target.class_name == 'Button' else None + + +def cancelled_prewrite_startup(job, pcb_pid=None): + """Positive ordinary pre-document cancellation proof; absence of Save is insufficient.""" + from .session_record import IDENTITY_KEYS, read_session_record + try: + if (job.get('diagnostic_only') is not False or job.get('interactive_input') + or job.get('native_lm_verify') or job.get('post_repair_consent') + or job.get('operation') != 'verify' or not job.get('operation_id') + or not job.get('desktop', '').startswith('CbbVerify_')): + return None + root=Path(job['root']) + if not Path(job['cancel_signal']).is_file() or (root/'save.log').exists():return None + path=root/'events.jsonl' + if path.stat().st_size>1024*1024:return None + events=[json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] + if any(str(e.get('stage','')).startswith(('save','integration','validate','failure_close')) + or e.get('stage') in ('startup_write_admitted','startup_supervisor_write_possible','identity_verified') + for e in events):return None + stages=('startup_supervisor_no_write','startup_prewrite_ready','startup_cancelled_prewrite') + selected=[] + for stage in stages: + matches=[(i,e) for i,e in enumerate(events) if e.get('stage')==stage] + if len(matches)!=1:return None + selected.append(matches[0]) + if [i for i,_ in selected]!=sorted(i for i,_ in selected):return None + binding={k:job[k] for k in ('operation_id','project','pcb','desktop')} + if any(any(e.get(k)!=v for k,v in binding.items()) for _,e in selected):return None + ready,cancelled=selected[1][1],selected[2][1] + pid=cancelled.get('pcb_pid') + if (not pid or pcb_pid is not None and pid!=pcb_pid + or cancelled.get('identity_verified') is not False or cancelled.get('write_admitted') is not False):return None + if not any(e.get('stage')=='pcb_worker_started' and e.get('pcb_pid')==pid + for e in events[selected[1][0]+1:selected[2][0]]):return None + session=read_session_record(Path(job['session_record_path']),evidence_root=root) + workers=[p for p in session.get('processes',()) if p.get('role')=='worker'] + if (session.get('operation_id')!=job['operation_id'] or session.get('desktop')!=job['desktop'] + or session.get('library')!=job['library'] or len(workers)!=1 + or not set(IDENTITY_KEYS)<=ready.get('worker_identity',{}).keys() + or any(ready.get('worker_identity',{}).get(k)!=workers[0].get(k) for k in IDENTITY_KEYS)):return None + baseline=ready.get('baseline') + if not isinstance(baseline,dict) or not {'started_ns','files'}<=baseline.keys():return None + return baseline + except (OSError,ValueError,KeyError,TypeError): + return None + + def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None, - timeout_seconds=20, launcher_process=None): + timeout_seconds=None, launcher_process=None): """Normally close our empty PCB after a diagnosed database startup failure. No COM attach: the global ROT can name another session. Only the exact read/write question is declined; no ownership is taken or version restored. Unknown windows and documents are retained. WM_CLOSE is cooperative. """ - import win32api, win32con, win32gui, win32process + import win32api, win32con, win32gui, win32process, win32event from .mentor_adapter import _process_details from .native_repair_ui import _current_desktop_name from .icdb_ownership import unreleased_addresses + from . import residual_sessions root = Path(job['root']) result = {'status': 'RETAINED', 'pcb_pid': pcb_pid} result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None, 'safe_to_continue': False} if launcher_process is not None: result['launcher_pid'] = launcher_process.pid + handles = ExitStack() try: desktop = job.get('desktop', '') if (job.get('interactive_input') or not desktop.startswith('CbbVerify_') @@ -79,14 +135,45 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: if not pcb_pid or pcb_pid in baseline_pids: raise ValueError('STARTUP_PROCESS_UNCONFIRMED') expected = os.path.normcase(os.path.abspath(job['pcb'])) + cancelled_diagnostic = (job.get('diagnostic_only') is True + and bool(job.get('cancel_signal')) and Path(job['cancel_signal']).exists() + and isinstance(job.get('diagnostic_log_baseline'), dict) + and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys() + and not (root/'save.log').exists()) + ordinary_baseline=cancelled_prewrite_startup(job,pcb_pid) + cancelled_prewrite=ordinary_baseline is not None + # Diagnostic close already owns a 30-second cleanup budget. Start it + # once here; the empty-to-loaded transition never resets that deadline. + if timeout_seconds is None: + timeout_seconds = 30 if cancelled_diagnostic or cancelled_prewrite else 20 deadline = time.monotonic() + max(0, timeout_seconds) sent = False declined_hwnd = None declined_kind = None cancelled_open = False + dismissed_tips = set() + close_handle = None + close_identity = None + close_frame = None + diagnostic_state = {'clicked': set()} + def cleanup_post(hwnd, message): + if (time.monotonic() >= deadline or _current_desktop_name() != desktop + or cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline + or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT + or residual_sessions._handle_identity(close_handle) != close_identity + or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid): + raise ValueError('STARTUP_ACTION_UNCONFIRMED') + win32gui.PostMessage(hwnd, message, 0, 0) while True: records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid] if not records: + if (close_handle is not None + and win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_OBJECT_0): + result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 原进程句柄尚未确认退出' + if time.monotonic() >= deadline: + break + time.sleep(.2) + continue if declined_hwnd is not None: cancelled_open = True result['cancelled_prompt'] = declined_kind @@ -111,6 +198,34 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: or '-reusablecircuit' not in [a.casefold() for a in args] or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]): raise ValueError('STARTUP_PROCESS_UNCONFIRMED') + if cancelled_diagnostic or cancelled_prewrite: + if time.monotonic() >= deadline: + result['detail']='STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached' + break + if cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline: + raise ValueError('STARTUP_IDENTITY_UNCONFIRMED: pre-write phase proof changed') + if (cancelled_diagnostic or cancelled_prewrite) and time.monotonic() < deadline: + if close_handle is None: + close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid)) + close_identity = residual_sessions._handle_identity(close_handle) + if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': + raise ValueError('STARTUP_PROCESS_UNCONFIRMED') + from .diagnostic_open import cancelled_startup_step + def ordinary_identity(): + from .diagnostic_open import _load_evidence + return (cancelled_prewrite_startup(job,pcb_pid)==ordinary_baseline + and _load_evidence(job,pcb_pid,ordinary_baseline,require_autosave=False) is not None) + closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state, + closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit, + identity_check=ordinary_identity if cancelled_prewrite else None) + if closed is not None and not sent: + sent, close_frame = True, closed + emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed, + document_identity='native_path_pid_logs', + cleanup='cancelled_prewrite' if cancelled_prewrite else 'cancelled_diagnostic') + if acted: + continue + if not sent: windows = [] def observe(hwnd, _): if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid @@ -121,6 +236,27 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: if declined_hwnd is not None and declined_hwnd not in windows: cancelled_open = True result['cancelled_prompt'] = declined_kind + dismissed = False + for hwnd in windows: + if hwnd in dismissed_tips or win32gui.GetClassName(hwnd) != '#32770': + continue + snapshot = _startup_snapshot(hwnd, pcb_pid) + target = _tip_target(snapshot) + if target is None: + continue + current = _startup_snapshot(hwnd, pcb_pid) + if current != snapshot or _tip_target(current) != target: + raise ValueError('STARTUP_TIP_CHANGED') + if cancelled_diagnostic or cancelled_prewrite: + cleanup_post(target.handle,win32con.BM_CLICK) + else: + win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0) + dismissed_tips.add(hwnd) + dismissed = True + emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=hwnd) + break + if dismissed: + continue # Prove the Tip disappeared; it does not prove a cancelled open. if declined_hwnd is None: for hwnd in windows: if win32gui.GetClassName(hwnd) != '#32770': @@ -134,7 +270,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: if _cancel_target(current) != target or current != snapshot: raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED') declined_kind, cancel = target - win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0) + if cancelled_diagnostic or cancelled_prewrite: + cleanup_post(cancel.handle,win32con.BM_CLICK) + else: + win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0) declined_hwnd = hwnd emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd, control_id=cancel.control_id, prompt=declined_kind) @@ -173,15 +312,38 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: win32gui.EnumChildWindows(main[0], child, None) addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb']) if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses): - win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0) + if close_handle is None: + close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid)) + close_identity = residual_sessions._handle_identity(close_handle) + if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': + raise ValueError('STARTUP_PROCESS_UNCONFIRMED') + if cancelled_diagnostic or cancelled_prewrite: + cleanup_post(main[0],win32con.WM_CLOSE) + else: + win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0) + close_frame = main[0] sent = True emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0]) # Observe exit even when the caller requested no extra wait. continue result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放' - # After the single owned WM_CLOSE, WMI may lose the executable/ - # command fields before removing the PID. Only observe exit here; - # never issue another close or treat missing fields as release. + # WMI fields can disappear during teardown. The held identity binds + # any late Tip action to the original process, never a reused PID. + if sent and time.monotonic() < deadline: + if _current_desktop_name() != desktop: + raise ValueError('STARTUP_DESKTOP_UNCONFIRMED') + snapshot = residual_sessions._process_windows({pcb_pid}) + windows = snapshot.get(pcb_pid, []) + if all(w.get('desktop') == desktop for w in windows): + dismissed = residual_sessions._dismiss_startup_tip( + dict(pid=pcb_pid, name='ExpeditionPCB.exe', scope_confirmed=True, startup_frame=close_frame, + **close_identity), close_handle, windows, + incomplete=residual_sessions._window_error(snapshot, pcb_pid), + dismissed=dismissed_tips, deadline=deadline) + if dismissed is not None: + dismissed_tips.add(dismissed) + emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=dismissed) + continue if time.monotonic() >= deadline: if sent: result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出' @@ -189,6 +351,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: time.sleep(.2) except Exception as error: result['detail'] = str(error) + finally: + handles.close() (root/'startup-close.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8') emit(stage='startup_close_result', **result) return result diff --git a/src/cbb_refresh_verify/file_probe.py b/src/cbb_refresh_verify/file_probe.py new file mode 100644 index 0000000..6406038 --- /dev/null +++ b/src/cbb_refresh_verify/file_probe.py @@ -0,0 +1,151 @@ +"""Bound read-only filesystem probes; keep proof handles alive through commit.""" +from contextlib import contextmanager, ExitStack +import hashlib +import json +from pathlib import Path +import re +import stat +import subprocess +import sys +import tempfile +import time +from uuid import uuid4 + + +@contextmanager +def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None): + """Only this pure probe may be terminated. stdin EOF releases its handles.""" + with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder: + job = Path(folder)/'request.json' + token = uuid4().hex + job.write_text(json.dumps({'token': token, 'library': str(library), + 'roots': [str(p) for p in roots] if roots is not None else None}), 'utf-8') + command = ([sys.executable] if getattr(sys, 'frozen', False) else + [sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)] + process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) + try: + deadline = time.monotonic()+max(.1, min(10, timeout_seconds)) + result_path = job.with_name('result.json') + while not result_path.exists(): + if stop is not None and stop.is_set(): + raise InterruptedError('FILE_PROBE_CANCELLED') + if time.monotonic() >= deadline: + raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放') + if process.poll() is not None: + raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据') + time.sleep(.02) + if stop is not None and stop.is_set(): + raise InterruptedError('FILE_PROBE_CANCELLED') + record = json.loads(result_path.read_text('utf-8')) + if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None: + error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效'))) + error.winerror = record.get('winerror') + raise error + # Duplicate the already-open handles before acknowledging the probe. + # Its exit can never create a gap in the parent's commit protection. + import win32api, win32con + with ExitStack() as protection: + child = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, process.pid) + protection.callback(child.Close) + if len(record['handles']) != len(record['exclusive_files'])+len(record['binding_files']): + raise OSError('FILE_PROBE_UNCONFIRMED: 证明句柄数量不符') + for handle in record['handles']: + owned = win32api.DuplicateHandle(child, handle, win32api.GetCurrentProcess(), + 0, False, win32con.DUPLICATE_SAME_ACCESS) + protection.callback(owned.Close) + yield {k: v for k, v in record.items() if k != 'handles'} + finally: + process.stdin.close() + try: + process.wait(.5) + except subprocess.TimeoutExpired: + process.terminate() # This executable only scans and opens read handles. + process.wait(3) + + +def _snapshot(library, roots): + from .scoped_manifest import scan_tree + entries = {library: library.lstat()} + for root in roots: + if root.exists(): + entries.update(scan_tree(root)) + native = sorted(path for path, info in entries.items() if stat.S_ISREG(info.st_mode) + and (path == library or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))) + if library not in native: + raise ValueError('目标库身份缺失') + addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr') + targets, signatures = [], {} + for address in addresses: + data = address.read_bytes() + signatures[str(address)] = hashlib.sha256(data).hexdigest() + database = address.parent.parent + matches = [] + for project in database.parent.glob('*.prj'): + if project not in entries or project.stat().st_size > 1024*1024: + continue + from .backup_recovery import _project_text + text = _project_text(project) + references = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', text, re.M) + if len(references) == 1 and (project.parent/references[0]).resolve() == database: + matches.append(project) + if len(matches) != 1 or database/'icdb.dat' not in native: + raise ValueError(f'地址未绑定唯一工程数据库,需人工核对:{address}') + targets.append({'project': str(matches[0]), 'database': str(database)}) + signatures[str(matches[0])] = hashlib.sha256(matches[0].read_bytes()).hexdigest() + return {'exclusive_files': [str(p) for p in native], 'addresses': [str(p) for p in addresses], + 'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures), + 'resource_scope': {'library': str(library), 'roots': [str(p) for p in roots], + 'projects': sorted(str(p) for p in entries if p.suffix.casefold() == '.prj'), + 'shared_dependencies': sorted(str(p.parent) for p in native + if p.is_relative_to(library.parent/'SymbolLibs') and p.name.casefold() == 'icdb.dat'), + 'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}} + + +def file_probe_main(job): + """No native launch, writes, repair, address deletion or process termination.""" + import win32con, win32file + job = Path(job) + request = json.loads(job.read_text('utf-8')) + result = {'token': request['token'], 'status': 'UNCONFIRMED'} + try: + def checked_path(value): + path = Path(value).absolute() + for part in (path, *path.parents): + try: + info = part.lstat() + except FileNotFoundError: + continue + if info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT: + raise ValueError(f'资源范围含重解析点:{part}') + return path.resolve() + library = checked_path(request['library']) + roots = [checked_path(p) for p in request['roots']] if request['roots'] is not None else [library.parent] + if library.suffix.casefold() != '.lmc' or any(not p.is_relative_to(library.parent) for p in roots): + raise ValueError('文件探测范围不属于所选库') + snapshot = _snapshot(library, roots) + with ExitStack() as stack: + handles = [] + for path in snapshot['exclusive_files']: + handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None, + win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) + stack.callback(handle.Close) + handles.append(int(handle)) + for path in snapshot['binding_files']: + handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ, + None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) + stack.callback(handle.Close) + handles.append(int(handle)) + if _snapshot(library, roots) != snapshot: + raise ValueError('占用检查期间资源集合变化') + pending = job.with_name('result.pending') + pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8') + pending.replace(job.with_name('result.json')) + sys.stdin.buffer.read(1) # Parent keeps stdin open until its commit finishes. + return 0 + except Exception as error: + pending = job.with_name('result.pending') + pending.write_text(json.dumps({**result, 'error': str(error), + 'winerror': getattr(error, 'winerror', None)}), 'utf-8') + pending.replace(job.with_name('result.json')) + return 1 diff --git a/src/cbb_refresh_verify/icdb_ownership.py b/src/cbb_refresh_verify/icdb_ownership.py index e6cca9f..9ab3dad 100644 --- a/src/cbb_refresh_verify/icdb_ownership.py +++ b/src/cbb_refresh_verify/icdb_ownership.py @@ -2,6 +2,19 @@ from pathlib import Path +def session_resource_scope(job): + """Persist declared targets; only fresh proof promotes them to observed scope.""" + library = Path(job['library']) + project, pcb = job.get('project'), job.get('pcb') + projects = [str(Path(project))] if project else [] + databases = [str(Path(p).parent/'database') for p in (project, pcb) if p] + shared = library.parent/'SymbolLibs/__ReusableBlocksSymb' + return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED', + 'library': str(library), 'operation_id': job.get('operation_id'), + 'block_name': job.get('block'), 'projects': projects, + 'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]} + + def database_directories(lmc_file, project, pcb): return tuple(dict.fromkeys(( Path(project).parent/'database', @@ -14,3 +27,20 @@ def unreleased_addresses(lmc_file, project, pcb): return [str(path/'cdbsvr/sAddress.adr') for path in database_directories(lmc_file, project, pcb) if (path/'cdbsvr/sAddress.adr').exists()] + + +def inspect_release_addresses(snapshot, *, stop=None): + """An address is a reason for native inspection, never an occupancy verdict.""" + import tempfile + from .native_repair import RepairTarget, run_native_repair + from .native_occupancy import confirmed_inspection + from .library_lock import LibraryBusy + results = [] + for item in snapshot['inspection_targets']: + target = RepairTarget(Path(item['project']), Path(item['database'])) + root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-')) + result = run_native_repair(target, root, inspection_only=True, stop=stop) + if not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE': + raise LibraryBusy(f'目标数据库未确认释放:{target.database};检查证据:{root}') + results.append(result) + return results diff --git a/src/cbb_refresh_verify/icdb_recovery.py b/src/cbb_refresh_verify/icdb_recovery.py index 78cf149..b7af1fa 100644 --- a/src/cbb_refresh_verify/icdb_recovery.py +++ b/src/cbb_refresh_verify/icdb_recovery.py @@ -8,7 +8,7 @@ import re ERROR_CODE = 'ICDB_REPAIR_REQUIRED' LOG_LIMIT = 128 * 1024 RECOVERY_ACTION = ( - '停止批次并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,' + '停止受影响工程的写入并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,' "使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。" '共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。' '不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。' @@ -16,6 +16,9 @@ RECOVERY_ACTION = ( _SESSION_LOSS = re.compile( r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+' r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE) +_INCONSISTENT = re.compile( + r"Project database \[([^\]\r\n]+)\] is inconsistent\. It has been manually copied while the iCDB Server was running\.\s*" + r"Please use iCDB Project Backup 'Repair project' functionality to fix this issue\.", re.I) _ICDB_MESSAGE = re.compile(r'(? LOG_LIMIT, 'icdb_errors': [' '.join(message.split()) for message in _icdb_error_paragraphs(decode_log(tail))], - 'session_losses': losses} + 'session_losses': losses, + 'inconsistent_databases': [match[1] for match in _INCONSISTENT.finditer(decode_log(tail))]} except FileNotFoundError: return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest(), 'icdb_errors': []} except OSError as error: @@ -161,6 +179,12 @@ def read_log_failure(path, baseline): historical = baseline.get('session_losses', []) if baseline else [] recovery = next((record for record in _session_losses(text) if appended or _session_identity(record) not in historical), None) + if recovery is None: + old = baseline.get('inconsistent_databases') if baseline else None + match = next((match for match in _INCONSISTENT.finditer(text) + if appended or old is not None and match[1] not in old), None) + if match is not None: + recovery = parse_recovery_request(match[0]) return text, recovery diff --git a/src/cbb_refresh_verify/library_lock.py b/src/cbb_refresh_verify/library_lock.py index 2e3d7ab..6769378 100644 --- a/src/cbb_refresh_verify/library_lock.py +++ b/src/cbb_refresh_verify/library_lock.py @@ -11,6 +11,28 @@ from uuid import uuid4 _guard = threading.RLock() _owners = {} +_library_guards = {} + + +def _library_guard(key): + """Serialize one lease without making slow resource probes global.""" + with _guard: + return _library_guards.setdefault(key, threading.RLock()) + + +def duplicate_worker_lease(library, process_handle): + """Keep the exact admitted exclusive file object alive across parent exit.""" + import win32api, win32con + lease = LibraryLock(library) + with _library_guard(lease.key): + owner = _owners.get(lease.key) + if owner is None: + return None + if owner['thread'] != threading.get_ident() or owner['retained'] or not owner['depth']: + raise LibraryBusy('不能将其他任务的库锁交给工作进程。') + remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), owner['handle'], + process_handle, 0, False, win32con.DUPLICATE_SAME_ACCESS) + return remote.Detach() # This handle belongs to the target process only. class LibraryBusy(OSError): @@ -82,10 +104,10 @@ def has_retained_library(library): return bool(owner and owner['retained']) -def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None): +def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None, stop=None): """Historical records trigger fresh proof, never process termination or repair.""" if not required: - with _guard: + with _library_guard(LibraryLock(library).key): owner = _owners.get(LibraryLock(library).key) marker = blocker_path(library) record = checkpoint_record(marker) @@ -108,10 +130,13 @@ def recheck_previous_release(library, evidence_dir, *, block_name=None, required logging.getLogger(__name__).warning('Release progress observer failed', exc_info=True) notify('previous_release_check', detail='正在复核历史记录对应的实际占用') try: - proof = release_retained_library(library, evidence_dir, block_name=block_name) + options = {'stop': stop} if stop is not None else {} + proof = release_retained_library(library, evidence_dir, block_name=block_name, **options) except Exception as error: notify('previous_release_unconfirmed', detail=str(error)) raise + from .operation_queue import note_metadata_progress + note_metadata_progress() notify('previous_release_confirmed', release_proof=proof, detail='已确认会话释放并归档历史记录;这不表示历史数据已恢复') return proof @@ -128,9 +153,14 @@ def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id, b export_record['block_name'] = block_name elif previous and previous['lease_id'] == lease_id and 'block_name' in previous: export_record['block_name'] = previous['block_name'] + from .icdb_ownership import session_resource_scope + scope = (previous.get('resource_scope') if previous and previous['lease_id'] == lease_id else None) + scope = scope or session_resource_scope({'library': library, 'block': export_record.get('block_name')}) with pending.open('w', encoding='utf-8') as stream: json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1, 'lease_id': lease_id, 'library': str(library), 'status': status, + 'lease_state': 'ACTIVE' if status == 'OPERATION_IN_PROGRESS' else 'RETAINED', + 'resource_scope': scope, 'blocked_resources': [], 'data_recovery_required': None, 'machine': socket.gethostname(), 'supervisor_created': win32process.GetProcessTimes(win32api.GetCurrentProcess())['CreationTime'].isoformat(), 'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream) @@ -159,7 +189,7 @@ class LibraryLock: return lease def __enter__(self): - with _guard: + with _library_guard(self.key): owner = _owners.get(self.key) if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'): try: @@ -180,7 +210,7 @@ class LibraryLock: if self.maintenance_guard is not None: return _enter_maintenance(self) import win32con, win32file - with _guard: + with _library_guard(self.key): owner = _owners.get(self.key) if owner: if owner['thread'] != threading.get_ident() or owner['retained']: @@ -246,7 +276,7 @@ class LibraryLock: self.maintenance_mutex = None def _exit_owned(self): - with _guard: + with _library_guard(self.key): if not self.entered: return owner = _owners[self.key] @@ -394,15 +424,13 @@ def _owner_is_blocking(item, library, roots): def _enter_maintenance(lease): """Transfer only a valid known lease, after project admission under lock.""" - import win32con, win32event, win32file - mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') - acquired = False + import win32con, win32file + from .operation_queue import check_active handle = None existing = None try: - acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) - if not acquired: raise LibraryBusy('已有 CBB 操作运行,维护不能接续') - with _guard: + check_active() + with _library_guard(lease.key): marker = blocker_path(lease.library) if marker.with_suffix('.pending').exists(): raise LibraryBusy('未完成检查点写入,不能自动接续') @@ -436,6 +464,7 @@ def _enter_maintenance(lease): with saved.open('xb') as stream: stream.write(old); stream.flush(); os.fsync(stream.fileno()) if saved.read_bytes() != old: raise OSError('原检查点归档校验失败') + check_active() lease_id = uuid4().hex _persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id) _owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle, @@ -443,19 +472,16 @@ def _enter_maintenance(lease): 'release_probe': lease.safe_to_release, 'block_name': None} lease.maintenance_proof = proof lease.entered = True - lease.maintenance_mutex = mutex return lease except Exception: if handle is not None and existing is None: handle.Close() - if acquired: win32event.ReleaseMutex(mutex) - mutex.Close() raise def owned_snapshot(path): """Read only a lease held by this thread, never reopen an exclusive file.""" import win32con, win32file - with _guard: + with _library_guard(_key(path)): owner = _owners.get(_key(path)) if not owner or owner['thread'] != threading.get_ident() or owner['retained']: return None @@ -470,19 +496,17 @@ def owned_snapshot(path): @contextmanager -def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoint=False): +def _prove_library_released(library, block_name=None, *, block_names=(), allow_unknown_checkpoint=False, stop=None): """Hold all native database read handles during explicit lease release.""" - import stat - import win32con, win32file + from .operation_queue import note_metadata_progress from .owner_probe import query_owners - from .scoped_manifest import scan_tree from .native_management import _retained_workers from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released from .native_engineering_identity import _OWNER_NAMES library = Path(library).resolve() assert_retained_exports_idle(library) - if any(worker.poll() is None and (allow_unknown_checkpoint - or not getattr(worker, 'cbb_library', None) or _key(worker.cbb_library) == _key(library)) + if any(worker.poll() is None and (not getattr(worker, 'cbb_library', None) + or _key(worker.cbb_library) == _key(library)) for worker in _retained_workers): raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。') from .com_runtime import initialize_com, uninitialize_com @@ -492,12 +516,17 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin 'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe', 'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES)) - scope_root = (Path(library).resolve().parent/'ReusableBlocksLP'/block_name/'Work').resolve() if block_name else None + blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ()))) + if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks): + raise ValueError('释放检查的工程名称无效') + scope_roots = tuple(library.parent/'ReusableBlocksLP'/name/'Work' for name in blocks) shared_root = Path(library).resolve().parent/'SymbolLibs' - if allow_unknown_checkpoint and scope_root is not None: + if allow_unknown_checkpoint and scope_roots: raise LibraryBusy('未知检查点必须执行完整库释放证明。') observed = [] def check_owners(): + if stop is not None and stop.is_set(): + raise InterruptedError('已停止释放检查') owners = [] observed.clear() from .session_record import active_write_records @@ -506,12 +535,11 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin for item in query_owners(names): if item['pid'] == os.getpid(): continue - if not allow_unknown_checkpoint: - roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,) - if not _owner_is_blocking(item, library, roots): - if _owner_matches_scope(item, library, roots) is None: - observed.append(item) - continue + roots = (*scope_roots, shared_root) if scope_roots else (library.parent,) + if not _owner_is_blocking(item, library, roots): + if _owner_matches_scope(item, library, roots) is None: + observed.append(item) + continue automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe') command = item['command'].casefold() if not automation or not command or any(flag in command for flag in ( @@ -519,68 +547,80 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin owners.append(item) if owners: raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}') + note_metadata_progress() return owners check_owners() - if scope_root is None: - entries = scan_tree(Path(library).parent) - else: - entries = {Path(library): Path(library).lstat()} - for root in (scope_root, shared_root): - if root.exists(): - entries.update(scan_tree(root)) - addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr' - and (scope_root is None or path.is_relative_to(scope_root) - or path.is_relative_to(shared_root))] - if addresses: - raise LibraryBusy(f'库中仍有数据库地址记录,不能自动解除:{addresses}') - # scan_tree already rejects links; only native candidates need file opens. - native = [path for path, metadata in entries.items() if stat.S_ISREG(metadata.st_mode) and ( - path == library - or (path.name.casefold() in ('icdb.dat', 'layoutdb.lyt') - and (scope_root is None or path.is_relative_to(scope_root) - or path.is_relative_to(shared_root))))] - if library not in native: - raise LibraryBusy('目标库身份缺失,不能解除协调阻止。') + from .file_probe import hold_release_files + roots = (*scope_roots, shared_root) if scope_roots else None + inspections = [] with ExitStack() as stack: + try: + files = stack.enter_context(hold_release_files(library, roots, stop=stop)) + except OSError as error: + blocked = LibraryBusy(str(error)) + blocked.winerror = getattr(error, 'winerror', None) + raise blocked from error + note_metadata_progress() + if files['addresses']: + # Native inspection needs the database; reacquire proof handles + # and compare the exact address/project binding before commit. + stack.close() + from .icdb_ownership import inspect_release_addresses + # Checkpoint I/O is per-library; only native inspection owns + # the host channel. The sidecar still excludes other writers. + if stop is not None and stop.is_set(): + raise InterruptedError('已停止释放检查') + inspections = inspect_release_addresses(files, stop=stop) + try: + current = stack.enter_context(hold_release_files(library, roots, stop=stop)) + except OSError as error: + blocked = LibraryBusy(str(error)) + blocked.winerror = getattr(error, 'winerror', None) + raise blocked from error + if any(current[key] != files[key] for key in ( + 'exclusive_files', 'addresses', 'signatures', 'inspection_targets')): + raise LibraryBusy('原生检查期间资源范围或地址身份变化。') + files = current + note_metadata_progress() export_proof = (prove_export_copies_released(library, allow_unknown_checkpoint=True) if allow_unknown_checkpoint else prove_export_copies_released(library)) export_copies = stack.enter_context(export_proof) - for path in native: - handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None, - win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) - stack.callback(handle.Close) owners = check_owners() - yield {'native_owners': owners, 'observed_owners': list(observed), - 'addresses': addresses, 'export_copies': export_copies, - 'unknown_checkpoint_recovery': allow_unknown_checkpoint, - 'exclusive_files': [str(path) for path in native]} + yield {**{k: v for k, v in files.items() if k not in ('status', 'token')}, + 'native_owners': owners, 'observed_owners': list(observed), + 'export_copies': export_copies, 'native_inspections': inspections, + 'data_recovery_required': any(item['repair_required'] for item in inspections) if inspections else None, + 'data_recovery_resources': [item['database'] for item in inspections if item['repair_required']], + 'unknown_checkpoint_recovery': allow_unknown_checkpoint} + finally: uninitialize_com(initialized) -def release_retained_library(library, evidence_dir, *, block_name=None): +def release_retained_library(library, evidence_dir, *, block_name=None, block_names=(), stop=None): """Reconcile historical leases after fresh owner/address/access proof. The upload sidecar is never deleted. This acknowledges process release, not the correctness of a partially changed library or its recovery state. """ - import win32con, win32event, win32file + import win32con, win32file + from .operation_queue import note_metadata_progress library = Path(library).resolve(strict=True) from .session_record import (retained_session_snapshot, acknowledge_library_release, reconciled_retained_sessions) retained = retained_session_snapshot(library) + requested_blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ()))) + if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in requested_blocks): + raise ValueError('释放检查的工程名称无效') evidence = Path(evidence_dir).resolve() if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence): raise ValueError('释放检查证据必须位于目标库之外。') lease = LibraryLock(library) - mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') - acquired = False external = None try: - acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) - if not acquired: - raise LibraryBusy('另一个 CBB 操作仍在运行。') - with _guard: + if stop is not None and stop.is_set(): + raise InterruptedError('已停止释放检查') + with _library_guard(lease.key): owner = _owners.get(lease.key) if owner and (not owner['retained'] or owner['depth']): raise LibraryBusy('本应用操作仍在使用库锁。') @@ -598,8 +638,10 @@ def release_retained_library(library, evidence_dir, *, block_name=None): before = {path: path.read_bytes() if path.exists() else None for path in checkpoints} unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items()) records = [checkpoint_record(path) for path, data in before.items() if data is not None] - scoped = (block_name if block_name and all(record and record.get('block_name') == block_name - for record in records) and (owner is None or owner.get('block_name') == block_name) else None) + scoped_blocks = (requested_blocks if requested_blocks and all(record + and record.get('block_name') in requested_blocks for record in records) + and (owner is None or owner.get('block_name') in requested_blocks) else ()) + scoped = scoped_blocks[0] if len(scoped_blocks) == 1 else None reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None, **{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}} for path, data in before.items() if data is not None @@ -610,28 +652,49 @@ def release_retained_library(library, evidence_dir, *, block_name=None): 'status': 'OWNER_RELEASE_UNCONFIRMED'}) foreign = sorted({item['block_name'] for item in reconciled if block_name and item.get('block_name') and item['block_name'] != block_name}) - proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else - _prove_library_released(library, block_name=scoped) - if scoped else _prove_library_released(library)) + options = {'stop': stop} if stop is not None else {} + if len(scoped_blocks) > 1: + options['block_names'] = scoped_blocks + proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True, **options) if unknown else + _prove_library_released(library, block_name=scoped, **options) + if scoped else _prove_library_released(library, **options)) with proof_context as proof: + if stop is not None and stop.is_set(): + raise InterruptedError('已停止释放检查') + with _guard: + if _owners.get(lease.key) is not owner: + raise LibraryBusy('释放检查期间租约身份变化,保留当前任务。') if unknown and proof.get('unknown_checkpoint_recovery') is not True: raise LibraryBusy('未知检查点缺少完整库释放证明,保留原文件。') if any((path.read_bytes() if path.exists() else None) != data for path, data in before.items()): raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。') root = evidence/('release-' + uuid4().hex) root.mkdir(parents=True, exist_ok=False) - reconciled_sessions = reconciled_retained_sessions(retained, block_name=scoped) + matching_retained = ({path: value for path, value in retained.items() + if value[1] in scoped_blocks} if scoped_blocks else retained) + reconciled_sessions = reconciled_retained_sessions(matching_retained, block_name=scoped) reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions) if item.get('block_name')}) record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof, - 'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY', - 'proof_block_name': scoped, 'reconciled_checkpoints': reconciled, + 'requested_block_name': block_name, 'requested_block_names': list(requested_blocks), + 'proof_scope': 'BLOCK' if scoped else 'BLOCKS' if scoped_blocks else 'LIBRARY', + 'proof_block_name': scoped, 'proof_block_names': list(scoped_blocks), + 'reconciled_checkpoints': reconciled, 'reconciled_foreign_blockers': sorted(set(foreign) | { block for block in reconciled_blocks if block_name and block != block_name}), 'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions, 'unknown_checkpoint_archived': unknown, + 'lease_state': 'RELEASED', 'blocked_resources': [], + 'data_recovery_required': proof.get('data_recovery_required', None), 'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')} - (root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8') + record['resource_scope'] = {**proof.get('resource_scope', {}), + 'scope_state': 'OBSERVED', 'library': str(library), 'block_name': scoped, + 'block_names': list(scoped_blocks), + 'lease_id': owner['lease_id'] if owner else None, + 'operation_ids': [item['operation_id'] for item in reconciled_sessions]} + pending = {**record, 'status': 'RELEASE_PENDING', 'lease_state': 'PENDING'} + (root/'release.json').write_text(json.dumps(pending, ensure_ascii=False, indent=2), encoding='utf-8') + note_metadata_progress() for index, checkpoint in enumerate(checkpoints): if checkpoint.exists(): data = checkpoint.read_bytes() @@ -639,15 +702,16 @@ def release_retained_library(library, evidence_dir, *, block_name=None): archived.write_bytes(data) if archived.read_bytes() != data: raise OSError('阻止记录归档校验失败,保持库锁。') + note_metadata_progress() + if stop is not None and stop.is_set(): + raise InterruptedError('已停止释放检查') checkpoint.unlink() # Checkpoint JSON only; never .lock. if owner: owner['handle'].Close() del _owners[lease.key] - acknowledge_library_release(record, retained, block_name=scoped) + (root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8') + acknowledge_library_release(record, matching_retained, block_name=scoped) return record finally: if external is not None: external.Close() - if acquired: - win32event.ReleaseMutex(mutex) - mutex.Close() diff --git a/src/cbb_refresh_verify/library_reader.py b/src/cbb_refresh_verify/library_reader.py index 09e8983..f576b73 100644 --- a/src/cbb_refresh_verify/library_reader.py +++ b/src/cbb_refresh_verify/library_reader.py @@ -203,20 +203,22 @@ def filesystem_status_map(library: Path, names): return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()} def read_library_fast(path: Path, *, status_reader=None): - """List CBBs from ReusableBlocksLP without touching COM or the .lmc. - - Useful when Library Manager is unavailable or already running: the folder - is the same source the LM tree shows, and an optional status_reader can - supply each item's flag without a full COM session. - """ + """Discover directories; this does not validate native format/registration.""" try: path = Path(path) + if path.suffix.casefold() != '.lmc': + return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。') if not path.is_file(): - return LibraryReadResult((), f'中心库不存在: {path}') + return LibraryReadResult((), f'INPUT_MISSING: 中心库不存在或不是文件: {path}') + with path.open('rb') as stream: + if not stream.read(1): + return LibraryReadResult((), 'INPUT_EMPTY: 中心库文件为空。') + if any(lock.is_dir() for lock in (path.with_suffix('.lock'), path.with_name('.'+path.stem+'.cbb-upload.lock'))): + return LibraryReadResult((), 'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录。') folder = path.parent/'ReusableBlocksLP' - if not folder.is_dir(): - return LibraryReadResult((), f'缺少 ReusableBlocksLP 目录: {folder}') - entries = [entry for entry in folder.iterdir() if entry.is_dir()] + if folder.exists() and not folder.is_dir(): + return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}') + entries = [entry for entry in folder.iterdir() if entry.is_dir()] if folder.is_dir() else [] names = tuple(sorted((entry.name for entry in entries), key=str.casefold)) statuses = {} if status_reader is not None and names: @@ -240,8 +242,11 @@ def read_library_fast(path: Path, *, status_reader=None): status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN') if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}: status = 'UNKNOWN' - records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status)) - return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name))) + records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status, + catalog_source='directory', status_source='status_reader' if status_reader else 'unknown')) + return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)), directory_count=len(entries)) + except PermissionError as error: + return LibraryReadResult((), f'INPUT_PERMISSION: 无权读取中心库: {error}') except Exception as error: return LibraryReadResult((), str(error)) diff --git a/src/cbb_refresh_verify/maintenance_entry.py b/src/cbb_refresh_verify/maintenance_entry.py index 3311e00..3d35279 100644 --- a/src/cbb_refresh_verify/maintenance_entry.py +++ b/src/cbb_refresh_verify/maintenance_entry.py @@ -19,22 +19,25 @@ def assert_native_idle(target=None): from .native_export_guard import assert_retained_exports_idle from .native_engineering_identity import _OWNER_NAMES from .library_lock import _key, _owner_matches_scope - library = None + library = Path(target.library) if target is not None and getattr(target, 'library', None) else None roots = () if target is not None: from .backup_recovery import _project_text roots = (Path(target.project).parent, Path(target.database)) - try: - lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M) - references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines] - if not references or any(match is None for match in references): - raise ValueError('CentralLibrary references are missing or invalid.') - libraries = {(Path(target.project).parent/match[1]).resolve(strict=True) for match in references} - if len(libraries) == 1 and all(path.suffix.casefold() == '.lmc' and path.is_file() for path in libraries): - library = libraries.pop() - roots += (library.parent/'SymbolLibs',) - except (OSError, ValueError): - pass # Missing/ambiguous original references cannot narrow retained ownership. + if library is not None: + roots += (library.parent/'SymbolLibs',) + else: + try: + lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M) + references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines] + if not references or any(match is None for match in references): + raise ValueError('CentralLibrary references are missing or invalid.') + libraries = {(Path(target.project).parent/match[1]).resolve(strict=True) for match in references} + if len(libraries) == 1 and all(path.suffix.casefold() == '.lmc' and path.is_file() for path in libraries): + library = libraries.pop() + roots += (library.parent/'SymbolLibs',) + except (OSError, ValueError): + pass # Missing/ambiguous original references cannot narrow retained ownership. assert_retained_exports_idle(library) if any(worker.poll() is None and (library is None or not getattr(worker, 'cbb_library', None) or _key(worker.cbb_library) == _key(library)) for worker in _retained_workers): diff --git a/src/cbb_refresh_verify/management.py b/src/cbb_refresh_verify/management.py index 5bf1810..fa71571 100644 --- a/src/cbb_refresh_verify/management.py +++ b/src/cbb_refresh_verify/management.py @@ -173,7 +173,9 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro write_admission=None): from .verify_runner import VerifyRequest, run_verify from .backup_recovery import _idle_check - import win32con, win32event + from contextlib import ExitStack + from .operation_queue import check_active, native_channel, task_stop, remember_result + stop = task_stop(stop) import pythoncom if adapter is None: from .native_management import NativeManagementAdapter @@ -190,8 +192,6 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro history = [] mutated = uploaded = removed = False owner_safe = True - mutex = None - acquired = False release_proof = None original = None change_report = None @@ -199,12 +199,13 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro nonlocal owner_safe if stop is not None and stop.is_set(): raise InterruptedError('MANAGEMENT_CANCELLED: 已停止后续原生操作') - owner_safe = False - try: - result = callback(*args) - except Exception as error: - owner_safe = getattr(error, 'safe_to_continue', False) is True - raise + with native_channel(): + owner_safe = False + try: + result = callback(*args) + except Exception as error: + owner_safe = getattr(error, 'safe_to_continue', False) is True + raise owner_safe = result.safe_to_continue return result def checkpoint(next_stage, **details): @@ -218,11 +219,15 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details}) def finish(status, detail='', safe=True): nonlocal change_report + remember_result(ManagementResult(request.operation, request.library, request.name, request.partition, + request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)) if mutated and original is not None and change_report is None: change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'], **comparison_rules(scope), 'unrelated_cbb_content_checked': False, 'detail': '原生会话尚未释放,未读取写后内容'} + remember_result(ManagementResult(request.operation, request.library, request.name, request.partition, + request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)) if safe: try: after = build_exclusive_library_manifest(library_root, scope=scope, progress=progress) @@ -244,12 +249,13 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro detail = (detail+'\n'+change_report['detail']).strip() result = ManagementResult(request.operation, request.library, request.name, request.partition, request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report) + remember_result(result) if report: try: _write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'}) except OSError as error: result = replace(result, detail=f'{detail}\n操作记录写入失败:{error}'.strip()) - return result + return remember_result(result) from .com_runtime import initialize_com, uninitialize_com initialized = initialize_com() try: @@ -283,6 +289,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro if request.operation in ('add', 'update'): if request.source is None: raise ValueError('新增/更新需要完整来源工程。') + if hasattr(adapter, 'validate_source'): + adapter.validate_source(request) source, pcb, top = source_project(request.source, request.top_level_block) if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent) or evidence.is_relative_to(source.parent) @@ -292,24 +300,30 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro root.mkdir(parents=True, exist_ok=False) report = root/'checkpoint.json' checkpoint('release_check') - mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') - acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) - if not acquired: - return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行;本次未启动。') from .library_lock import recheck_previous_release release_proof = recheck_previous_release(library, root/'previous-release', block_name=request.name, required=request.check_previous_release or bool(unfinished_target - and unfinished_target.get('safe_to_continue') is not True), progress=progress) + and unfinished_target.get('safe_to_continue') is not True), progress=progress, stop=stop) if release_proof is not None: checkpoint('release_check', release_proof=release_proof) if unfinished_target: - return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}') + from .session_record import _proof_covers_session + fresh = (request.check_previous_release and isinstance(release_proof, dict) + and _proof_covers_session(release_proof, {'library': str(library), 'block': request.name}) + and bool(release_proof.get('evidence_path')) + and Path(release_proof['evidence_path']).resolve().is_relative_to((root/'previous-release').resolve()) + and Path(release_proof['evidence_path']).is_file()) + if not fresh: + return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}') + checkpoint('release_check', confirmed_new_request=True, + previous_failed_operation=unfinished_target['evidence_path']) if hasattr(adapter, 'bind_library_mapping'): adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root) if hasattr(adapter,'bind_write_admission'): adapter.bind_write_admission(write_admission if native_idle_check else None) + check_active() with LibraryLock(library, block_name=request.name, safe_to_release=lambda: owner_safe or ( - callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))): + callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))), ExitStack() as native_stack: work = library.parent/'ReusableBlocksLP'/request.name/'Work' target_project, target_pcb = work/(request.name+'.prj'), work/'PCB/pcb.pcb' if request.operation != 'add': @@ -324,7 +338,6 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro if source: idle_check(library, source, pcb) checkpoint('catalog_before') - owner_safe = False before = invoke(adapter.catalog, library, root/'before') owner_safe = before.safe_to_continue if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1: @@ -366,6 +379,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro if request.operation in ('remove', 'update'): if stop is not None and stop.is_set(): return finish('CANCELLED', '已取消,未开始移除', owner_safe) + native_stack.enter_context(native_channel()) checkpoint('native_remove') mutated = True; owner_safe = False native = invoke(adapter.remove, request, root/'remove') @@ -385,6 +399,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro if stop is not None and stop.is_set(): return finish('RECOVERY_REQUIRED' if mutated else 'CANCELLED', '已停止后续导入;已发生的原生变更需要核对', owner_safe) + if not removed: + native_stack.enter_context(native_channel()) checkpoint('native_add') mutated = True; owner_safe = False native = invoke(adapter.add, staged, root/'add') @@ -413,6 +429,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或工程关联未确认一致。\n'+native.detail, owner_safe) uploaded = True checkpoint('uploaded') + native_stack.close() if not request.auto_verify: return finish('UPLOADED', '上传已确认;本批次未启用自动校验。\n'+native.detail) # Adapter catalog cannot return until its exact native owner exits. @@ -442,52 +459,63 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro status = 'BLOCKED' return finish(status, str(error), owner_safe) finally: - if mutex is not None: - if acquired: - win32event.ReleaseMutex(mutex) - mutex.Close() uninitialize_com(initialized) -def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, **kwargs): +def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs): from threading import Event from .write_admission import WriteAdmission + from .operation_queue import QueueCancelled, TaskHandoff, request_library_keys, remember_result, current_context + context = context or current_context() + if context is not None: + stop = stop if stop is not None else context.stop + progress = context.guard_callback(progress) if progress else None if stop is None: stop = Event() kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop)) results = [] retained_libraries = set() + cancelled = False for request in requests: - if stop is not None and stop.is_set(): - break - key = str(request.library).casefold() - if key in retained_libraries: + keys = request_library_keys(request, context) + stopped = (cancelled or stop.is_set() or context is not None + and (context.stop.is_set() or context.stop_after_current.is_set())) + if stopped or keys.intersection(retained_libraries): result = ManagementResult(request.operation, request.library, request.name, request.partition, request.source, request.auto_verify, 'complete', 'SKIPPED', True, - '同库原生会话尚未释放,未启动新的写入') + '队列已停止,未操作此 CBB' if stopped else '同库原生会话尚未释放,未启动新的写入') results.append(result) if progress: progress({'stage': result.status, 'block': result.name, 'detail': result.detail}) continue def action(): result = run_management(request, progress=progress, stop=stop, **kwargs) + remember_result(result) if not result.safe_to_continue: from .operation_lifecycle import recheck_failed_release - result = recheck_failed_release(request.library, request.name, result) + result = recheck_failed_release(request.library, request.name, result, stop=stop) return result - from .operation_queue import QueueCancelled try: result = item_executor(request, action) if item_executor is not None else action() except QueueCancelled as error: - results.append(ManagementResult(request.operation, request.library, request.name, request.partition, - request.source, request.auto_verify, 'complete', 'CANCELLED', True, str(error))) - break + known = error.result if isinstance(error, TaskHandoff) else None + if isinstance(known, ManagementResult): + result = replace(known, safe_to_continue=False, + status='RECOVERY_REQUIRED' if known.status in ('PASS', 'UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED') + else known.status, + release_proof=dict(status='RELEASE_PENDING', lease_state='PENDING', + resource_scope=error.scope, previous_release_proof=known.release_proof)) + else: + result = ManagementResult(request.operation, request.library, request.name, request.partition, + request.source, request.auto_verify, 'complete', + 'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED', + not isinstance(error, TaskHandoff), str(error)) results.append(result) if progress: progress({'stage': result.status, 'block': result.name, 'detail': result.detail, 'evidence_path': str(result.evidence_path or '')}) if not result.safe_to_continue: - retained_libraries.add(key) + retained_libraries.update(keys) if result.status == 'CANCELLED': - break + cancelled = True return results diff --git a/src/cbb_refresh_verify/management_transaction.py b/src/cbb_refresh_verify/management_transaction.py index 6b2743d..f8c490d 100644 --- a/src/cbb_refresh_verify/management_transaction.py +++ b/src/cbb_refresh_verify/management_transaction.py @@ -25,9 +25,9 @@ def fixture_authority(root, library, token): def current_lease(library): - from .library_lock import LibraryLock, _guard, _owners, blocker_path, checkpoint_record + from .library_lock import LibraryLock, _library_guard, _owners, blocker_path, checkpoint_record lease = LibraryLock(library) - with _guard: + with _library_guard(lease.key): owner = _owners.get(lease.key) guard = checkpoint_record(blocker_path(library)) if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident() diff --git a/src/cbb_refresh_verify/mentor_adapter.py b/src/cbb_refresh_verify/mentor_adapter.py index b2e127d..6bfa38c 100644 --- a/src/cbb_refresh_verify/mentor_adapter.py +++ b/src/cbb_refresh_verify/mentor_adapter.py @@ -68,6 +68,10 @@ def pcb_startup_timeout_seconds(timeout_seconds): return max(60.0, float(timeout_seconds)) +def lm_dispatch_timeout_seconds(timeout_seconds): + return max(.1, min(45.0, float(timeout_seconds))) + + def same_path(first, second): return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second))) @@ -680,6 +684,11 @@ def execute_job(job, emit): launcher_process = None completed = False identity_verified = False + write_admitted = False + prewrite_eligible = (job.get('diagnostic_only') is False and not job.get('native_lm_verify') + and not job.get('post_repair_consent') and not job.get('interactive_input') + and all(job.get(k) for k in ('operation_id','session_record_path','desktop'))) + startup_binding={k:job.get(k) for k in ('operation_id','project','pcb','desktop')} diagnostic_close_attempted = False helper = None app = doc = pi = None @@ -698,12 +707,15 @@ def execute_job(job, emit): from .diagnostic_open import snapshot_diagnostic_logs job['diagnostic_log_baseline'] = snapshot_diagnostic_logs(job) else: - ensure_pcb_central_library( - job['pcb'], - job['lmc_file'], - evidence_dir=Path(root) / 'diagnostics', - emit=emit, - ) + from .maintenance_entry import maintenance_project_files + for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])): + ensure_project_central_library(config, job['lmc_file'], + evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit) + if prewrite_eligible: + from .diagnostic_open import snapshot_diagnostic_logs + from .session_record import process_identity + emit(stage='startup_prewrite_ready',baseline=snapshot_diagnostic_logs(job), + worker_identity=process_identity(os.getpid()),**startup_binding) emit( stage='verify_mode', mode=('library_manager_native' if bool(job.get('native_lm_verify', False)) @@ -716,12 +728,13 @@ def execute_job(job, emit): pcb_started_ns = time.time_ns() if bool(job.get('native_lm_verify', False)): from .library_manager_verify import launch_library_verify + dispatch_deadline = time.monotonic()+lm_dispatch_timeout_seconds(job['timeout']) emit(stage='lm_launch', library=job['lmc_file'], block=job['block_name']) lm_session = launch_library_verify( job['lmc_file'], job['block_name'], emit, - time.monotonic() + pcb_startup_timeout_seconds(job['timeout']), + dispatch_deadline, mentor_bin=job.get('mentor_bin'), interactive_input=bool(job.get('interactive_input', False)), ) @@ -737,8 +750,8 @@ def execute_job(job, emit): worker_parent_pid = int(launcher_process.pid) emit(stage='pcb_launcher_started', launcher_pid=worker_parent_pid, command=list(command), strategy='reusable_circuit_direct') - pcb_deadline = reset_verify_activity_deadline( - 0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout'])) + pcb_deadline = (dispatch_deadline if job.get('native_lm_verify') else + time.monotonic()+pcb_startup_timeout_seconds(job['timeout'])) while time.monotonic() < pcb_deadline: if job.get('cancel_signal') and Path(job['cancel_signal']).exists(): raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求') @@ -771,6 +784,8 @@ def execute_job(job, emit): break time.sleep(.2) if worker_pid is None: + if job.get('native_lm_verify'): + raise RuntimeError('VERIFY_DISPATCH_FAILED: LM 菜单返回但未观察到目标 PCB,未执行校验') raise RuntimeError('ReusableCircuit common 启动后未观察到 wg PCB 子进程') if job.get('diagnostic_only'): # Global PCB COM can wait on another design's modal window. @@ -805,6 +820,10 @@ def execute_job(job, emit): # the old, working path acquires the token inside the SysWOW64 # cscript save helper below. The PCB UI license dialog has already # been handled by the private-desktop supervisor. + if job.get('cancel_signal') and Path(job['cancel_signal']).exists(): + raise RuntimeError('VERIFY_CANCELLED: 未开始工程集成') + write_admitted = True + if prewrite_eligible:emit(stage='startup_write_admitted',**startup_binding) refresh_integration( pi, emit=emit, @@ -910,6 +929,10 @@ def execute_job(job, emit): elif not completed and worker_pid is not None: try: from .failed_session import close_failed_startup + if (prewrite_eligible and not write_admitted and not identity_verified + and job.get('cancel_signal') and Path(job['cancel_signal']).exists()): + emit(stage='startup_cancelled_prewrite',pcb_pid=worker_pid, + identity_verified=False,write_admitted=False,**startup_binding) failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit, launcher_process=launcher_process) if failed_close.get('status') == 'CLOSED' and lm_session is not None: @@ -926,6 +949,8 @@ def execute_job(job, emit): ) if completed and lm_session is not None: lm_session.close() + elif worker_pid is None and lm_session is not None: + lm_session.close() # No PCB was dispatched; close only this owned LM. def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *, diff --git a/src/cbb_refresh_verify/models.py b/src/cbb_refresh_verify/models.py index 551c12c..eb519fc 100644 --- a/src/cbb_refresh_verify/models.py +++ b/src/cbb_refresh_verify/models.py @@ -7,8 +7,15 @@ class CbbRecord: partition_name: str logical_type: str = "LP" status: str = "UNKNOWN" + catalog_source: str = "provided" + status_source: str = "provided" + missing_reason: str = "" @dataclass(frozen=True) class LibraryReadResult: records: tuple[CbbRecord, ...] error: str | None = None + directory_count: int | None = None + native_count: int | None = None + missing_project_count: int | None = None + catalog_verified: bool = False diff --git a/src/cbb_refresh_verify/native_backup.py b/src/cbb_refresh_verify/native_backup.py index bdd0e3e..7796315 100644 --- a/src/cbb_refresh_verify/native_backup.py +++ b/src/cbb_refresh_verify/native_backup.py @@ -1,7 +1,11 @@ """Open the official backup UI; version selection and writes stay native.""" from dataclasses import dataclass import json +import hashlib +import os from pathlib import Path +from pathlib import PureWindowsPath +import re import stat import subprocess import sys @@ -39,6 +43,36 @@ def native_backup_project(library, block): return project +def native_backup_target(request, *, mode='versions', target_database=None): + """Bind the official tool without requiring an openable/healthy PCB.""" + from .backup_recovery import _project_text + from .maintenance_entry import maintenance_project_files + if mode not in ('versions', 'repair'): + raise ValueError('NATIVE_TARGET_MODE_INVALID') + project = native_backup_project(request.lmc_file, request.block_name) + candidates = (project,) + if target_database is not None: + pcbs = list((project.parent/'PCB').glob('*.pcb')) + if len(pcbs) != 1: + raise ValueError('NATIVE_TARGET_UNCONFIRMED: 无法唯一绑定 PCB 工程') + candidates = maintenance_project_files(project, pcbs[0]) + matches = [] + for config in candidates: + values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"\s*$', _project_text(config), re.M) + if len(values) != 1 or not values[0] or PureWindowsPath(values[0]).root or PureWindowsPath(values[0]).drive: + if config == project or target_database is None: + raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 必须唯一且为工程内相对路径,不支持绝对路径或多条记录') + continue + database = (config.parent/values[0]).resolve() + if not database.is_relative_to(project.parent.resolve()): + raise ValueError('NATIVE_TARGET_UNCONFIRMED: 数据库不在当前工程内') + if target_database is None or database == Path(target_database).resolve(): + matches.append((config, database)) + if len(matches) != 1: + raise ValueError('NATIVE_TARGET_UNCONFIRMED: 诊断数据库未绑定唯一工程 PRJ') + return matches[0] + + @dataclass class NativeBackupSession: process: object @@ -46,10 +80,18 @@ class NativeBackupSession: library: Path block: str path_lease: object = None + mode: str = 'versions' + project: Path | None = None + database: Path | None = None + session_record_path: Path | None = None + operation_id: str | None = None -def launch_native_backup(request): - project = native_backup_project(request.lmc_file, request.block_name) +def launch_native_backup(request, *, mode='versions', target_database=None): + from .library_lock import recheck_previous_release + from .session_record import register_worker_session + from .operation_queue import check_active, native_channel, task_stop, commit_worker_start + project, database = native_backup_target(request, mode=mode, target_database=target_database) native_backup_executable(request.mentor_bin) root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12]) library_root = Path(request.lmc_file).resolve().parent @@ -57,17 +99,55 @@ def launch_native_backup(request): raise ValueError('运行记录目录需位于中心库之外。') root.mkdir(parents=True) job = root/'request.json' - job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name, - 'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8') + recheck_previous_release(request.lmc_file, root/'previous-release', + block_name=request.block_name, stop=task_stop(None)) + record = {'library': str(request.lmc_file), 'block': request.block_name, + 'project': str(project), 'database': str(database), 'mode': mode, + 'project_sha256': hashlib.sha256(project.read_bytes()).hexdigest(), + 'target_database': str(target_database) if target_database is not None else None, + 'mentor_bin': request.mentor_bin, 'automatic_repair': False, + 'operation': 'native_backup', 'operation_id': root.name, + 'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-worker.signal'), + 'start_gate_protocol': 'event-v1', + 'cancel_signal': str(root/'cancel-worker.signal'), 'supervisor_pid': os.getpid(), 'desktop': None} + job.write_text(json.dumps(record, ensure_ascii=False), 'utf-8') command = ([sys.executable] if getattr(sys, 'frozen', False) else [sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)] - process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) - return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name) + try: + check_active() + process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) + register_worker_session(process, record) + with native_channel(): + check_active() + commit_worker_start(process, record) + except BaseException: + Path(record['cancel_signal']).touch() # The unadmitted child exits without native launch. + raise + return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name, + mode=mode, project=project, database=database, session_record_path=Path(record['session_record_path']), + operation_id=record['operation_id']) + + +class _BackupJobWriter: + """Independent Job handle keeps future descendants inside the writer boundary.""" + def __init__(self, job): + import win32api, win32con + current = win32api.GetCurrentProcess() + self.job = win32api.DuplicateHandle(current, job, current, 0, False, win32con.DUPLICATE_SAME_ACCESS) + + def poll(self): + import win32job + if self.job is None: + return 0 + if win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList): + return None + self.job.Close(); self.job = None + return 0 class _NativeBackupProcess: """Track this visible tool and its descendants without killing on close.""" - def __init__(self, command, cwd): + def __init__(self, command, cwd, *, before_resume=None): import win32con, win32job, win32process self.job = win32job.CreateJobObject(None, '') startup = win32process.STARTUPINFO() @@ -80,6 +160,8 @@ class _NativeBackupProcess: raise try: win32job.AssignProcessToJobObject(self.job, self.handle) + if before_resume is not None: + before_resume(self) win32process.ResumeThread(thread) except Exception: # No native code has run while suspended; there can be no DB write. @@ -102,11 +184,54 @@ class _NativeBackupProcess: self.handle.Close(); self.job.Close() +def run_native_backup_worker(job, *, admission_state=None): + """Publish admission refusal only when this exact worker never entered native work.""" + from .desktop_worker import run_native_worker + from .management import _write_json + from .session_record import IDENTITY_KEYS, process_identity, read_session_record + job = Path(job) + entered = False + request = json.loads(job.read_text('utf-8')) + identity = process_identity(os.getpid()) + def registered(): + try: + path = Path(request['session_record_path']) + session = read_session_record(path, evidence_root=job.parent) + return (session['operation_id'] == request['operation_id'] + and session.get('operation') == 'native_backup' + and session.get('library') == request['library'] and session.get('block') == request['block'] + and request.get('project') in session.get('resource_scope', {}).get('projects', ()) + and any(all(process.get(key) == identity[key] for key in IDENTITY_KEYS) + for process in session.get('processes', ()) if process.get('role') == 'worker')) + except (OSError, ValueError, KeyError, TypeError): + return False # Unknown registration never establishes a safe terminal result. + def execute(path): + nonlocal entered + if not registered(): + raise ValueError('NATIVE_BACKUP_ADMISSION_UNCONFIRMED: 当前工程与工作进程未登记') + entered = True + return native_backup_worker_main(path) + try: + return run_native_worker(execute, job, admission_state=admission_state) + except Exception as error: + bound = registered() + _write_json(job.with_name('result.json'), {'status': 'FAILED', 'detail': str(error), + 'operation_id': request.get('operation_id'), 'worker_identity': identity, + 'library': request.get('library'), 'block': request.get('block'), + 'mode': request.get('mode', 'versions'), 'project': request.get('project'), + 'database': request.get('database'), 'worker_entered': entered, + 'native_started': None if entered else False, + 'safe_to_continue': bound and not entered, 'restore_confirmed': False, + 'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False}) + return 1 + + def native_backup_worker_main(job, *, process_factory=None): from .library_lock import LibraryLock from .management import _write_json job = Path(job) - result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False} + result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False, + 'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False} native = None def write_evidence(name, value): try: @@ -117,14 +242,34 @@ def native_backup_worker_main(job, *, process_factory=None): try: record = json.loads(job.read_text('utf-8')) library, block = Path(record['library']), record['block'] - result.update(library=str(library), block=block) - project = native_backup_project(library, block) + result.update(library=str(library), block=block, operation_id=record.get('operation_id')) + from types import SimpleNamespace + mode = record.get('mode', 'versions') + project, database = native_backup_target(SimpleNamespace(lmc_file=library, block_name=block), + mode=mode, target_database=record.get('target_database')) if project != Path(record['project']): raise ValueError('工程身份已变化,未打开原生工具。') + if record.get('project_sha256') and hashlib.sha256(project.read_bytes()).hexdigest() != record['project_sha256']: + raise ValueError('工程内容身份已变化,未打开原生工具。') + if record.get('database') and database != Path(record['database']): + raise ValueError('数据库身份已变化,未打开原生工具。') + result.update(mode=mode, project=str(project), database=str(database), + session_record_path=record.get('session_record_path')) executable = native_backup_executable(record.get('mentor_bin', '')) released = True - with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released): - native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent) + with LibraryLock(library, checkpoint=bool(record.get('session_record_path')), + block_name=block, safe_to_release=lambda: released): + from .maintenance_entry import _assert_native_idle_for + _assert_native_idle_for(SimpleNamespace(project=project, database=database, library=library)) + def admitted(process): + from .session_record import update_worker_state + from .desktop_worker import register_native_writer + if record.get('session_record_path'): + update_worker_state(record, 'NATIVE_CALL', identities=(('native', process.pid),), required=True) + register_native_writer(_BackupJobWriter(process.job)) + command = [str(executable), '-p', str(project)] # User alone invokes Repair in the official UI. + native = (process_factory(command, project.parent) if process_factory else + _NativeBackupProcess(command, project.parent, before_resume=admitted)) released = False result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False) write_evidence('state.json', result) @@ -145,6 +290,7 @@ def native_backup_worker_main(job, *, process_factory=None): time.sleep(.25) released = True result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True) + result['release'] = {'native_exited': True, 'remaining_pids': [], 'safe_to_continue': True} return 0 if result['native_exit_code'] == 0 else 1 except Exception as error: result.update(status='FAILED', detail=str(error), safe_to_continue=native is None) diff --git a/src/cbb_refresh_verify/native_export_guard.py b/src/cbb_refresh_verify/native_export_guard.py index d64ebea..9a274c4 100644 --- a/src/cbb_refresh_verify/native_export_guard.py +++ b/src/cbb_refresh_verify/native_export_guard.py @@ -79,7 +79,7 @@ def assert_retained_exports_idle(library=None): def begin_export_analysis(library, root, project): - from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy + from .library_lock import LibraryLock, _library_guard, blocker_path, checkpoint_record, LibraryBusy from .management_transaction import current_lease library, root, project = Path(library).resolve(), Path(root).resolve(), Path(project).resolve() owner = current_lease(library) @@ -89,7 +89,7 @@ def begin_export_analysis(library, root, project): record = {'protocol': 'cbb-native-export-analysis', 'version': 1, 'token': uuid4().hex, 'library': str(library), 'lease_id': owner['lease_id'], 'supervisor_pid': owner['supervisor_pid'], 'analysis_root': str(root), 'project': str(project)} - with _guard: + with _library_guard(LibraryLock(library).key): marker = blocker_path(library) checkpoint = checkpoint_record(marker) if (checkpoint is None or checkpoint['lease_id'] != owner['lease_id'] @@ -100,6 +100,77 @@ def begin_export_analysis(library, root, project): return record['token'] +def _external_export_library(process): + """Recover a live copy's owner; an outside path alone proves no association.""" + import ntpath + import re + import stat + import subprocess + from .failed_session import _command_args + from .backup_recovery import _native_scope_match + from .native_engineering_identity import _process_birth + def read(path): + info = path.lstat() + if info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT or info.st_size > 1024*1024: + raise ValueError('Untrusted export association') + value = json.loads(path.read_text('utf-8')) + if not isinstance(value, dict): + raise ValueError('Invalid export association') + return value + try: + birth = _process_birth(process.get('created')) + image = process.get('executable') + if birth is None or not image or ntpath.basename(image).casefold() != process['name'].casefold(): + return None + candidates = [] + for arg in _command_args(process.get('command', ''))[1:]: + path = Path(arg.split('=', 1)[-1]) + if path.is_absolute() and (path.suffix.casefold() in ('.prj', '.pcb') + or path.name.casefold() in ('database', 'icdb.dat')): + candidates.append(path) + associations = set() + for path in candidates: + project_root = next((p for p in (path, *path.parents) if p.name.casefold() == 'project'), None) + if project_root is None or project_root.resolve() != project_root: + return None + root = project_root.parent + owner = read(root/'export-owner.json') + project, library = Path(owner['project']), Path(owner['library']) + if (owner.get('protocol') != 'cbb-native-export-analysis' or owner.get('version') != 1 + or not re.fullmatch('[0-9a-f]{32}', str(owner.get('token', ''))) + or not re.fullmatch('[0-9a-f]{32}', str(owner.get('lease_id', ''))) + or type(owner.get('supervisor_pid')) is not int or owner['supervisor_pid'] <= 0 + or Path(owner['analysis_root']) != root or project.parent != project_root + or project.suffix.casefold() != '.prj' or not project.is_file() + or not library.is_absolute() or library.suffix.casefold() != '.lmc' or not library.is_file() + or root.is_relative_to(library.parent) or library.parent.is_relative_to(root) + or _native_scope_match(process['command'], roots=(project_root,)) is not True): + return None + matched = False + for kind, executable in (('ascii', 'icdb2ascii.exe'), ('csv', 'icdb2csv.exe'), ('edif', 'edifexporter.exe')): + evidence = root/(kind+'-process.json') + if not evidence.exists(): + continue + recorded = read(evidence) + command = recorded.get('command') + if (recorded.get('native_started') is not True or recorded.get('kind') != kind + or not isinstance(command, list) or not command or not all(isinstance(v, str) for v in command) + or ntpath.basename(command[0]).casefold() != executable + or _native_scope_match(subprocess.list2cmdline(command), roots=(project_root,)) is not True): + continue + for identity in recorded.get('process_identities', []): + if (identity.get('pid') == process['pid'] and _process_birth(identity.get('created')) == birth + and identity.get('executable') + and ntpath.normcase(identity['executable']) == ntpath.normcase(image)): + matched = True + if not matched: + return None + associations.add(library.resolve()) + return next(iter(associations)) if len(associations) == 1 else None + except (OSError, ValueError, KeyError, TypeError, AttributeError): + return None + + @contextmanager def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, unstarted_token=''): """Fresh process and exclusive-copy proof, including after interpreter exit.""" @@ -116,9 +187,12 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns raise LibraryBusy('Invalid library checkpoint cannot release export ownership.') # Only the explicit release path supplies full-library/native proof and # archives the unchanged metadata while its coordination handle is held. - assert_retained_exports_idle() - if any(p['name'].casefold() in _OWNER_NAMES for p in _process_snapshot()): - raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.') + for process in _process_snapshot(): + if process['name'].casefold() not in _OWNER_NAMES: + continue + associated_library = _external_export_library(process) + if associated_library is None or associated_library == library: + raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.') yield [] return if checkpoint is None or 'export_analysis' not in checkpoint: @@ -208,8 +282,8 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns def finish_export_analysis(library, token, *, native_not_started=False): - from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy - with _guard, prove_export_copies_released(library, + from .library_lock import LibraryLock, _library_guard, blocker_path, checkpoint_record, LibraryBusy + with _library_guard(LibraryLock(library).key), prove_export_copies_released(library, unstarted_token=token if native_not_started else ''): marker = blocker_path(library) checkpoint = checkpoint_record(marker) diff --git a/src/cbb_refresh_verify/native_management.py b/src/cbb_refresh_verify/native_management.py index 4235476..9c68633 100644 --- a/src/cbb_refresh_verify/native_management.py +++ b/src/cbb_refresh_verify/native_management.py @@ -53,9 +53,10 @@ def removal_output_ok(code, output, name, partition): + r"' from partition '" + re.escape(partition) + r"'\.", output) is not None) -def catalog_dialog_action(title, text): +def catalog_dialog_action(title, text, *, read_only=False): value = (title + '\n' + text).casefold() - if ('this central library must be updated' in value or 'select flow type' in value): + if ('this central library must be updated' in value or 'select flow type' in value + or read_only and ('save' in value or 'upgrade' in value)): return 'cancel' return 'observe' @@ -222,6 +223,7 @@ class NativeManagementAdapter: from .session_record import process_identity job = {**job, 'cancel_signal': str(evidence/'cancel-management.signal'), 'start_gate': str(evidence/'start-management.signal'), + 'start_gate_protocol': 'event-v1', 'session_record_path': str(evidence/'session.json'), 'operation_id': uuid4().hex, 'supervisor_pid': os.getpid(), 'supervisor_identity': process_identity(os.getpid()), 'block': job.get('name')} @@ -242,12 +244,17 @@ class NativeManagementAdapter: worker.bind_cancellation(job['cancel_signal']) if hasattr(worker, 'bind_session'): worker.bind_session(job) - Path(job['start_gate']).touch() - while worker.poll() is None and time.monotonic() < deadline: - if self.stop is not None and self.stop.is_set(): - Path(job['cancel_signal']).touch() - break - time.sleep(.1) + from contextlib import nullcontext + from .operation_queue import commit_worker_start, native_channel + # Only admitted native waiting outlives the UI's metadata deadline. + channel = native_channel(read_only=True) if job.get('worker_role') == 'catalog_readonly' else nullcontext() + with channel: + commit_worker_start(worker, job) + while worker.poll() is None and time.monotonic() < deadline: + if self.stop is not None and self.stop.is_set(): + Path(job['cancel_signal']).touch() + break + time.sleep(.1) if worker.poll() is None: # DesktopWorker.close() requests a kill without a cancellation file. # Keep this exact worker alive until its native call returns normally. @@ -275,7 +282,8 @@ class NativeManagementAdapter: worker.close() def catalog(self, library, evidence): - result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(library))}, evidence) + result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly', + 'library': str(absolute_preserving_drive(library))}, evidence) if not result.get('success') or not result.get('safe_to_continue'): raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'), safe_to_continue=result.get('safe_to_continue') is True) @@ -300,12 +308,31 @@ class NativeManagementAdapter: removal_input(request.name, request.partition) if request.partition != 'Logical-Physical' or catalog.flow != 1: raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。') + self.validate_source(request) + + def validate_source(self, request, *, probe_files=True): + if request.operation not in ('add', 'update'): + return + if request.source is None: + raise ValueError('请选择完整来源工程。') + source = Path(request.source) + if probe_files: + source = source.resolve(strict=True) + if source.suffix.casefold() != '.prj' or probe_files and not source.is_file(): + raise ValueError('请选择完整来源工程的 PRJ 文件。') + if source.stem.casefold() != request.name.casefold(): + raise ValueError(f'SOURCE_NAME_MISMATCH: 来源工程名 {source.stem} 与目标 {request.name} 不一致;' + '当前版本不支持改名,请重新选择同名 PRJ。') def add(self, request, evidence): # Route readiness never grants production mutation authority. capability = self.capabilities()['add'] if not capability.supported: return NativeOutcome(False, True, capability.reason, evidence_path=Path(evidence)) + try: + self.validate_source(request) + except (OSError, ValueError) as error: + return NativeOutcome(False, True, str(error), evidence_path=Path(evidence)) return self._add_transaction(request, Path(evidence)) def prepare_add_transaction(self, request, root, *, original_source): @@ -315,6 +342,7 @@ class NativeManagementAdapter: from .management import source_project from .backup_recovery import _align_library try: + self.validate_source(request) if not self.capabilities()['add'].supported: raise ValueError(self.capabilities()['add'].reason) validate_native_copy_paths(request.source, request.library, request.name) @@ -442,6 +470,7 @@ class NativeManagementAdapter: return NativeOutcome(False, True, 'Native Add requires an existing staged PRJ source project.', evidence_path=evidence) try: + self.validate_source(request) source_identity = engineering_identity(source) except (ValueError, OSError) as error: return NativeOutcome(False, True, f'Unable to read source engineering identity: {error}', @@ -686,11 +715,11 @@ def _dispatch_diagnostics(root, stage, app, library, *, paths=None): stream.write(json.dumps(record, ensure_ascii=False, default=str) + '\n') -def _set_probe_field(hwnd, control_id, expected, root): - """Set/read a remote Edit with a one-second total message budget.""" +def _set_probe_field(hwnd, control_id, expected, root, *, read_only=False): + """Set/read or revalidate a remote Edit with a one-second total message budget.""" from ctypes import wintypes record = {'control_id': control_id, 'hwnd': int(hwnd), 'expected': expected, - 'actual': None, 'matched': False} + 'actual': None, 'matched': False, 'read_only': read_only} deadline = time.monotonic() + 1.0 try: user32 = ctypes.WinDLL('user32', use_last_error=True) @@ -707,9 +736,10 @@ def _set_probe_field(hwnd, control_id, expected, root): remaining, ctypes.byref(returned)): raise TimeoutError(f'原生字段消息超时或失败:{control_id}, Windows={ctypes.get_last_error()}') return returned.value - text = ctypes.create_unicode_buffer(expected) - if not message(0x000C, 0, text): # WM_SETTEXT - raise RuntimeError(f'原生字段拒绝写入:{control_id}') + if not read_only: + text = ctypes.create_unicode_buffer(expected) + if not message(0x000C, 0, text): # WM_SETTEXT + raise RuntimeError(f'原生字段拒绝写入:{control_id}') buffer = ctypes.create_unicode_buffer(32768) copied = message(0x000D, len(buffer), buffer) # WM_GETTEXT, remote Edit marshalled by Windows. record['actual'] = buffer.value @@ -745,6 +775,9 @@ def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None): import gc gc.collect() # Release UIA wrappers before closing native child dialogs. if not job.get('_native_add_pending'): + writer = job.pop('_native_add_writer', None) + if writer is not None: + writer.complete() _close_probe_dialogs(desktop, owned_pids) @@ -840,6 +873,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None) if not hwnd or win32gui.GetClassName(hwnd) != 'Edit': raise RuntimeError(f'原生新增字段身份不匹配:{control}') _set_probe_field(hwnd, control, value, root) + # Changing source/top fields can make Mentor derive a different name. + for control, value in fields.items(): + _set_probe_field(win32gui.GetDlgItem(dialog, control), control, value, root, read_only=True) _write_json(root/'submitted-fields.json', fields) ok = win32gui.GetDlgItem(dialog, 1083) if not ok: @@ -851,9 +887,18 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None) _require_add_supervisor(job, root) from .session_record import dispatch_native, update_worker_state def submit_add(): + _require_add_supervisor(job, root) # Registration/journal I/O may have outlived cancellation. job['_native_add_pending'] = True win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0) - dispatch_native(job, submit_add, asynchronous=True, required=True) + from .desktop_worker import register_pending_native_operation + writer = register_pending_native_operation(job, owned_pids) + job['_native_add_writer'] = writer + try: + dispatch_native(job, submit_add, asynchronous=True, required=True) + except Exception: + if not job.get('_native_add_pending'): + writer.complete() + raise success = None while time.monotonic() < deadline: pythoncom.PumpWaitingMessages() @@ -884,6 +929,7 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None) if not success: raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。') job['_native_add_pending'] = False + writer.complete() update_worker_state(job, 'POSTCALL') @@ -1056,6 +1102,8 @@ def _catalog_native(job, root): def _catalog_com(job, root): + if job.get('worker_role') == 'catalog_readonly' and job.get('operation') != 'catalog': + raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH') import pythoncom, win32com.client, win32con, win32gui, win32process from .mentor_adapter import _process_details try: @@ -1089,7 +1137,7 @@ def _catalog_com(job, root): win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None) title = win32gui.GetWindowText(hwnd) text = '\n'.join(win32gui.GetWindowText(child) for child in children) - if catalog_dialog_action(title, text) == 'cancel': + if catalog_dialog_action(title, text, read_only=job.get('worker_role') == 'catalog_readonly') == 'cancel': if hwnd not in observed: observed.append(hwnd) refused.append({'title': title, 'text': text}) @@ -1223,11 +1271,23 @@ def _catalog_com(job, root): return result -def management_worker_main(request_path): +def catalog_worker_main(request_path): + """A catalog-only entry: never allow this read role to select a write branch.""" + job = json.loads(Path(request_path).read_text(encoding='utf-8')) + if job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly': + raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH') + return management_worker_main(request_path, catalog_readonly=True) + + +def management_worker_main(request_path, *, catalog_readonly=False): """Internal worker. Desktop identity and capability gates are rechecked here.""" request_path = Path(request_path) root = request_path.parent job = json.loads(request_path.read_text(encoding='utf-8')) + if job.get('worker_role') == 'catalog_readonly' and not catalog_readonly: + raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH') + if catalog_readonly and (job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly'): + raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH') result = {'success': False, 'safe_to_continue': True} try: _, desktop = _current_desktop() @@ -1285,6 +1345,8 @@ def management_worker_main(request_path): except (FileNotFoundError, PermissionError): result['safe_to_continue'] = True raise + from .desktop_worker import register_native_writer + register_native_writer(process) update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)], continuation=True) try: _write_json(root/'native-process.json', {'pid': process.pid, 'command': command}) diff --git a/src/cbb_refresh_verify/native_repair.py b/src/cbb_refresh_verify/native_repair.py index 3ec1a5f..2504ee8 100644 --- a/src/cbb_refresh_verify/native_repair.py +++ b/src/cbb_refresh_verify/native_repair.py @@ -264,21 +264,44 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr job_path = root/'repair-request.json' cancel = root/'cancel-repair.signal' desktop = 'CbbRepair_'+uuid4().hex[:12] - job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database), + from .operation_queue import current_context + context = current_context() + library = (maintenance_context or {}).get('library') or (context.library if context else str(target.project)) + job = {'project': str(target.project), 'database': str(target.database), 'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds, 'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop, - 'maintenance_context': maintenance_context, 'inspection_only': inspection_only}, - ensure_ascii=False), encoding='utf-8') + 'maintenance_context': maintenance_context, 'inspection_only': inspection_only, + 'library': library, 'operation_id': root.name+'-'+uuid4().hex[:8], + 'operation': 'inspect' if inspection_only else 'repair', + 'block': (maintenance_context or {}).get('block'), + 'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-repair.signal')} + job['start_gate_protocol'] = 'event-v1' + job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8') command = ([sys.executable] if getattr(sys, 'frozen', False) else [sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)] + from .operation_queue import task_stop + return _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress, task_stop(stop), job) + + +def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress, stop, job): + from .desktop_worker import DesktopWorker worker = DesktopWorker(command, desktop) worker.bind_cancellation(cancel) + from .operation_queue import check_active, native_channel, commit_worker_start + native = native_channel(inspection_only=job.get('inspection_only') is True) + entered = False # Worker admission includes filesystem/ownership checks before the native # timeout begins. Bound that preparation separately; never extend on polls. deadline = time.monotonic()+60+max(1, float(timeout_seconds))+5 event_count = 0 cancelled = False try: + if hasattr(worker, 'bind_session'): + worker.bind_session(job) + check_active() + native.__enter__() + entered = True + commit_worker_start(worker, job) while worker.poll() is None and time.monotonic()= timeout_seconds): + cancelled = call.is_set() + call.abandoned = True + raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) + if call.error is not None: + raise call.error + return call.result + + class NativeQueue: def __init__(self): self.condition = Condition() self.pending = [] self.active = False + self.closed = False + self.contexts = {} def wake(self): with self.condition: self.condition.notify_all() - def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None): - ticket = object() + def close(self, *, timeout_seconds=30): + deadline = time.monotonic()+min(30, max(0, timeout_seconds)) + with self.condition: + self.closed = True + contexts = tuple(self.contexts.values()) + for context in contexts: + context.cancel() + self.condition.notify_all() + return tuple(context.close(timeout_seconds=max(0, deadline-time.monotonic())) + for context in contexts) + + def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None, + context=None, timeout_seconds=10): + def available_now(): + if not ready(): + return False + if context is None: + return True # Explicit recovery controls must still reach their retained clients. + from .session_record import _live_library_available + return all(_live_library_available(path) for path in (context.library, *context.aliases)) + ticket = [object(), False] acquired, notified = False, False previous_state = None - with self.condition: self.pending.append((ticket, ready)) + with self.condition: + if self.closed: + raise QueueCancelled('队列已关闭,未启动新的操作。') + if context is not None: + self.contexts[id(context)] = context + self.pending.append(ticket) try: while not acquired: + available = available_now() # Cached predicates only, outside the queue lock. with self.condition: - if stop is not None and stop.is_set(): + if (self.closed or stop is not None and stop.is_set() + or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())): raise QueueCancelled('已取消排队,未启动原生操作。') - first = next((token for token, available in self.pending if available()), None) + ticket[1] = bool(available) + first = next((entry for entry in self.pending if entry[1]), None) if not self.active and first is ticket: - self.pending = [entry for entry in self.pending if entry[0] is not ticket] self.active = acquired = True else: self.condition.wait(.1) + if acquired and not available_now(): + with self.condition: + ticket[1] = self.active = acquired = False + self.condition.notify_all() if not acquired and waiting is not None: try: current_state = wait_state() if wait_state is not None else None @@ -39,11 +451,12 @@ class NativeQueue: notified, previous_state = True, current_state except Exception: pass - if stop is not None and stop.is_set(): + if (stop is not None and stop.is_set() + or context is not None and context.stop_after_current.is_set()): raise QueueCancelled('已取消排队,未启动原生操作。') - return action() + return context.run(action, stop=stop, timeout_seconds=timeout_seconds) if context else action() finally: with self.condition: - self.pending = [entry for entry in self.pending if entry[0] is not ticket] + self.pending = [entry for entry in self.pending if entry is not ticket] if acquired: self.active = False self.condition.notify_all() diff --git a/src/cbb_refresh_verify/pcb_open_consent.py b/src/cbb_refresh_verify/pcb_open_consent.py index 83477bc..11d76f1 100644 --- a/src/cbb_refresh_verify/pcb_open_consent.py +++ b/src/cbb_refresh_verify/pcb_open_consent.py @@ -18,14 +18,16 @@ class OpenChoice: def __init__(self, block, library): self.block, self.library = block, library self.decision = None + self.decision_origin = None self._lock = Lock() - def choose(self, decision): + def choose(self, decision, *, origin='user'): if decision not in ('continue', 'skip', 'cancel'): raise ValueError('无效的打开工程选择') with self._lock: if self.decision is None: self.decision = decision + self.decision_origin = origin def validate_owner(job, target_pid, launcher_pid, worker_pid): @@ -46,8 +48,14 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid): @contextmanager def resource_guard(job, allowed_pids): - import win32con, win32file - from .icdb_ownership import database_directories, unreleased_addresses + import hashlib + from .file_probe import hold_release_files + from .maintenance_entry import maintenance_project_files + from .native_repair import RepairTarget, run_native_repair + from .native_occupancy import confirmed_inspection + from .session_record import IDENTITY_KEYS + from .operation_queue import task_stop + from .management import _write_json from .owner_probe import query_process_snapshot from .library_lock import _owner_is_blocking from .verify_runner import preflight, VerifyRequest @@ -56,21 +64,48 @@ def resource_guard(job, allowed_pids): if project.resolve() != Path(job['project']).resolve() or pcb.resolve() != Path(job['pcb']).resolve(): raise ValueError('PCB_OPEN_PROJECT_CHANGED') roots = (project.parent, library.parent/'SymbolLibs') + configs = maintenance_project_files(project, pcb) + def binding(): + return {str(path.resolve()): hashlib.sha256(path.read_bytes()).hexdigest() for path in (pcb, *configs)} + original_binding = binding() def check(): - if unreleased_addresses(library, project, pcb): - raise ValueError('目标仍有数据库地址记录,暂不能确认读写打开。') for row in query_process_snapshot(): if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots): raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。') check() - paths = [library, pcb.parent/'Layout/LayoutDB.lyt', - *(d/'icdb.dat' for d in database_directories(library, project, pcb) if (d/'icdb.dat').is_file())] + stop = task_stop(None) with ExitStack() as stack: - for path in dict.fromkeys(paths): - handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None, - win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) - stack.callback(handle.Close) + files = stack.enter_context(hold_release_files(library, roots, stop=stop)) + inspections = [] + if files['addresses']: + targets = files['inspection_targets'] + if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets): + raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对') + stack.close() # Native inspection must access the DB; repeat exact proof afterwards. + for index, item in enumerate(targets): + target = RepairTarget(Path(item['project']), Path(item['database'])) + evidence = Path(job['root'])/('open-inspection-'+str(index)) + result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'), + timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop) + identity = result.get('native_identity') or {} + if (not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE' + or identity.get('pid') != result.get('native_pid') + or any(identity.get(key) is None for key in IDENTITY_KEYS) + or not identity.get('image') or not identity.get('owner_sid')): + raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查未确认当前数据库未占用') + inspections.append(result) + current = stack.enter_context(hold_release_files(library, roots, stop=stop)) + if any(current[key] != files[key] for key in ( + 'exclusive_files', 'binding_files', 'addresses', 'signatures', 'inspection_targets', 'resource_scope')): + raise ValueError('PCB_OPEN_RESOURCE_CHANGED: 原生检查期间资源或地址身份变化') + if binding() != original_binding: + raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化') check() + _write_json(Path(job['root'])/'pcb-open-resource-proof.json', { + 'operation_id': job.get('operation_id'), 'library': str(library), + 'project': str(project), 'pcb': str(pcb), 'binding': original_binding, + 'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'], + 'native_inspections': inspections, 'repair_confirmed': False}) yield @@ -106,9 +141,11 @@ class OpenController: action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'], 'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid, 'owner': owner, 'choice': self.choice.decision} + action['decision_origin'] = self.choice.decision_origin def send(): _write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict( - choice=self.choice.decision, project=self.job['project'], pcb=self.job['pcb'], + choice=self.choice.decision, decision_origin=self.choice.decision_origin, + project=self.job['project'], pcb=self.job['pcb'], library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record())) self.sent, self.sent_at = True, time.monotonic() return perform(snapshot, action, snapshot.phase) @@ -128,8 +165,10 @@ class OpenController: error = 'PCB_OPEN_ANSWER_FAILED' if not error and control == 7: error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED' + skipped_detail = ('超时默认跳过本项。' if self.choice.decision_origin == 'timeout_default' + else '用户跳过本项。') return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot, - error_code=error, detail=result.detail or ('用户跳过本项。' if control == 7 else ''), + error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''), accepted_controls=result.accepted_controls, channel=result.channel, action=action['action'], observed_snapshots=tuple(snapshots)) except Exception as error: diff --git a/src/cbb_refresh_verify/pcb_restore_prompt.py b/src/cbb_refresh_verify/pcb_restore_prompt.py index 00844f6..ea8ce17 100644 --- a/src/cbb_refresh_verify/pcb_restore_prompt.py +++ b/src/cbb_refresh_verify/pcb_restore_prompt.py @@ -13,14 +13,16 @@ class RestoreChoice: self.block, self.library = block, library self.candidates = tuple(dict(c) for c in candidates) self.decision = None + self.decision_origin = None self._lock = Lock() - def choose(self, kind): + def choose(self, kind, *, origin='user'): if kind != 'cancel' and not any(c['kind'] == kind and c['enabled'] for c in self.candidates): raise ValueError('Unknown or disabled PCB restoration version') with self._lock: if self.decision is None: self.decision = kind + self.decision_origin = origin def _candidate_key(candidates): @@ -82,7 +84,11 @@ class RestoreController: if self.prompt.decision is None: return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots)) if self.prompt.decision == 'cancel': - raise ValueError('用户取消 PCB 版本选择;未确认恢复,保留原生现场。') + _write_json(Path(self.job['root'])/'pcb-version-user-choice.json', dict( + project=self.job['project'], pcb=self.job['pcb'], choice='cancel', + decision_origin=self.prompt.decision_origin, snapshot=snapshot.to_record())) + reason = '超时默认取消' if self.prompt.decision_origin == 'timeout_default' else '用户取消' + raise ValueError(reason+' PCB 版本选择;未确认恢复,保留原生现场。') selected = next(c for c in choice['candidates'] if c['kind'] == self.prompt.decision) if not selected['enabled']: raise ValueError('PCB_VERSION_DISABLED') @@ -99,12 +105,14 @@ class RestoreController: action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'], 'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid, 'choice': selected['kind'], 'candidates': list(self.prompt.candidates)} + action['decision_origin'] = self.prompt.decision_origin if self.owner is not None: action['owner'] = self.owner self.selection_sent = True self.confirm_sent = confirming self.sent_at = time.monotonic() record = {'project': self.job['project'], 'pcb': self.job['pcb'], 'choice': selected['kind'], + 'decision_origin': self.prompt.decision_origin, 'date': selected['date'], 'historical_restore': True, 'confirm_sent': confirming, 'snapshot': snapshot.to_record()} _write_json(Path(self.job['root'])/'pcb-version-user-choice.json', record) diff --git a/src/cbb_refresh_verify/residual_sessions.py b/src/cbb_refresh_verify/residual_sessions.py index 5bfc561..ad54e07 100644 --- a/src/cbb_refresh_verify/residual_sessions.py +++ b/src/cbb_refresh_verify/residual_sessions.py @@ -252,7 +252,7 @@ def _post_window_message(window, hwnd, pid, message): win32gui.PostMessage(hwnd, message, 0, 0) -def _process_windows(pids): +def _process_windows(pids, *, include_hidden_documents=False): result = _WindowSnapshot(pids) if not pids: return result import win32api, win32con, win32gui, win32process @@ -271,10 +271,13 @@ def _process_windows(pids): kind = win32gui.GetClassName(handle) if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD): documents.append(handle) - if win32gui.IsWindowVisible(handle): + visible = bool(win32gui.IsWindowVisible(handle)) + if visible or (include_hidden_documents and kind.casefold().startswith('afx:') + and win32gui.GetClassName(win32gui.GetParent(handle)) == 'MDIClient'): children.append({'hwnd': int(handle), 'class': kind, 'id': win32gui.GetDlgCtrlID(handle) & 0xffff, - 'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle))}) + 'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle)), + 'visible': visible}) win32api.SetLastError(0) win32gui.EnumChildWindows(hwnd, child, None) window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd), @@ -482,6 +485,339 @@ def inspect_residual_sessions(library, *, block_names=()): 'previous_records': previous} +def _hidden_tip_owner(tip, pid): + """Read only the Tip's direct hidden frame, never arbitrary hidden windows.""" + import win32api, win32con, win32gui, win32process + with _window_desktop(tip['desktop']) as desktop: + hwnd = win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) + if (not hwnd or hwnd not in _desktop_windows(desktop) + or win32process.GetWindowThreadProcessId(hwnd)[1] != pid + or win32gui.IsWindowVisible(hwnd) or win32gui.IsWindowEnabled(hwnd)): + return None + kind, title = win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd) + if not kind.startswith('Afx:') or title.strip() not in ( + 'Expedition PCB', 'Expedition PCB - Reusable Block'): + return None + children, documents = [], [] + def child(control, _): + control_class = win32gui.GetClassName(control) + if control_class.casefold() == 'msctls_progress32': + children.append({'class': control_class}) + if control_class == 'MDIClient' and win32gui.GetWindow(control, win32con.GW_CHILD): + documents.append(control) + win32api.SetLastError(0) + win32gui.EnumChildWindows(hwnd, child, None) + return dict(hwnd=hwnd, title=title, **{'class': kind}, desktop=tip['desktop'], + enabled=False, children=children, documents=documents) + + +def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=(), deadline=None, stop=None): + """A non-writing startup Tip may finish an already pending normal close.""" + import win32con, win32event, win32gui + from .failed_session import _startup_snapshot, _tip_target + if (incomplete or row.get('scope_confirmed') is not True + or row.get('name', '').casefold() != 'expeditionpcb.exe' + or row.get('runtime_phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED') + or native_activity(row['name'], windows)['status'] != 'IDLE'): + return None + desktops = {w.get('desktop', '') for w in windows} + if len(desktops) != 1 or not next(iter(desktops), '').startswith('CbbVerify_'): + return None + tips = [w for w in windows if w['class'] == '#32770' and w['title'] == 'Tip of the Day'] + if len(tips) != 1 or tips[0]['hwnd'] in dismissed: + return None + tip = tips[0] + hidden_owner = None + if not any(w['class'].startswith('Afx:') for w in windows): + hidden_owner = _hidden_tip_owner(tip, row['pid']) + # A disabled empty frame is expected behind a modal Tip. No document, + # progress, other dialog, or arbitrary disabled application is admitted. + rest = [dict(w, enabled=True) if w['class'].startswith('Afx:') else w + for w in windows if w is not tip] + if hidden_owner is not None: + rest.append(dict(hidden_owner, enabled=True)) + main, _ = close_target(row['name'], rest) + if (main is None or main.get('documents') + or row.get('startup_frame', main['hwnd']) != main['hwnd'] + or main['title'].strip() not in ( + 'Expedition PCB', 'Expedition PCB - Reusable Block')): + return None + buttons = [c for c in tip['children'] if c['class'] == 'Button' and c.get('id') == 1 + and c.get('enabled')] + if len(buttons) != 1 or not tip['enabled']: + return None + if row.get('library'): + from .session_record import active_write_records + if active_write_records(row['library']): + return None + with _window_desktop(tip['desktop'], write=True): + if win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd']: + return None + current = _startup_snapshot(tip['hwnd'], row['pid']) + target = _tip_target(current) + if (target is None or target.handle != buttons[0]['hwnd'] + or current.title != tip['title'] or current.window_class != tip['class']): + return None + fresh = _process_windows({row['pid']}) + if (_window_error(fresh, row['pid']) or fresh.get(row['pid']) != windows + or win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_TIMEOUT + or _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')} + or win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd'] + or hidden_owner is not None and _hidden_tip_owner(tip, row['pid']) != hidden_owner + or _startup_snapshot(tip['hwnd'], row['pid']) != current): + return None + if (deadline is not None and time.monotonic() >= deadline + or stop is not None and stop.is_set()): + return None + _post_window_message(tip, target.handle, row['pid'], win32con.BM_CLICK) + return tip['hwnd'] + + +def _cancelled_diagnostic_record(row): + """Existing complete registration can authorize cleanup, never validation.""" + import stat + import pywintypes, win32con, win32event + from .session_record import _session, IDENTITY_KEYS, active_write_records + from .failed_session import _command_args + if row.get('scope_confirmed') is not True or row.get('name', '').casefold() != 'expeditionpcb.exe': + return None + def same(a, b): + return os.path.normcase(os.path.abspath(str(a))) == os.path.normcase(os.path.abspath(str(b))) + def read(path, *, lines=False): + if path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT: + raise ValueError('STARTUP_RECORD_REPARSE_POINT') + with path.open('rb') as stream: + data = stream.read(1024*1024+1) + if len(data) > 1024*1024: + raise ValueError('STARTUP_RECORD_TOO_LARGE') + return [json.loads(line) for line in data.splitlines()] if lines else json.loads(data) + matches = [] + for record in row.get('session_records', ()): + try: + path = Path(record['path']); root = path.parent + session, state, identities = _session(path, root) + job, result = read(root/'request.json'), read(root/'result.json') + operation = session['operation_id'] + scope = session.get('resource_scope', {}) + if (record.get('operation_id') != operation or job.get('operation_id') != operation + or job.get('diagnostic_only') not in (True,False) or job.get('interactive_input') is not False + or job.get('operation') != 'verify' or session.get('operation') != 'verify' + or not all(same(value, row['library']) for value in (job['library'], job['lmc_file'], session['library'])) + or not same(job['root'], root) or not same(job['session_record_path'], path) + or job.get('desktop') != session.get('desktop') or not job['desktop'].startswith('CbbVerify_') + or scope.get('scope_state') != 'DECLARED' or scope.get('operation_id') != operation + or not same(scope.get('library', ''), row['library']) + or scope.get('projects') != [job['project']] + or not Path(job['pcb']).is_relative_to(Path(job['project']).parent) + or not same(job['cancel_signal'], session['cancel_signal']) + or Path(job['cancel_signal']).parent != root or not Path(job['cancel_signal']).is_file() + or result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING' + or result.get('write_outcome', {}).get('save_state') != 'UNKNOWN' + or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()): + continue + native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']] + workers = [p for p in identities if p.get('role') in ('worker', 'helper')] + if (len(native) != 1 or not workers + or any(native[0][k] != row.get(k) for k in IDENTITY_KEYS) + or any(p.get('role') not in ('worker','helper','native','supervisor') for p in identities)): + continue + for worker in workers: + try: + with _process_handle(worker['pid']) as held: + if win32event.WaitForSingleObject(held, 0) != win32con.WAIT_OBJECT_0: + raise ValueError('STARTUP_WORKER_STILL_ACTIVE') + except (OSError, pywintypes.error) as error: + if getattr(error, 'winerror', None) != 87: + raise + args = _command_args(row['command']) + if ('-reusablecircuit' not in [a.casefold() for a in args] + or not any(same(a, job['pcb']) for a in args[1:])): + continue + events = read(root/'events.jsonl', lines=True) + if (not any(e.get('stage') == 'pcb_worker_started' and e.get('pcb_pid') == row['pid'] for e in events) + or not any(e.get('stage') == 'pcb_baseline' and row['pid'] not in e.get('pids', []) for e in events) + or any(str(e.get('stage', '')).startswith(('save', 'integration', 'validate', 'failure_close')) + or e.get('stage') == 'diagnostic_complete' for e in events)): + continue + closes = [e for e in events if e.get('stage') in ('startup_close_requested', 'diagnostic_wm_close')] + if len(closes) > 1 or any(e.get('pcb_pid') != row['pid'] or not e.get('hwnd') for e in closes): + continue + if any(r.get('operation_id') != operation for r in active_write_records(row['library'])): + continue + if job.get('diagnostic_only') is False: + from .failed_session import cancelled_prewrite_startup + from .diagnostic_open import _load_evidence + baseline=cancelled_prewrite_startup(job,row['pid']) + if baseline is None or _load_evidence(job,row['pid'],baseline,require_autosave=False) is None: + continue + matches.append(dict(job=job, record_path=str(path), operation_id=operation, + closed_frame=closes[0]['hwnd'] if closes else None, + declined_buttons=[e['hwnd'] for e in events if e.get('stage')=='startup_prompt_no' + and e.get('pcb_pid')==row['pid'] and e.get('control_id')==7 and e.get('hwnd')], + dismissed_tips=[e['hwnd'] for e in events if e.get('stage')=='startup_tip_dismissed' + and e.get('pcb_pid')==row['pid'] and e.get('hwnd')])) + except (OSError, pywintypes.error, ValueError, KeyError, TypeError): + continue + return matches[0] if len(matches) == 1 else None + + +def _legacy_diagnostic_windows(row): + """Adapt the existing complete private-desktop snapshot for diagnostic policy.""" + import win32con, win32gui + snapshot = _process_windows({row['pid']}, include_hidden_documents=True) + if _window_error(snapshot, row['pid']): + raise ValueError('STARTUP_WINDOW_UNCONFIRMED') + result = [] + for window in snapshot.get(row['pid'], []): + if window.get('desktop') != row['cleanup_desktop']: + raise ValueError('STARTUP_DESKTOP_UNCONFIRMED') + benign = (not window['title'] and window['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')) + benign = benign or (window['class'] == 'Internet Explorer_Hidden' and not window['title'] + and not window['children'] and window.get('rect', [1,1,2,2])[:2] == window.get('rect', [1,1,2,2])[2:]) + if benign: + continue + with _window_desktop(window['desktop']): + children = [dict(c, parent=win32gui.GetParent(c['hwnd'])) for c in window['children']] + result.append(dict(hwnd=window['hwnd'], pid=row['pid'], **{'class':window['class']}, + text=window['title'], enabled=window['enabled'], children=children, + owner=int(win32gui.GetWindow(window['hwnd'], win32con.GW_OWNER) or 0))) + return result + + +def _close_registered_startup(row, handle, proof, *, stop=None, deadline=None): + import pywintypes, win32con, win32event + from .diagnostic_open import cancelled_startup_step + from .operation_queue import check_active + job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop']) + if deadline is None:deadline = time.monotonic()+30 + def active_owner(): + check_active() + if stop is not None and stop.is_set(): + return False + owner = _force_ownership(handle,row['pid']) + return (owner.get('force_user_confirmed') is True + and win32event.WaitForSingleObject(handle,0) == win32con.WAIT_TIMEOUT + and _handle_identity(handle) == {k:row.get(k) for k in ('created_handle','image')} + and all(owner.get(k) == row.get(k) for k in ('owner_sid','session_id'))) + def confirmed(): + if not active_owner():return False + fresh = next((p for p in query_process_snapshot() if p['pid'] == row['pid']), None) + return (fresh is not None and all(fresh.get(k) == row.get(k) for k in ('created','command','executable','name')) + and _cancelled_diagnostic_record(row) == proof) + def post(hwnd, message): + if not active_owner() or time.monotonic() >= deadline: + raise ValueError('STARTUP_ACTION_UNCONFIRMED') + _post_window_message({'desktop':job['desktop']}, hwnd, row['pid'], message) + state = {'clicked':set()}; closed = proof['closed_frame']; dismissed_tips = set(proof.get('dismissed_tips',())) + def read_bound_windows(): + windows=_legacy_diagnostic_windows(bound) + for window in windows: + if any(c['hwnd'] in proof.get('declined_buttons',()) for c in window['children']): + state['clicked'].add(window['hwnd']) + return windows + try: + while time.monotonic() < deadline: + if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0: + return {'release_status':'RELEASED','detail':'已正常结束已取消的诊断启动'} + if not active_owner(): + break + snapshot = _process_windows({row['pid']}) + # Only this fully proved no-write operation may bypass its historical + # UNCONFIRMED label; other operations were vetoed by the proof above. + tip_row = {k:v for k,v in row.items() if k not in ('runtime_phase','library')} + if closed is not None: + tip_row['startup_frame'] = closed + has_tip = any(w['title'] == 'Tip of the Day' for w in snapshot.get(row['pid'],[])) + tip = (_dismiss_startup_tip(tip_row,handle,snapshot.get(row['pid'],[]), + incomplete=_window_error(snapshot,row['pid']),dismissed=dismissed_tips,deadline=deadline,stop=stop) + if has_tip and confirmed() else None) + if tip is not None: + dismissed_tips.add(tip) + if closed is None: + continue # Tip may precede loading; the same intent still owns its one Close. + while time.monotonic() < deadline: + if win32event.WaitForSingleObject(handle,100) == win32con.WAIT_OBJECT_0: + return {'release_status':'RELEASED','detail':'已关闭启动提示并正常退出'} + if stop is not None and stop.is_set():break + break # Never stack another Close after a legacy Tip acknowledgement. + try: + closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline, + post=post,emit=lambda **event:None,read_windows=read_bound_windows, + identity_check=confirmed) + except RuntimeError as error: + if not str(error).startswith('STARTUP_WINDOW_CHANGED:'): + raise + # No may remove a modal and enable the target while the next + # snapshot is being read. Revalidate anew inside the same budget. + time.sleep(.1) + except (OSError, pywintypes.error, ValueError, RuntimeError) as error: + return {'release_status':'WAITING','detail':str(error)} + return {'release_status':'WAITING','detail':'已请求取消启动清理,等待原生退出后重新检查'} + + +def _ordinary_startup_close(row, handle, proof, *, stop=None): + """One persisted retained phase, serialized with existing explicit release.""" + import win32con, win32event + from .session_record import read_session_record, write_session_record + from .operation_queue import native_phase + waiting = {'release_status':'WAITING','detail':'取消启动清理已交接或原生执行通道忙,继续观察'} + mutex=win32event.CreateMutex(None,False,r'Local\CbbRefreshVerify795') + acquired=False + try: + acquired=win32event.WaitForSingleObject(mutex,0) in (win32con.WAIT_OBJECT_0,win32con.WAIT_ABANDONED) + if not acquired or stop is not None and stop.is_set():return waiting + path=Path(proof['record_path']) + record=read_session_record(path,evidence_root=path.parent) + if 'retained_startup_cleanup' in record or _cancelled_diagnostic_record(row)!=proof:return waiting + # Complete loaded identity and every prompt are checked before consuming + # the one-shot intent. Unknown/multiple documents remain observation-only. + from .diagnostic_open import _target_frame, _pending_prompt + windows=_legacy_diagnostic_windows(dict(row,cleanup_desktop=proof['job']['desktop'])) + frame=_target_frame(windows,Path(proof['job']['pcb']).stem,require_ready=False) + if frame is None:return waiting + for window in windows: + _pending_prompt([window],closing=proof['closed_frame'] is not None,frame=frame, + pcb_name=Path(proof['job']['pcb']).name) + if _cancelled_diagnostic_record(row)!=proof or stop is not None and stop.is_set():return waiting + deadline=time.monotonic()+30 + record['retained_startup_cleanup']=dict(operation_id=proof['operation_id'], + pcb_pid=row['pid'],owner_pid=os.getpid(),state='CLAIMED',closed_frame=proof['closed_frame'], + deadline_monotonic=deadline,identity={k:row[k] for k in ('created_handle','image','owner_sid','session_id')}) + write_session_record(path,record) # Durable before No/Close; never removed or retried. + with native_phase(read_only=True): + return _close_registered_startup(row,handle,proof,stop=stop,deadline=deadline) + except (OSError,ValueError,RuntimeError): + return waiting + finally: + if acquired:win32event.ReleaseMutex(mutex) + mutex.Close() + + +def resume_cancelled_startup(path, *, stop=None): + """Observer-only entry for one late loaded, positively proved ordinary cancel.""" + from .session_record import _session + from .failed_session import cancelled_prewrite_startup + path=Path(path) + try: + session,state,identities=_session(path,path.parent) + if 'retained_startup_cleanup' in session or stop is not None and stop.is_set():return False + job=json.loads(path.with_name('request.json').read_text(encoding='utf-8')) + if job.get('diagnostic_only') is not False:return False + native=[p for p in identities if p.get('role')=='native' + and Path(p['image']).name.casefold()=='expeditionpcb.exe'] + if len(native)!=1 or cancelled_prewrite_startup(job,native[0]['pid']) is None:return False + plan=inspect_residual_sessions(session['library'],block_names=(session['block'],)) + rows=[r for r in plan['sessions'] if r['pid']==native[0]['pid']] + if len(rows)!=1:return False + row=dict(rows[0],session_records=[dict(path=str(path),operation_id=session['operation_id'])]) + proof=_cancelled_diagnostic_record(row) + if proof is None:return False # Includes exact worker/helper exit and fresh loaded logs. + _request_close(row,stop=stop) + return True + except (OSError,ValueError,KeyError,TypeError,RuntimeError): + return False + + def _request_close(row, *, stop=None): import win32con, win32event with _process_handle(row['pid']) as handle: @@ -494,6 +830,35 @@ def _request_close(row, *, stop=None): windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid']) if error: return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error} + if stop is not None and stop.is_set(): + return {'release_status': 'CANCELLED', 'detail': '已停止释放'} + if proof := _cancelled_diagnostic_record(row): + owner = _force_ownership(handle,row['pid']) + if (owner.get('force_user_confirmed') is not True + or any(owner.get(k) != row.get(k) for k in ('owner_sid','session_id'))): + return {'release_status':'WAITING','detail':'取消启动会话的用户或 Windows 会话未确认'} + if stop is not None and stop.is_set(): + return {'release_status':'CANCELLED','detail':'已停止释放'} + from .session_record import handoff_session + record_path = Path(proof['record_path']) + handoff_session(record_path, evidence_root=record_path.parent, observe_only=False) + if proof['job'].get('diagnostic_only') is False: + return _ordinary_startup_close(row,handle,proof,stop=stop) + from .operation_queue import native_phase + # This confirmed no-write native cleanup has its own single bounded + # budget; metadata inactivity must not abandon it between No and Close. + with native_phase(read_only=True): + return _close_registered_startup(row, handle, proof, stop=stop) + if _dismiss_startup_tip(row, handle, windows, stop=stop) is not None: + # Legacy startup cleanup may already have sent WM_CLOSE. Only wait + # for it here; never stack another close behind this acknowledgement. + deadline = time.monotonic()+3 + while time.monotonic() < deadline: + if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0: + return {'release_status': 'RELEASED', 'detail': '已关闭启动提示并正常退出'} + if stop is not None and stop.is_set(): + return {'release_status': 'CANCELLED', 'detail': '已停止释放'} + return {'release_status': 'WAITING', 'detail': '已关闭启动提示,等待原生退出后重新检查'} if row['name'].casefold() == 'expeditionpcb.exe': from .failed_session import _startup_snapshot, _cancel_target for window in windows: @@ -560,9 +925,11 @@ def _force_close(row, *, stop=None): 'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'} -def _finish_library_release(library, evidence): +def _finish_library_release(library, evidence, block_names=(), stop=None): from .library_lock import release_retained_library - return release_retained_library(library, evidence) + return release_retained_library(library, evidence, + block_name=block_names[0] if len(block_names) == 1 else None, + block_names=block_names, stop=stop) def _request_native_cancel(row, *, stop=None): @@ -622,6 +989,7 @@ def release_targets_complete(rows): def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False): + from .operation_queue import note_metadata_progress library = Path(plan['library']).resolve() root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12]) if root.is_relative_to(library.parent) or library.parent.is_relative_to(root): @@ -661,6 +1029,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca result['consent_path'] = str(consent_path) try: fresh = {r['pid']: r for r in query_process_snapshot()} + note_metadata_progress() blocks = plan.get('block_names', ()) roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks) + (library.parent/'SymbolLibs',)) if blocks else (library.parent,) @@ -691,6 +1060,9 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca if not save(): return result try: + if not force and not cancel_native: + row['session_records'] = [{k:r.get(k) for k in ('path','operation_id')} + for r in plan.get('runtime_sessions', []) if r.get('path')] outcome = (_request_native_cancel(row, stop=stop) if cancel_native else (_force_close if force else _request_close)(row, stop=stop)) except Exception as error: @@ -698,7 +1070,9 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca row.update(outcome) if not save(): return result # Preserve completed facts; stop further actions on storage failure. + note_metadata_progress() after = {r['pid']: r for r in query_process_snapshot()} + note_metadata_progress() remaining_windows = _process_windows({r['pid'] for r in result['sessions'] if r['release_status'] == 'WAITING' and r['pid'] in after}) for row in result['sessions']: @@ -713,7 +1087,8 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca if row.get('force_user_confirmed') is True else None), native_activity=native_activity(row['name'], windows, incomplete=error)) if release_targets_complete(result['sessions']) and not (stop and stop.is_set()): - result['proof'] = _finish_library_release(library, root/'library-proof') + result['proof'] = _finish_library_release(library, root/'library-proof', + blocks, stop) proof = result['proof'] if (proof.get('status') != 'RELEASE_CONFIRMED' or Path(proof.get('library', '')).resolve() != library): diff --git a/src/cbb_refresh_verify/scoped_manifest.py b/src/cbb_refresh_verify/scoped_manifest.py index 9df40c9..3988dda 100644 --- a/src/cbb_refresh_verify/scoped_manifest.py +++ b/src/cbb_refresh_verify/scoped_manifest.py @@ -4,7 +4,6 @@ Unknown engineering files are primary. Only explicit runtime, history and generated categories are ignored by semantic comparisons; they are still copied and their membership/size/mtime must remain stable throughout the snapshot. """ -from concurrent.futures import ThreadPoolExecutor from contextlib import ExitStack from dataclasses import asdict, dataclass import hashlib @@ -12,6 +11,7 @@ import os from pathlib import Path import shutil import stat +from .operation_queue import note_metadata_progress MANIFEST_VERSION = 1 @@ -207,6 +207,7 @@ def scan_tree(root, *, scope=None, exclude=None, check=None): if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)): raise ValueError(f'不支持的特殊文件:{entry.path}') entries[path] = metadata + note_metadata_progress() if stat.S_ISDIR(metadata.st_mode): folders.append(path) return dict(sorted(entries.items())) @@ -250,12 +251,13 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi files = {} hashed_bytes = 0 _emit(progress, 'hash', 0, 0, total_files=len(selected)) - with ThreadPoolExecutor(max_workers=8) as pool: - for count, (relative, item) in enumerate(pool.map(hashed, selected), 1): - files[relative] = item - hashed_bytes += item['size'] - if count % 256 == 0 or count == len(selected): - _emit(progress, 'hash', count, hashed_bytes, total_files=len(selected)) + # Stay on the bounded task thread: executor workers are joined at interpreter exit. + for count, (relative, item) in enumerate(map(hashed, selected), 1): + note_metadata_progress() + files[relative] = item + hashed_bytes += item['size'] + if count % 256 == 0 or count == len(selected): + _emit(progress, 'hash', count, hashed_bytes, total_files=len(selected)) # Check primary membership and metadata again after every hash completed. # Runtime files can change/add/disappear without a semantic conflict. after = scan_tree(root, scope=scope, exclude=exclude) @@ -285,6 +287,7 @@ def build_exclusive_library_manifest(root, *, scope, progress=None): raise OSError(f'LIBRARY_DATABASE_IN_USE: 无法独占读取 {path}:{error}') from error handles[path] = handle stack.callback(handle.Close) + note_metadata_progress() def digest(path): if path not in handles: @@ -328,7 +331,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi destination.mkdir(parents=True, exist_ok=False) files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)] from .library_lock import owned_snapshot - # Resolve ownership on the operation thread, before parallel copy workers. + # Resolve ownership on the operation thread before copying. owned = {path: data for path in files if path.name.endswith('.cbb-upload.lock') and (data := owned_snapshot(path)) is not None} @@ -386,16 +389,16 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi raise OSError(f'复制期间文件变化:{path}') return relative.as_posix(), digest, label - with ThreadPoolExecutor(max_workers=8) as pool: - for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1): - if label is not None: - size = entries[source/relative].st_size - record[relative] = {'size': size, 'sha256': digest, 'scope': label} - hashed_count += 1 - hashed_bytes += size - if count % 256 == 0 or count == len(files): - _emit(progress, 'copy', hashed_count, hashed_bytes, - copied_files=count, total_files=len(files)) + for count, (relative, digest, label) in enumerate(map(copy_file, files), 1): + note_metadata_progress() + if label is not None: + size = entries[source/relative].st_size + record[relative] = {'size': size, 'sha256': digest, 'scope': label} + hashed_count += 1 + hashed_bytes += size + if count % 256 == 0 or count == len(files): + _emit(progress, 'copy', hashed_count, hashed_bytes, + copied_files=count, total_files=len(files)) def validate_bytes(relative): item = record[relative] @@ -404,8 +407,9 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi raise OSError(f'复制期间主要文件内容变化:{path}') if hash_function(destination/relative) != item['sha256']: raise OSError(f'复制内容校验失败:{path}') - with ThreadPoolExecutor(max_workers=8) as pool: - list(pool.map(validate_bytes, record)) + for relative in record: + validate_bytes(relative) + note_metadata_progress() if _metadata_record(source, scan_tree(source)) != expected_metadata: raise OSError(f'复制期间目录内容变化:{source}') if _metadata_record(destination, scan_tree(destination)) != expected_metadata: diff --git a/src/cbb_refresh_verify/session_record.py b/src/cbb_refresh_verify/session_record.py index f970a1a..68ba480 100644 --- a/src/cbb_refresh_verify/session_record.py +++ b/src/cbb_refresh_verify/session_record.py @@ -1,4 +1,4 @@ -"""Bounded, observation-only journal for native calls that outlive a task.""" +"""Bounded registration and observation for native calls that outlive a task.""" from contextlib import ExitStack from datetime import datetime, timezone import json @@ -22,13 +22,30 @@ def _library_key(library): return os.path.normcase(os.path.normpath(str(library))) -def library_available(library): +def library_available(library, *, live_only=False): """Cached queue predicate: no file, process or network queries.""" + if live_only: + return _live_library_available(library) key = _library_key(library) with _observer_guard: return not any(key in aliases for aliases in _retained_libraries.values()) +def _live_library_available(library): + """Ignore stale retention, but wait for an actual registered observer.""" + key = _library_key(library) + with _observer_guard: + for path, aliases in _retained_libraries.items(): + observer = _observers.get(path) + if key not in aliases or observer is None or not observer[0].is_alive(): + continue + state = _retained_results.get(path, {}) + if (state.get('observer_initializing') is True or state.get('status') == 'ACTIVE' + or state.get('owned_worker_alive') is True): + return False + return True + + def retained_session_snapshot(library): key = _library_key(library) with _observer_guard: @@ -67,6 +84,25 @@ def acknowledge_library_release(proof, snapshot, *, block_name=None): _retained_results.pop(path, None) +def _proof_covers_session(proof, session): + """A receipt may acknowledge only resources actually covered by its proof.""" + scope = proof.get('resource_scope') + library = session.get('library') + if (proof.get('status') != 'RELEASE_CONFIRMED' or proof.get('lease_state') != 'RELEASED' + or not isinstance(scope, dict) or scope.get('scope_state') != 'OBSERVED' + or not library or _library_key(proof.get('library', '')) != _library_key(library) + or _library_key(scope.get('library', '')) != _library_key(library)): + return False + if proof.get('proof_scope') == 'LIBRARY': + return not scope.get('block_names') and not proof.get('proof_block_names') + blocks = proof.get('proof_block_names') + observed = scope.get('block_names') + if (proof.get('proof_scope') not in ('BLOCK', 'BLOCKS') or not isinstance(blocks, list) + or not blocks or not isinstance(observed, list) or blocks != observed): + return False + return bool(session.get('block') and session['block'] in blocks) + + def record_session_release(proof, records): """Persist a past proof only for the pre-proof operation, never replay it.""" errors = [] @@ -78,7 +114,8 @@ def record_session_release(proof, records): path = Path(record['path']) session = read_session_record(path, evidence_root=path.parent) if (session['operation_id'] != record.get('operation_id') - or Path(session['library']).resolve() != library): + or Path(session['library']).resolve() != library + or not _proof_covers_session(proof, session)): continue write_session_record(path.with_name('observation-release-'+uuid4().hex+'.json'), { 'operation_id': session['operation_id'], 'library': str(library), @@ -108,14 +145,47 @@ def library_wait_reason(library): def register_worker_session(worker, job): """The launcher must persist identity before opening the worker's gate.""" path = Path(job['session_record_path']) - write_session_record(path, {k: job.get(k) for k in ( - 'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal')} - | {'processes': [{'role': 'worker', **process_identity(worker.pid)}]}) + from .operation_queue import check_worker_admission, current_context, bind_supervised_worker + check_worker_admission(job) + context = current_context() + protection = ('duplicated_lease' if job.get('worker_lease_handle') else + 'worker_owned_lease' if job.get('operation') == 'native_backup' else + 'inspection_only' if job.get('inspection_only') is True else + 'catalog_readonly' if job.get('worker_role') == 'catalog_readonly' + and job.get('operation') == 'catalog' else None) + if context is not None and context.native_policy == 'external': + if protection is None or worker.pid == os.getpid(): + raise RuntimeError('WORKER_OWNERSHIP_REQUIRED: 原生写入未登记独立进程和租约。') + from .icdb_ownership import session_resource_scope + record = ({k: job.get(k) for k in ( + 'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal', 'worker_lease_handle', + 'worker_role', 'start_gate_protocol', 'start_gate')} + | {'processes': [{'role': 'worker', **process_identity(worker.pid)}], + 'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job), + 'worker_protection': protection, 'task_operation_id': context.operation_id if context else None, + 'blocked_resources': [], 'data_recovery_required': None}) + if job.get('start_gate_protocol') == 'event-v1': + import win32api, win32con, win32event + event = win32event.CreateEvent(None, True, False, None) + process = getattr(worker, 'handle', None) or getattr(worker, '_handle', None) + if process is None: + raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少工作进程句柄。') + # Use the launch handle, never a reopened PID. The child's event survives + # supervisor exit even before Python startup or journal reads finish. + remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), event, + process, 0, False, win32con.DUPLICATE_SAME_ACCESS) + record['worker_start_handle'] = remote.Detach() + worker._start_event = event + worker._start_binding = (str(path), job['operation_id'], job['start_gate']) + write_session_record(path, record) + bind_supervised_worker(path, record) worker.session_record_path = path worker.cbb_library = job['library'] + check_worker_admission(job) # A slow registration must not open a gate after UI shutdown. -def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False, continuation=False): +def update_worker_state(job, phase, *, identities=(), observed_identities=(), write_outcome=None, + required=False, continuation=False): """required controls I/O; only existing same-phase calls may continue recording after supervisor loss.""" if not job.get('session_record_path'): if required: @@ -132,6 +202,12 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None, requir for role, pid in identities: if pid and not any(p['pid'] == pid for p in state['processes']): state['processes'].append({'role': role, **process_identity(pid)}) + # Callers supply these only after validating an open handle's exact + # job membership; do not reopen a snapshot PID during publication. + for role, identity in observed_identities: + bound = {key: identity[key] for key in IDENTITY_KEYS} + if not any(all(p.get(key) == value for key, value in bound.items()) for p in state['processes']): + state['processes'].append({'role': role, **bound}) state['phase'] = phase if write_outcome is not None: state['write_outcome'] = write_outcome @@ -230,7 +306,13 @@ def _result(status, detail='', *, session=None, state=None, proof=None): return {'status': status, 'detail': detail, 'library': (session or {}).get('library'), 'block': (session or {}).get('block'), 'operation_id': (session or {}).get('operation_id'), - 'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof} + 'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof, + 'lease_state': (proof or {}).get('lease_state', 'ACTIVE' if status == 'ACTIVE' else 'UNCONFIRMED'), + 'resource_scope': (proof or {}).get('resource_scope') or (session or {}).get('resource_scope') + or {'scope_state': 'RECHECK_REQUIRED'}, + 'blocked_resources': (proof or {}).get('blocked_resources', (session or {}).get('blocked_resources', [])), + 'data_recovery_required': (proof or {}).get('data_recovery_required', + (session or {}).get('data_recovery_required'))} def _reconcile(path, root, handles, stack, *, release=True): @@ -305,15 +387,17 @@ def inspect_session_record(path, *, evidence_root): def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None, observe_only=False): stop = stop if stop is not None else threading.Event() + read_only = observe_only if callable(observe_only) else lambda: observe_only observation = Path(path).with_name('observation-' + uuid4().hex + '.json') with ExitStack() as stack: handles = {} while True: + observation_only = read_only() try: - result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observe_only) + result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observation_only) except Exception as error: result = _result('UNCONFIRMED', str(error)) - if (not observe_only and process is not None and process.poll() is not None + if (not observation_only and process is not None and process.poll() is not None and getattr(process, 'cbb_library', None)): try: from .library_lock import release_retained_library @@ -323,7 +407,16 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p session={'library': str(process.cbb_library)}, proof=proof) except Exception: pass - if result['status'] == 'IDENTITY_CHANGED' and not observe_only: + if result['status'] == 'ACTIVE' and not observation_only and not stop.is_set(): + try: + from .residual_sessions import resume_cancelled_startup + if resume_cancelled_startup(path, stop=stop): + # Cleanup is not release proof. Re-read all held identities + # and independently prove the resource release as usual. + result = _reconcile(Path(path), Path(evidence_root), handles, stack) + except Exception: + logging.getLogger(__name__).warning('Retained startup cleanup unavailable', exc_info=True) + if result['status'] == 'IDENTITY_CHANGED' and not observation_only: try: from .library_lock import release_retained_library proof = release_retained_library(result['library'], Path(path).parent/'release-proof') @@ -331,6 +424,10 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof} except Exception as error: result['detail'] += f';资源释放待确认:{error}' + try: + result['owned_worker_alive'] = process is not None and process.poll() is None + except Exception: + result['owned_worker_alive'] = False try: write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'}) except (OSError, ValueError): @@ -341,7 +438,7 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p except Exception: logging.getLogger(__name__).warning('Observation callback failed', exc_info=True) if (result['status'] == 'RELEASED' or stop.is_set() - or observe_only and result['status'] != 'ACTIVE'): + or read_only() and result['status'] != 'ACTIVE'): return result if not handles and process is not None and process.poll() is None: stop.wait(1) @@ -363,33 +460,49 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set() with _observer_guard: if key in _observers: + if (observe_only is False and session.get('operation_id') + and _retained_results.get(key, {}).get('operation_id') == session['operation_id']): + _retained_results[key]['release_operation_id'] = session['operation_id'] return _retained_libraries[key] = aliases _retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED', 'library': str(library) if library else None, 'block': session.get('block'), - 'detail': '正在核对残留会话', 'operation_id': session.get('operation_id')} + 'detail': '正在核对残留会话', 'operation_id': session.get('operation_id'), + 'observer_initializing': True} def notify(value): with _observer_guard: if _retained_libraries.get(key) is aliases: previous = _retained_results[key] _retained_results[key] = {**previous, **value, + 'observer_initializing': False, 'library': value.get('library') or previous['library'], 'operation_id': value.get('operation_id') or previous['operation_id'], 'block': value.get('block') or previous['block']} if progress is not None: progress(value) + def observation_only(): + if not observe_only: + return False + with _observer_guard: + value = _retained_results.get(key, {}) + return not (session.get('operation_id') and _retained_libraries.get(key) is aliases + and value.get('operation_id') == session.get('operation_id') + and value.get('release_operation_id') == session.get('operation_id')) def observe(): result = None try: result = observe_retained_session(path, evidence_root=evidence_root, progress=notify, - stop=stop, process=process, observe_only=observe_only) + stop=stop, process=process, observe_only=observation_only) if process is not None and process.poll() is not None: process.close() return result finally: with _observer_guard: - _observers.pop(key, None) - if result and result['status'] == 'RELEASED': + if _observers.get(key, (None,))[0] is threading.current_thread(): + _observers.pop(key, None) + if (result and result['status'] == 'RELEASED' + and _retained_libraries.get(key) is aliases + and _retained_results.get(key, {}).get('operation_id') == session.get('operation_id')): _retained_libraries.pop(key, None) _retained_results.pop(key, None) thread = threading.Thread(target=observe, name='retained-native-session', daemon=True) @@ -420,9 +533,14 @@ def discover_sessions(evidence_root, *, library=None): if not (name.startswith('observation-') and name.endswith('.json')): continue observation = read_session_record(Path(folder)/name, evidence_root=root) + proof = observation.get('release_proof') or {} + proof = proof if isinstance(proof, dict) else {} + session_scope = value.get('resource_scope') if observation['operation_id'] == value['operation_id'] and ( - observation.get('status') == 'RELEASED' and observation.get('release_proof') + observation.get('status') == 'RELEASED' + and _proof_covers_session(proof, value) or observation.get('status') == 'FINISHED' + and isinstance(session_scope, dict) and session_scope.get('scope_state') == 'DECLARED' and observation.get('native_release_confirmed') is True and observation.get('worker_exited') is True): completed = True diff --git a/src/cbb_refresh_verify/ui/backup_recovery_dialog.py b/src/cbb_refresh_verify/ui/backup_recovery_dialog.py index 6eff0fb..0fedaeb 100644 --- a/src/cbb_refresh_verify/ui/backup_recovery_dialog.py +++ b/src/cbb_refresh_verify/ui/backup_recovery_dialog.py @@ -2,12 +2,14 @@ from pathlib import Path from threading import Event -from PySide6.QtCore import QObject, QThreadPool, Signal +from PySide6.QtCore import QObject, QThreadPool, Signal, Qt from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox) from .workers import ServiceWorker from .backup_notice import MANUAL_BACKUP_NOTICE +from . import timed_prompt +from ..operation_queue import BatchTaskContext class RecoverySignals(QObject): @@ -27,13 +29,17 @@ class BackupRecoveryDialog(QDialog): self.recoverer = recoverer self.native_queue = None self.stop = Event() + self.context = None + self.ui_job = None + self.admit = None + self.setWindowModality(Qt.NonModal) self.busy = False self.pool = QThreadPool(self) self.pool.setMaxThreadCount(1) self.signals = RecoverySignals(self) self.signals.progress.connect(self._progress) - if parent is not None and hasattr(parent, '_show_version_choice'): - self.signals.choice.connect(parent._show_version_choice) + self._choice_handler = getattr(parent, '_show_version_choice', None) + self.signals.choice.connect(self._choice) self.block_combo = QComboBox() self.block_combo.addItems(list(names)) self.source_edit = QLineEdit() @@ -46,7 +52,7 @@ class BackupRecoveryDialog(QDialog): self.close_button.clicked.connect(self.reject) self.cancel_queue_button = QPushButton('取消排队') self.cancel_queue_button.setEnabled(False) - self.cancel_queue_button.clicked.connect(self.stop.set) + self.cancel_queue_button.clicked.connect(lambda:self.stop.set()) self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。') self.status_label.setWordWrap(True) layout = QFormLayout(self) @@ -88,42 +94,69 @@ class BackupRecoveryDialog(QDialog): except Exception as error: self.status_label.setText(str(error)) return - if QMessageBox.question(self, '确认从备份恢复', + if timed_prompt.question(self, '确认从备份恢复', f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{request.lmc_file}\nCBB:{name}\n来源:{source}' '\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?', - QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes: + QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes: + return + if self.admit is not None and not self.admit((request, source)): + self.status_label.setText('相同任务已提交,未重复执行。') return self.busy = True - self.stop.clear() + self.context = BatchTaskContext(str(request.lmc_file), targets=(name,), native_policy='external') + context = self.context + self.stop = context.stop self._set_enabled(False) self.status_label.setText('正在准备恢复…') self.started.emit(name) def execute(): - options = {'version_prompt': self.signals.choice.emit,'stop':self.stop} if self.recoverer is None else {} - action = lambda: recoverer(request, source, progress=self.signals.progress.emit, **options) - if self.native_queue is None: return action() + options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {} + action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options) + if self.native_queue is None: return context.run(action) from ..operation_queue import QueueCancelled def restore(): - self.signals.progress.emit({'stage': 'queue_acquired'}) + self._emit(context, 'progress',{'stage': 'queue_acquired'}) return action() try: - return self.native_queue.run(restore, stop=self.stop, waiting=lambda: self.signals.progress.emit( + return self.native_queue.run(restore, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress', {'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'})) except QueueCancelled as error: - from ..verify_runner import VerifyResult + from ..operation_queue import TaskHandoff + from ..verify_runner import VerifyResult, _handoff_verify_result + if isinstance(error, TaskHandoff): return _handoff_verify_result(error) return VerifyResult('CANCELLED', stderr=str(error)) self.worker = ServiceWorker(execute) - self.worker.signals.succeeded.connect(lambda result: self._result(name, result)) - self.worker.signals.failed.connect(lambda error: self._failed(name, error)) - self.worker.signals.finished.connect(self._finished) + self.worker.signals.succeeded.connect(context.guard_callback(lambda result: self._result(name, result), current=lambda:self.context)) + self.worker.signals.failed.connect(context.guard_callback(lambda error: self._failed(name, error), current=lambda:self.context)) + self.worker.signals.finished.connect(lambda:self._finished() if self.context is context else None) self.pool.start(self.worker) + def _emit(self, context, signal, value): + if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set(): + if signal == 'choice': value.choose('cancel') + return + try: + delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)() + if not delivered and signal == 'choice': value.choose('cancel') + except RuntimeError: + if signal == 'choice': value.choose('cancel') + + def _choice(self, payload): + context, choice = payload + if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None: + choice.choose('cancel') + return + self._choice_handler((self.ui_job,choice) if self.ui_job else choice) + def _set_enabled(self, enabled): for widget in (self.block_combo, self.source_edit, self.browse_button, self.restore_button, self.close_button): widget.setEnabled(enabled) def _progress(self, event): + if isinstance(event, tuple): + context, event = event + if context is not self.context or not self.busy: return if isinstance(event, dict): if event.get('stage') in ('waiting_native_slot', 'queue_acquired'): self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot') @@ -159,6 +192,7 @@ class BackupRecoveryDialog(QDialog): def closeEvent(self, event): if self.busy: + self.stop.set() event.ignore() else: super().closeEvent(event) diff --git a/src/cbb_refresh_verify/ui/icdb_check_task.py b/src/cbb_refresh_verify/ui/icdb_check_task.py index 30ed9ad..3aa077a 100644 --- a/src/cbb_refresh_verify/ui/icdb_check_task.py +++ b/src/cbb_refresh_verify/ui/icdb_check_task.py @@ -1,8 +1,7 @@ """A check batch owns its snapshot and yields the native queue after each CBB.""" -from threading import Event from PySide6.QtCore import QObject, QThreadPool, Signal from .workers import ServiceWorker -from ..operation_queue import QueueCancelled +from ..operation_queue import QueueCancelled, BatchTaskContext from ..verify_runner import VerifyResult, run_verify, write_batch_report from ..icdb_maintenance import write_maintenance_report @@ -12,14 +11,18 @@ class IcdbCheckTask(QObject): item_done = Signal(str, object) finished = Signal(object) - def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None): + def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None, status_reader=None, choice_prompt=None): super().__init__(parent) self.requests = tuple(requests) self.queue, self.report_root = queue, report_root self.path_lease = path_lease - self.verifier = verifier or (lambda req: run_verify(req, progress=self.event.emit, stop=self.stop)) + self.context = BatchTaskContext(str(self.requests[0].lmc_file), + targets=tuple(r.block_name for r in self.requests), native_policy='external') + self.status_reader = status_reader + self.verifier = verifier or (lambda req: run_verify(req, progress=self._emit_event, + stop=self.stop, version_prompt=choice_prompt)) self.results = [] - self.stop = Event() + self.stop = self.context.stop self.active = False self.paused = False self.invalidated = set() @@ -30,6 +33,12 @@ class IcdbCheckTask(QObject): self.retained_libraries = set() self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) + def _emit_event(self, event): + try: + self.context.guard_callback(self.event.emit)(event) + except RuntimeError: + pass + def start(self): self.active = True self._next() @@ -68,23 +77,31 @@ class IcdbCheckTask(QObject): from ..session_record import library_available, library_wait_reason try: def execute(): + if self.status_reader is not None: + statuses = self.status_reader((request.block_name,), request.lmc_file) + self.update_statuses(statuses) + if statuses.get(request.block_name) == 'NOT_REGISTERED': + return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。') if request.block_name in self.ready_names: return VerifyResult('SKIPPED', stderr='工程已为 READY,跳过 ICDB 检查。') if request.block_name in self.invalidated: return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。') - self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name}) + self._emit_event({'stage': 'icdb_check_start', 'block': request.block_name}) result = self.verifier(request) if not result.safe_to_continue: from ..operation_lifecycle import recheck_failed_release result = recheck_failed_release(request.lmc_file, request.block_name, result) return result - return self.queue.run(execute, stop=self.stop, + return self.queue.run(execute, stop=self.stop, context=self.context, wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)), - ready=lambda: not self.paused and library_available(request.lmc_file), - waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name, + ready=lambda: not self.paused, + waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name, 'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file), 'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'})) except QueueCancelled as error: + from ..operation_queue import TaskHandoff + from ..verify_runner import _handoff_verify_result + if isinstance(error, TaskHandoff): return _handoff_verify_result(error) return VerifyResult('CANCELLED', stderr=str(error)) except Exception as error: return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False, @@ -117,7 +134,12 @@ class IcdbCheckTask(QObject): return report, '' except Exception as error: return None, str(error) - self.worker = ServiceWorker(write) + def bounded_write(): + try: + return BatchTaskContext(str(self.requests[0].lmc_file)).run(write, metadata_only=True) + except Exception as error: + return None, str(error) + self.worker = ServiceWorker(bounded_write) self.worker.signals.succeeded.connect(self._report_ready) self.worker.signals.finished.connect(self._complete) self.pool.start(self.worker) diff --git a/src/cbb_refresh_verify/ui/main_window.py b/src/cbb_refresh_verify/ui/main_window.py index 2e60cc9..64dec0a 100644 --- a/src/cbb_refresh_verify/ui/main_window.py +++ b/src/cbb_refresh_verify/ui/main_window.py @@ -5,6 +5,10 @@ import ntpath import time from collections import Counter from dataclasses import replace +from types import SimpleNamespace +import json + +from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer from PySide6.QtGui import QColor, QIcon @@ -47,6 +51,8 @@ except ImportError: from cbb_refresh_verify.ui.workers import ServiceWorker from cbb_refresh_verify.library_reader import read_library_fast, scan_open_library_status from cbb_refresh_verify.batch_status import authoritative_status_map +from .timed_prompt import arm_default +from . import timed_prompt from cbb_refresh_verify.defaults import DEFAULT_TIMEOUT_SECONDS from cbb_refresh_verify.network_path import LibraryPathLease, select_library_file from cbb_refresh_verify.verify_runner import (VerifyRequest, preflight_skip_reason, run_verify, @@ -71,7 +77,6 @@ STATUS_LABELS = { 'CRASHED': '状态桥崩溃', } - def application_icon_path(): return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico' @@ -79,7 +84,7 @@ def application_icon_path(): class MainWindow(QWidget): def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None, authoritative_status=True, path_lease_factory=None, status_refresher=None, - management_adapter=None, native_backup_launcher=None): + management_adapter=None, native_backup_launcher=None, catalog_reader=None): super().__init__() self.setWindowTitle('CBB 刷新校验') icon_path = application_icon_path() @@ -92,6 +97,7 @@ class MainWindow(QWidget): self.library_lease = None self.mentor_lmc_path = None self.data_root = Path(data_root or (logging_context.root if logging_context else Path(os.environ.get('LOCALAPPDATA', '.'))/'CbbRefreshVerify')) + self._settings_enabled = data_root is not None or logging_context is not None or reader is None from cbb_refresh_verify.native_management import NativeManagementAdapter self.management_adapter = management_adapter or NativeManagementAdapter() self.management_capabilities = self.management_adapter.capabilities() @@ -109,30 +115,30 @@ class MainWindow(QWidget): self.native_backup_timer = QTimer(self) self.native_backup_timer.setInterval(400) self.native_backup_timer.timeout.connect(self._poll_native_backup) - if reader is not None: - self.reader = reader - elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy': - self.reader = lambda path: read_library_fast( - path, - status_reader=lambda p, names: authoritative_status_map( - names, p, self.data_root / 'status-scan.jsonl'), - ) - else: - # Legacy icon/filesystem reader remains opt-in until the bridge is - # accepted on the target Mentor installation. It cannot override - # the authoritative path when that path is enabled explicitly. - self.reader = lambda path: read_library_fast( - path, - status_reader=lambda p, names: scan_open_library_status( - p, names, mapping_store=self.data_root/'image-status-map.json'), - ) - self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) + self._injected_reader = reader is not None + self.reader = reader or read_library_fast + self.catalog_reader = catalog_reader or (None if reader is not None else getattr(self.management_adapter,'catalog',None)) + self._view_revision = 0 + self._jobs = {} + self._dialogs = [] + self._current_job = None + self._stale_table = False + self._read_counts = (None, None, None) + self._diagnostic_evidence = {} + self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8) self.lifecycle_pool = QThreadPool(self); self.lifecycle_pool.setMaxThreadCount(1) + self.lease_pool = QThreadPool(self); self.lease_pool.setMaxThreadCount(1) self._lifecycle_workers = set() + self._lifecycle_contexts = set() self._lease_pending = 0 self._lease_workers = set() + self._lease_contexts = set() + self._shutdown_leases = {} + self._retention_intents = {} + self._retention_ready = set() self._mapping_busy = 0 - self._mapping_auto_idle = False + self._mapping_owners = Counter() + self._mapping_auto_owners = set() self._mapping_finish_waiters = [] self._closing = self._close_ready = False self._queue_wait_library = None @@ -155,11 +161,14 @@ class MainWindow(QWidget): self._icdb_completed = 0 self.signals = ProgressSignals(self); self.signals.event.connect(self._progress) self.signals.batch_ready.connect(self._batch_done) - if hasattr(self.management_adapter, 'session_progress'): - self.management_adapter.session_progress = self.signals.event.emit self.signals.version_choice.connect(self._show_version_choice) self.version_dialog = None self.lmc_edit = QLineEdit() + try: + if self._settings_enabled: + self.lmc_edit.setText(str(json.loads((self.data_root/'settings.json').read_text('utf-8')).get('last_library', ''))) + except (OSError, ValueError, TypeError): + pass self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9')) self.dms_edit = QLineEdit(os.environ.get('CBB_DMS_LOGIN_CONFIG', '')) self.mentor_bin_edit = QLineEdit(os.environ.get('SDD_LM_BIN', '')) @@ -186,6 +195,7 @@ class MainWindow(QWidget): self.cbb_table.horizontalHeader().setSectionResizeMode(column, QHeaderView.ResizeToContents) self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows) self.cbb_table.setMinimumHeight(150) + self.cbb_table.currentCellChanged.connect(lambda *_: self._update()) self.cbb_table.itemChanged.connect(lambda _item: self._update()) self.search_edit = QLineEdit() self.search_edit.setPlaceholderText('按 CBB 名称或分区搜索') @@ -277,6 +287,9 @@ class MainWindow(QWidget): self.native_backup_button.setToolTip('勾选一个非 READY CBB,打开原生备份列表并选择回退版本。') self.native_backup_button.clicked.connect(self.open_native_backup) maintenance_layout.addWidget(self.native_backup_button) + self.native_repair_button = QPushButton('手动 Repair…') + self.native_repair_button.clicked.connect(lambda: self.open_native_backup(mode='repair')) + maintenance_layout.addWidget(self.native_repair_button) maintenance_row = QHBoxLayout() maintenance_row.addWidget(self.icdb_repair_button) self.icdb_stop_button = QPushButton('停止检查') @@ -336,15 +349,64 @@ class MainWindow(QWidget): self._update() def _invalidate(self): + if self._current_job is not None and self._current_job.kind == 'read': + self._current_job.context.close(timeout_seconds=0) + self._view_revision += 1 + self._current_job = None self._reimport_offers = () - if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path: - self._release_library_lease() - self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {} - self._records_by_name = {} - self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update() - self._global_icdb_run = False - if not self._icdb_active(): - self.icdb_progress.hide(); self.icdb_phase.hide() + self._diagnostic_evidence.clear() + self._resume_batch = None + self._stale_table = bool(self._records_by_name) + self._release_library_lease() + self.loaded_path = None + self.mentor_lmc_path = None + self.busy = False + self._update() + + def _new_job(self, kind, *, library=None, targets=(), lease=None): + library = str(library or self.mentor_lmc_path or self.lmc_edit.text()) + lease = self.library_lease if lease is None else lease + policy = 'external' if kind in ('verify','management','recovery','icdb','catalog','status','native_session') else 'restricted' + context = BatchTaskContext(library, aliases=tuple(_library_path_keys(library, lease)), + targets=tuple(targets), native_policy=policy) + job = SimpleNamespace(context=context, kind=kind, revision=self._view_revision, + lease=lease, requests=(), records={}, active=True, keep_session=False) + self._jobs[context.operation_id] = job + self._current_job = job + self.stop = context.stop + return job + + def _job_current(self, job): + from shiboken6 import isValid + return (not self._closing and isValid(self) and isValid(self.cbb_table) + and job.revision == self._view_revision and self._current_job is job) + + def _emit_job(self, job, signal, value): + # A native observer may outlive both its Qt receiver and its handoff. + if self._closing or not job.active: + if signal == 'version_choice': value.choose('cancel') + return + try: + getattr(self.signals, signal).emit((job, value)) + except RuntimeError: + if signal == 'version_choice': value.choose('cancel') + + def _finish_job(self, job): + if job.keep_session: + if self._job_current(job): self._finished() + return + paused = getattr(job, 'paused_check', None) + if paused is not None and paused.active and not paused.stop.is_set() and not self._closing: + paused.resume() + job.active = False + self._jobs.pop(job.context.operation_id, None) + state = job.context.close(timeout_seconds=0) + if job.lease is not None and job.lease is not self.library_lease: + if state['pending'] or id(job.lease) in self._shutdown_leases: + self._retain_path_lease(job.lease) + elif not any(other.lease is job.lease for other in self._jobs.values()): + self._close_path_lease(job.lease) + if self._job_current(job): self._finished() def _release_library_lease(self): lease, self.library_lease = self.library_lease, None @@ -352,7 +414,7 @@ class MainWindow(QWidget): return # The visible native session still needs this mapping. if self._icdb_active() and self.icdb_task.path_lease is lease: return # This background task still uses its captured mapping. - if lease is None: + if lease is None or any(job.lease is lease for job in self._jobs.values()): return try: self._close_path_lease(lease) @@ -361,45 +423,73 @@ class MainWindow(QWidget): self.logging_context.logger.warning('library_lease_release_failed error=%s', error) def _close_path_lease(self, lease): - self._lease_action(lease.close, hold_busy=self.busy) + if id(lease) in self._shutdown_leases: return + if id(lease) in self._retention_intents and id(lease) not in self._retention_ready: return + self._lease_action(lease.close) def _retain_path_lease(self, lease, *, hold_busy=False): if lease is not None: - self._lease_action(lease.retain_for_recovery, hold_busy=hold_busy) + self._retention_intents[id(lease)] = lease + self._retention_ready.discard(id(lease)) + def retained(_): + self._retention_ready.add(id(lease)) + if (not self._closing and lease is not self.library_lease + and not any(job.lease is lease for job in self._jobs.values())): + self._close_path_lease(lease) + self._lease_action(lease.retain_for_recovery, retained, hold_busy=hold_busy, completed_always=True) - def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False): + def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False, + library=None, completed_always=False): # The serial pool orders retain before every subsequent close. + owner = (self._view_revision, id(self._current_job)) + def current(): + from shiboken6 import isValid + return (isValid(self) and isValid(self.cbb_table) and not self._closing + and owner == (self._view_revision, id(self._current_job))) self._lease_pending += 1 if hold_busy: - if not self._mapping_busy and not self.busy: - self._mapping_auto_idle = True + if not self.busy: self._mapping_auto_owners.add(owner) + self._mapping_owners[owner] += 1 self._mapping_busy += 1 self.busy = True self._update() - worker = ServiceWorker(action) + library = library or getattr(getattr(action,'__self__',None),'mentor_path',None) + context = BatchTaskContext(str(library or self.mentor_lmc_path or self.loaded_path or self.data_root), + native_policy='restricted') + self._lease_contexts.add(context) + worker = ServiceWorker(lambda:context.run(action)) self._lease_workers.add(worker) - if completed is not None: worker.signals.succeeded.connect(completed) - worker.signals.failed.connect(failed or self._display_error) + if completed is not None: + worker.signals.succeeded.connect(lambda result:completed(result) if completed_always or current() else None) + worker.signals.failed.connect(lambda error:(failed or self._display_error)(error) if current() else None) def finished(): self._lease_workers.discard(worker) + self._lease_contexts.discard(context) self._lease_pending -= 1 - if hold_busy: self._mapping_busy -= 1 + if hold_busy: + self._mapping_busy -= 1 + self._mapping_owners[owner] -= 1 from shiboken6 import isValid if not isValid(self) or not isValid(self.cbb_table): return - if not self._mapping_busy: - callbacks, self._mapping_finish_waiters = self._mapping_finish_waiters, [] - auto_idle, self._mapping_auto_idle = self._mapping_auto_idle, False - for callback in callbacks: callback() - if auto_idle and not callbacks: self._finished() + if not self._mapping_owners[owner]: + callbacks = [entry for entry in self._mapping_finish_waiters if entry[0] == owner] + self._mapping_finish_waiters = [entry for entry in self._mapping_finish_waiters if entry[0] != owner] + for callback_owner, callback in callbacks: + if current(): callback() + if owner in self._mapping_auto_owners and not callbacks and current(): self._finished() + self._mapping_auto_owners.discard(owner) + self._mapping_owners.pop(owner, None) self._update() worker.signals.finished.connect(finished) - self.pool.start(worker) + self.lease_pool.start(worker) def _defer_mapping_finish(self, callback): - if not self._mapping_busy: return False - if callback not in self._mapping_finish_waiters: - self._mapping_finish_waiters.append(callback) + owner = (self._view_revision, id(self._current_job)) + if not self._mapping_owners[owner]: return False + waiter = (owner, callback) + if waiter not in self._mapping_finish_waiters: + self._mapping_finish_waiters.append(waiter) return True def _update(self): @@ -411,8 +501,13 @@ class MainWindow(QWidget): ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0 selected = self.selected_records() native_target = self._native_backup_target() - self.native_backup_button.setEnabled(ready and self._native_backup_session is None - and native_target is not None) + native_pending = any(job.active and job.kind == 'native_session' for job in self._jobs.values()) + native_enabled = ready and self._native_backup_session is None and not native_pending and native_target is not None + self.native_backup_button.setEnabled(native_enabled) + self.native_repair_button.setEnabled(native_enabled) + reason = ('原生版本/修复窗口仍在使用或正在打开。' if self._native_backup_session is not None or native_pending else + '请选择一个当前可见的非 READY CBB。' if native_target is None else '') + self.native_repair_button.setToolTip(reason or '打开原生工具;请在其中手动选择 Repair。') ready = ready and not self._native_backup_same_library() self.batch_button.setEnabled(ready and bool(self._eligible_names())) self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True))) @@ -420,7 +515,7 @@ class MainWindow(QWidget): self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set()) self.backup_restore_button.setEnabled(ready and bool( self._eligible_names(checked_only=bool(self.selected_records())))) - self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip())) + self.release_library_button.setEnabled(not self._closing and bool(self.lmc_edit.text().strip())) waiting_library = self._queued_release_library() self.queue_release_button.setVisible(waiting_library is not None) self.queue_release_button.setEnabled(waiting_library is not None and not self._closing) @@ -429,7 +524,11 @@ class MainWindow(QWidget): if action is not None and isValid(action): queued_target = bool(waiting_library and _library_path_keys(waiting_library, task.path_lease) & _library_path_keys(task.requests[0].lmc_file, task.path_lease)) - action.setEnabled(not self._closing and (not self.busy or queued_target)) + action.setEnabled(self._summary_current(getattr(task,'summary',None)) and (not self.busy or queued_target)) + recovery = getattr(task,'recovery_action',None) + if recovery is not None and isValid(recovery): + recovery.setEnabled(not self.busy and self._summary_current(getattr(task,'summary',None)) + and not (getattr(task,'recovery_names',set()) & task.invalidated)) reasons = [] for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)): reason = self._management_block_reason(operation) @@ -441,15 +540,21 @@ class MainWindow(QWidget): current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None notice = ('上次操作结果待复查,执行前将重新检查占用。' if self._management_library_unsafe(current_library) else '') + notice = '旧表已失效,请重新读取中心库。' if self._stale_table else notice self.library_notice.setText(notice) self.library_notice.setVisible(bool(notice)) for widget in (self.lmc_edit, self.browse_button, self.load_button, self.timeout_spin, self.advanced_toggle, self.advanced_panel): - widget.setEnabled(not self.busy) + widget.setEnabled(not self._closing) counts = self.visible_counts() self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · ' f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}') - self.stop_button.setEnabled((self.busy and self.loaded_path is not None and not self.stop.is_set()) + directory, native, missing = self._read_counts + if directory is not None: + self.counts_label.setText(self.counts_label.text() + + f' · 目录 {directory} · 原生 {native if native is not None else "未知"} · 缺工程 {missing or 0}') + self.stop_button.setEnabled(any(job.active and not job.context.stop.is_set() for job in self._jobs.values()) + or (self.busy and not self.stop.is_set()) or self._icdb_active() and not self.icdb_task.stop.is_set()) self.stop_button.setText('取消当前任务并停止队列') available = bool(self._reimport_offers) and not self.busy and self.management_capabilities['update'].supported @@ -457,20 +562,27 @@ class MainWindow(QWidget): self.reimport_button.setEnabled(available) self.reimport_button.setToolTip(self.management_capabilities['update'].reason) if self._reimport_summary_action is not None: - self._reimport_summary_action.setEnabled(available) + self._reimport_summary_action.setEnabled(available and self._summary_current(getattr(self,'_batch_summary',None))) if getattr(self, '_residual_release_action', None) is not None: - self._residual_release_action.setEnabled(not self.busy) + self._residual_release_action.setEnabled(not self.busy and self._summary_current(getattr(self,'_batch_summary',None))) if getattr(self, '_resume_batch_action', None) is not None: pending = getattr(self, '_resume_batch', None) same = bool(pending and _library_path_keys(pending['library'], self.library_lease) & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)) - self._resume_batch_action.setEnabled(not self.busy and same and pending['released']) + self._resume_batch_action.setEnabled(not self.busy and same and pending['released'] + and self._summary_current(getattr(self,'_batch_summary',None))) def _show_unfinished_management(self): from cbb_refresh_verify.management import unfinished_operations from cbb_refresh_verify.session_record import discover_sessions, handoff_session root = self.data_root - notify = self.signals.event.emit + revision, owner = self._view_revision, self._current_job + context = BatchTaskContext(str(root)) + self._lifecycle_contexts.add(context) + def notify(value): + if self._closing: return + try: self.signals.event.emit((revision, owner, value)) + except RuntimeError: pass def inspect(): unfinished = unfinished_operations(root/'management') sessions = discover_sessions(root) @@ -480,11 +592,14 @@ class MainWindow(QWidget): observe_only=True, progress=lambda value: notify({'stage': 'session_observation', **value})) return unfinished, sessions - worker = ServiceWorker(inspect) + worker = ServiceWorker(lambda:context.run(inspect)) self._lifecycle_workers.add(worker) - worker.signals.succeeded.connect(self._unfinished_sessions_ready) - worker.signals.failed.connect(self._display_error) - worker.signals.finished.connect(lambda: self._lifecycle_workers.discard(worker)) + def current(): + from shiboken6 import isValid + return (isValid(self) and not self._closing and revision == self._view_revision and owner is self._current_job) + worker.signals.succeeded.connect(lambda payload:self._unfinished_sessions_ready(payload) if current() else None) + worker.signals.failed.connect(lambda error:self._display_error(error) if current() else None) + worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._lifecycle_contexts.discard(context))) self.lifecycle_pool.start(worker) def _unfinished_sessions_ready(self, payload): @@ -521,7 +636,7 @@ class MainWindow(QWidget): if queued and not allowed_queue: self._update() return - if (self.busy and not allowed_queue) or not self.lmc_edit.text().strip(): + if not self.lmc_edit.text().strip(): return from shiboken6 import isValid previous = getattr(self, 'release_dialog', None) @@ -530,16 +645,22 @@ class MainWindow(QWidget): return from .residual_release_dialog import ResidualReleaseDialog library = Path(self._queue_wait_library if allowed_queue else self.mentor_lmc_path or self.lmc_edit.text().strip()) - self._queue_release_mode = bool(allowed_queue and self.busy) + self._queue_release_mode = self.busy + revision, owner_job, lease = self._view_revision, self._current_job, self.library_lease self.release_dialog = ResidualReleaseDialog(library, self.data_root/'release-checks', self) + dialog = self.release_dialog + dialog.path_lease = lease + self._dialogs.append(dialog) self.release_dialog.native_queue = self.native_queue - if self._queue_release_mode: - from cbb_refresh_verify.network_path import release_retained_path_leases - lease = self.library_lease - self.release_dialog.release_finalizer = lambda proof: release_retained_path_leases(proof, current_lease=lease) - self.release_dialog.before_release.connect(self._stop_icdb_check) - self.release_dialog.released.connect(lambda result: self._complete_library_release(self.release_dialog.library, result)) - self.release_dialog.finished.connect(self._release_dialog_finished) + from cbb_refresh_verify.network_path import release_retained_path_leases + self.release_dialog.release_finalizer = lambda proof: release_retained_path_leases(proof, current_lease=lease) + release_check = self.icdb_task if self._check_matches_library(library) else None + self.release_dialog.before_release.connect(lambda:release_check.cancel() + if release_check is not None and release_check.active else None) + self.release_dialog.released.connect(lambda result: self._complete_library_release( + library, result, lease=lease, revision=revision, owner_job=owner_job)) + self.release_dialog.finished.connect(lambda *_:self._release_dialog_finished() + if revision == self._view_revision and owner_job is self._current_job else None) self.busy = True; self._update() self.release_dialog.show() @@ -556,33 +677,45 @@ class MainWindow(QWidget): self.summary = self._new_result_summary('_batch_summary') self.summary.setWindowTitle('继续未执行项') self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole) - self._resume_batch_action.clicked.connect(self._resume_released_batch) + summary = self.summary + self._bind_summary_action(summary, self._resume_batch_action, self._resume_released_batch) self._update() self.summary.setText('会话已释放,可以继续未执行项。') self.summary.show() - def _complete_library_release(self, library, result): + def _complete_library_release(self, library, result, *, lease=None, revision=None, owner_job=None): from cbb_refresh_verify.network_path import release_retained_path_leases + lease = self.library_lease if lease is None else lease + if revision is None: + revision, owner_job = self._view_revision, self._current_job + def current(): + return not self._closing and revision == self._view_revision and owner_job is self._current_job + def ready(): + self._management_unsafe_libraries.discard(_path_key(library)) + if lease is not None and not getattr(lease, '_retained_for_recovery', False): + self._retention_intents.pop(id(lease), None) + self._retention_ready.discard(id(lease)) + if current(): self._library_release_ready(library, result) try: if (not isinstance(result, dict) or result.get('status') != 'RELEASE_CONFIRMED' - or not (_library_path_keys(result.get('library'), self.library_lease) - & _library_path_keys(library, self.library_lease))): + or not (_library_path_keys(result.get('library'), lease) + & _library_path_keys(library, lease))): raise ValueError('RELEASE_PROOF_UNCONFIRMED: 释放证明未确认或不属于当前中心库。') except Exception as error: - self._failed(error) + if current(): self._display_error(error) return if result.get('mapping_cleanup_complete') is True: - self._library_release_ready(library, result) + ready() return - lease = self.library_lease def release(): try: release_retained_path_leases(result, current_lease=lease) except Exception: if lease is not None: lease.retain_for_recovery() raise - self._lease_action(release, lambda _: self._library_release_ready(library, result), - self._display_error, hold_busy=True) + self._lease_action(release, lambda _: ready(), + lambda error:self._display_error(error) if current() else None, + hold_busy=current(), library=library, completed_always=True) def _library_release_ready(self, library, result): current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text().strip()) @@ -603,11 +736,12 @@ class MainWindow(QWidget): def _resume_released_batch(self): pending = getattr(self, '_resume_batch', None) if self.busy or not pending or not pending['released']: return + if pending.get('revision',self._view_revision) != self._view_revision: return if not (_library_path_keys(pending['library'], self.library_lease) & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): return self._resume_batch = None - self._run(pending['names'], maintenance=pending['maintenance']) + self._run(pending['names'], maintenance=pending['maintenance'], request_snapshot=pending.get('requests')) def _management_library_unsafe(self, library): if self._management_unsafe and self._management_unsafe_library is not None: @@ -651,22 +785,70 @@ class MainWindow(QWidget): def _open_management_dialog(self, requests, *, recovery_from=None): from .management_dialog import ManagementDialog self._global_icdb_run = False - self.stop.clear() + job = self._new_job('management', library=requests[0].library, targets=tuple(r.name for r in requests)) self._management_is_recovery = bool(recovery_from) self._management_operation_library = _path_key(requests[0].library) if requests else None requests = [replace(request, check_previous_release=True) if self._management_library_unsafe(request.library) else request for request in requests] - self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter, + adapter = self.management_adapter + if hasattr(adapter, 'session_progress'): + from copy import copy + adapter = copy(adapter) + adapter.session_progress = lambda event:self._emit_job(job,'event',event) + self.management_dialog = ManagementDialog(requests, self, adapter=adapter, recovery_from=recovery_from) + dialog = self.management_dialog + self._dialogs.append(dialog) + dialog.ui_job = job + dialog.admit = lambda snapshot:self._admit_snapshot(job,snapshot) self.management_dialog.native_queue = self.native_queue self.management_dialog.release_requested.connect(self._open_waiting_release) - self.management_dialog.before_execute.connect(lambda names: self._invalidate_check_targets(requests[0].library, names)) + def started(names): + self._adopt_dialog_context(job, dialog) + self._invalidate_check_targets(requests[0].library, names) + self.management_dialog.before_execute.connect(started) self._management_results = [] - self.management_dialog.completed.connect(self._management_completed) - self.management_dialog.finished.connect(self._management_closed) + def completed(results): + job.submitted = False + job.results = tuple(results) + if self._job_current(job): self._management_completed(results) + else: self._stale_operation_results(job, results) + def closed(*_): + if self._job_current(job): self._management_closed() + self._finish_job(job) + self.management_dialog.completed.connect(completed) + self.management_dialog.finished.connect(closed) self.busy = True; self._update() self.management_dialog.show() + def _admit_snapshot(self, job, snapshot): + if any(other is not job and other.kind == job.kind and getattr(other,'submitted',False) + and getattr(other,'submitted_snapshot',None) == snapshot for other in self._jobs.values()): return False + job.submitted_snapshot, job.submitted = snapshot, True + return True + + def _adopt_dialog_context(self, job, dialog): + self._jobs.pop(job.context.operation_id, None) + job.context = dialog.context or job.context + job.active = True + self._jobs[job.context.operation_id] = job + if job.revision == self._view_revision and (self._job_current(job) or not self.busy): + self._current_job = job + self.stop = job.context.stop + + def _stale_operation_results(self, job, results): + # Housekeeping belongs to the submitted lease, even after a view switch. + unsafe = any(not result.safe_to_continue for result in results) + if unsafe: + self._management_unsafe_libraries.add(_path_key(job.context.library)) + if job.lease is not None: self._retain_path_lease(job.lease) + proofs = [getattr(result, 'release_proof', None) for result in results] + for proof in proofs: + if isinstance(proof, dict) and proof.get('status') == 'RELEASE_CONFIRMED': + from cbb_refresh_verify.network_path import release_retained_path_leases + self._lease_action(lambda proof=proof: release_retained_path_leases(proof, current_lease=job.lease), + library=job.context.library) + def _open_waiting_release(self, library): from cbb_refresh_verify.session_record import library_available if not library_available(library): @@ -834,32 +1016,47 @@ class MainWindow(QWidget): path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0] if path: self.lmc_edit.setText(path); self.load_library() - def _start(self, action, callback, *, queued=True): - self.stop.clear() + def _start(self, action, callback, *, queued=True, job=None, metadata_only=False, bounded=True, stale=None): + job = job or self._new_job('action') self.busy = True; self._update() - self.worker = ServiceWorker(self._queued_action(action) if queued else action) - self.worker.signals.succeeded.connect(callback) - self.worker.signals.failed.connect(self._failed) - self.worker.signals.finished.connect(self._finished) + execute = (self._queued_action(action, job=job) if queued else + lambda: job.context.run(action, metadata_only=metadata_only)) if bounded else action + self.worker = ServiceWorker(execute) + worker = self.worker + self._lifecycle_workers.add(worker) + self.worker.signals.succeeded.connect(lambda value: callback(value) if self._job_current(job) + else stale(value) if stale is not None else None) + def failed(error): + if isinstance(error, TaskHandoff) and job.lease is not None: + self._retain_path_lease(job.lease) + if not self._job_current(job): return + if isinstance(error, QueueCancelled): self._display_error(error) + else: self._failed(error) + self.worker.signals.failed.connect(failed) + self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job))) self.pool.start(self.worker) - def _queued_action(self, action, *, label='', library=None): + def _queued_action(self, action, *, label='', library=None, job=None): from cbb_refresh_verify.session_record import library_available, library_wait_reason if library is None: from PySide6.QtCore import QThread if QThread.currentThread() != self.thread(): raise RuntimeError('后台入队必须传入任务绑定的中心库路径') library = getattr(self, 'mentor_lmc_path', None) or self.lmc_edit.text() + job = job or self._current_job + stop = job.context.stop if job else self.stop + def emit(event): + if job: self._emit_job(job, 'event', event) + else: self.signals.event.emit(event) def execute(): event = {'stage': 'native_slot_acquired', 'library': str(library)} if label: event['detail'] = label+'中…' - self.signals.event.emit(event) + emit(event) return action() - return lambda: self.native_queue.run(execute, stop=self.stop, - ready=lambda: library_available(library), + return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, wait_state=lambda: library_wait_reason(library), - waiting=lambda: self.signals.event.emit({'stage': 'waiting_native_slot', + waiting=lambda: emit({'stage': 'waiting_native_slot', 'library': str(library), 'retained': not library_available(library), 'detail': (label+':' if label else '')+(library_wait_reason(library) or '已排队,等待当前原生操作结束')})) @@ -897,15 +1094,34 @@ class MainWindow(QWidget): & _library_path_keys(task.requests[0].lmc_file, task.path_lease)): task.update_statuses(statuses) - def _start_icdb_check(self, names): + def _start_icdb_check(self, names, *, request_snapshot=None): if self.busy or self._icdb_active() or not self.loaded_path or self._native_backup_same_library(): return eligible = set(self._maintenance_names()) names = [name for name in names if name in eligible] if not names: return from .icdb_check_task import IcdbCheckTask - requests = tuple(replace(self._request(name), maintenance=True, auto_repair=False) for name in names) + requests = (tuple(request for request in request_snapshot if request.block_name in names) if request_snapshot is not None + else tuple(replace(self._request(name), maintenance=True, auto_repair=False) for name in names)) + if not requests: return task = IcdbCheckTask(requests, self.native_queue, self.data_root/'reports', - verifier=self.verifier, path_lease=self.library_lease, parent=self) + verifier=self.verifier, path_lease=self.library_lease, parent=self, + status_reader=self.status_refresher if self.catalog_reader is not None else None) + previous_job = self._current_job + job = self._new_job('icdb', library=requests[0].lmc_file, targets=names) + self._current_job = previous_job + self._jobs.pop(job.context.operation_id, None) + job.context = task.context + self.stop = task.stop + self._jobs[job.context.operation_id] = job + task.ui_job = job + task.revision = self._view_revision + task.status_reader = self._execution_status_reader(task.context.operation_id, task.path_lease) + if self.verifier is None: + def verify_request(req): + from cbb_refresh_verify.verify_runner import run_verify + return run_verify(req, progress=task._emit_event, stop=task.stop, + version_prompt=lambda choice:self._emit_job(job,'version_choice',choice)) + task.verifier = verify_request task.records = {name: self._records_by_name[name] for name in names} self.icdb_task = task self.icdb_tasks.append(task) @@ -919,6 +1135,7 @@ class MainWindow(QWidget): task.start(); self._update() def _icdb_event(self, task, event): + if self._closing or getattr(task,'revision',self._view_revision) != self._view_revision: return name, stage = str(event.get('block', '')), str(event.get('stage', '')) detail = str(event.get('detail') or stage) self.icdb_phase.setText(f'{name} · '+({'icdb_check_start': '正在检查', @@ -932,6 +1149,9 @@ class MainWindow(QWidget): self.logging_context.logger.info('icdb_background block=%s stage=%s detail=%s', name, stage, detail) def _icdb_item_done(self, task, name, result): + if self._closing or getattr(task,'revision',self._view_revision) != self._view_revision: return + if result.error_category == 'ICDB_REPAIR_REQUIRED' and result.evidence_path: + self._diagnostic_evidence[name] = result.evidence_path.parent/'diagnostics'/'icdb-recovery.json' self.icdb_progress.setValue(len(task.results)) if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): @@ -974,6 +1194,13 @@ class MainWindow(QWidget): held_by_native = self._native_backup_session is not None and self._native_backup_session.path_lease is lease if lease is not self.library_lease and not held_by_native: self._close_path_lease(lease) + job = getattr(task,'ui_job',None) + if job is not None: + job.lease = None # The explicit task lease cleanup above owns it. + self._finish_job(job) + if self._closing or getattr(task,'revision',self._view_revision) != self._view_revision: + self._update() + return for request, result in zip(task.requests, task.results): if result.status == 'SKIPPED': self._icdb_item_done(task, request.block_name, result) text = (f'ICDB 检查结束:未发现异常 {counts["checked_without_repair"]},发现问题 {counts["issues_found"]},' @@ -999,28 +1226,37 @@ class MainWindow(QWidget): summary.setTextFormat(Qt.PlainText); summary.setAttribute(Qt.WA_ShowWithoutActivating) if any(not result.safe_to_continue for result in task.results): def release_task(): + if not self._summary_current(summary): return if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): self.status_label.setText(f'请切回 {task.requests[0].lmc_file} 后释放该检查的残留。') return self.check_library_release(queued=self.busy) task.release_action = summary.addButton('查看残留并释放…', QMessageBox.ActionRole) - task.release_action.clicked.connect(release_task) + self._bind_summary_action(summary, task.release_action, release_task) if offers: action = summary.addButton('选择副本恢复…', QMessageBox.ActionRole) task.recovery_action = action task.recovery_names = {req.block_name for req, _, _ in offers} def recover(): + if not self._summary_current(summary): return if task.recovery_names & task.invalidated: return if self.busy or not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): return self._reimport_offers = offers self.reimport_failed() - action.clicked.connect(recover) + self._bind_summary_action(summary, action, recover) summary.show(); self._update() def load_library(self): - if self.busy or not self.lmc_edit.text(): return + if self._closing or not self.lmc_edit.text(): return + if (self._current_job is not None and self._current_job.kind == 'read' + and self._current_job.active and self._current_job.revision == self._view_revision): return + self._view_revision += 1 + self._diagnostic_evidence.clear() + self._stale_table = bool(self._records_by_name) + job = self._new_job('read', library=self.lmc_edit.text()) + job.lease = None self._maintenance_recovery_view = False self._global_icdb_run = False if self._management_unsafe_library is not None: @@ -1032,9 +1268,7 @@ class MainWindow(QWidget): if not self._icdb_active(): self.icdb_progress.hide(); self.icdb_phase.hide() self._release_library_lease() - self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set() - self._records_by_name = {} - self.skipped_names = set(); self.skip_reasons = {} + self.loaded_path = None path = self.lmc_edit.text() self.status_label.setText('正在读取中心库…') def read(): @@ -1056,6 +1290,7 @@ class MainWindow(QWidget): lease.remote_root or '-', lease.created) recovery_view = False result = self.reader(mentor_path) + job.context.check_active() if not result.error: self._publish_check_statuses(mentor_path, {record.name: record.status for record in result.records}, lease) @@ -1080,17 +1315,28 @@ class MainWindow(QWidget): finally: pythoncom.CoUninitialize() def loaded(payload): result, skip_reasons, lease, mentor_path, recovery_view = payload - if path != self.lmc_edit.text(): + if path != self.lmc_edit.text() or job.revision != self._view_revision: self._close_path_lease(lease) return if result.error: self._close_path_lease(lease) self.status_label.setText(result.error); return self.library_lease = lease + self._stale_table = False + self._read_counts = (result.directory_count, result.native_count, + result.missing_project_count if result.missing_project_count is not None else len(skip_reasons)) self._maintenance_recovery_view = recovery_view self.mentor_lmc_path = mentor_path self.loaded_path = path + try: + if self._settings_enabled: + self.data_root.mkdir(parents=True, exist_ok=True) + settings = self.data_root/'settings.json' + settings.write_text(json.dumps({'last_library': path}, ensure_ascii=False), encoding='utf-8') + except OSError as error: + self.output.append(f'无法保存上次路径:{error}') self.cbb_table.setRowCount(0) + self._row_by_name = {} self.ready_names = {r.name for r in result.records if r.status == 'READY' and r.name not in skip_reasons} self.skip_reasons = dict(skip_reasons) self.skipped_names = set(skip_reasons) @@ -1113,7 +1359,7 @@ class MainWindow(QWidget): self.cbb_table.setItem(row, 1, QTableWidgetItem(record.partition_name)) status_text = STATUS_LABELS.get(record.status, record.status) if record.name in self.skipped_names: - status_text += ' · 缺少工程/PCB' + status_text += ' · 未登记目录' if record.catalog_source == 'directory_only' else ' · 缺少工程/PCB' self.cbb_table.setItem(row, 2, QTableWidgetItem(status_text)) # Preflight touches each CBB's project and was previously run # synchronously in this GUI callback, making large libraries @@ -1144,11 +1390,81 @@ class MainWindow(QWidget): self.status_label.setText( f'已读取 {len(result.records)} 个 CBB,其中 Ready {ready_count} 个,' f'缺文件跳过 {len(self.skipped_names)} 个。{suffix}') + if result.directory_count is not None and not result.catalog_verified: + self.status_label.setText(f'目录发现 {result.directory_count} 项,原生记录数待复核。{suffix}') if recovery_view: self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。' '仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。') self._apply_filters() - self._start(read, loaded) + if self.catalog_reader is not None and not result.catalog_verified: + self._start_catalog(job, result, lease, mentor_path, loaded) + self._start(read, loaded, queued=False, job=job, metadata_only=True, + stale=lambda payload: self._close_path_lease(payload[2])) + + def _start_catalog(self, read_job, initial, lease, library, deliver): + from cbb_refresh_verify.models import CbbRecord, LibraryReadResult + context = BatchTaskContext(str(library), aliases=tuple(_library_path_keys(library, lease)), native_policy='external') + job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision, + lease=lease, requests=(), records={}, active=True, keep_session=False) + self._jobs[context.operation_id] = job + def reconcile(): + catalog = self.catalog_reader(Path(library), self.data_root/'catalog'/context.operation_id) + if _path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1: + raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。') + native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'} + directories = {record.name: record for record in initial.records} + names = tuple(sorted(native.keys() | directories.keys())) + try: + statuses = self.status_refresher(tuple(native), Path(library)) + except Exception: + statuses = {name:'UNAVAILABLE' for name in native} + self._publish_check_statuses(library, statuses, lease) + records, reasons = [], {} + for name in names: + source = ('both' if name in native and name in directories else + 'native_only' if name in native else 'directory_only') + reason = ('CATALOG_NOT_REGISTERED: 仅发现目录,原生目录未登记。' if name not in native else + preflight_skip_reason(Path(library), name) or '') + if name not in directories and not reason: + reason = 'PROJECT_MISSING: 原生记录缺少工程目录。' + if reason: reasons[name] = reason + records.append(CbbRecord(name, native[name].partition if name in native else directories[name].partition_name, + status=statuses.get(name,'UNKNOWN'), catalog_source=source, + status_source='authoritative' if name in native else 'unknown', missing_reason=reason)) + context.check_active() + result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native), + missing_project_count=sum(name in native for name in reasons), catalog_verified=True) + return result, reasons, lease, library, False + worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context)) + self._lifecycle_workers.add(worker) + def completed(payload): + if self._job_current(read_job): deliver(payload) + def failed(error): + if self._job_current(read_job): + self.status_label.setText(f'目录已显示;原生目录未确认:{error}') + worker.signals.succeeded.connect(completed) + worker.signals.failed.connect(failed) + worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job))) + self.pool.start(worker) + + def _execution_status_reader(self, operation_id, lease): + """Recheck registration once per submission and status at each admission.""" + catalog_reader, status_reader = self.catalog_reader, self.status_refresher + if catalog_reader is None: return None # Injected readers own their boundary. + evidence = self.data_root/'catalog-admission'/operation_id + registered = None + def read(names, library): + nonlocal registered + if registered is None: + catalog = catalog_reader(Path(library), evidence) + if (_path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1): + raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。') + registered = frozenset(entry.name for entry in catalog.entries if entry.partition == 'Logical-Physical') + statuses = dict(status_reader(tuple(name for name in names if name in registered), Path(library))) + statuses.update({name:'NOT_REGISTERED' for name in names if name not in registered}) + self._publish_check_statuses(library, statuses, lease) + return statuses + return read def _request(self, name): return VerifyRequest(Path(self.mentor_lmc_path or self.loaded_path), name, self.data_root/'evidence', @@ -1173,21 +1489,21 @@ class MainWindow(QWidget): from .backup_notice import MANUAL_BACKUP_NOTICE if self.busy or not self.loaded_path or self._native_backup_same_library() or not names: return - if QMessageBox.question(self, '确认批量校验', + if timed_prompt.question(self, '确认批量校验', f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{self.loaded_path}\n' f'将校验 {len(names)} 个可见非 READY CBB 并保存结果。确认继续?', - QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes: + QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes: self._run(names) def repair_icdb_all(self): if self.busy or not self.loaded_path: return names = self._maintenance_names() if not names: return - answer = QMessageBox.question(self, 'ICDB 批量检查', + answer = timed_prompt.question(self, 'ICDB 批量检查', f'当前中心库:{self.loaded_path}\n\n' f'将检查 {len(names)} 个可见非 READY CBB' f'{"(仅勾选项)" if self.selected_records() else ""}。\n' - '仅检查 ICDB 状态,不执行修复或回退。\n\n是否开始?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) + '仅检查 ICDB 状态,不执行修复或回退。\n\n是否开始?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if answer == QMessageBox.Yes: self._run(names, maintenance=True) @@ -1200,9 +1516,10 @@ class MainWindow(QWidget): _library_path_keys(library, lease or self.library_lease) & _library_path_keys(session.library, getattr(session, 'path_lease', None))) - def open_native_backup(self): + def open_native_backup(self, checked=False, *, mode='versions'): if self.busy or not self.loaded_path or self._native_backup_session is not None: return + if any(job.active and job.kind == 'native_session' for job in self._jobs.values()): return target = self._native_backup_target() if target is None: self.status_label.setText('请勾选一个非 READY CBB。') @@ -1210,74 +1527,101 @@ class MainWindow(QWidget): from cbb_refresh_verify.native_backup import launch_native_backup request = self._request(target.name) launcher = self.native_backup_launcher or launch_native_backup - self._global_icdb_run = False - self._reimport_offers = () - self.status_label.setText(f'正在打开 {request.block_name} 的版本与备份…') + job = self._new_job('native_session', library=request.lmc_file, targets=(target.name,)) paused_check = self.icdb_task if self._check_matches_library(request.lmc_file) else None + job.paused_check = paused_check if paused_check is not None: paused_check.pause(); paused_check.invalidate([request.block_name]) + self.status_label.setText(f'正在打开 {target.name} 的原生{ "修复工具" if mode == "repair" else "版本与备份" }…') def opened(session): - session.path_lease = self.library_lease + session.path_lease = job.lease + session.ui_job = job + job.keep_session = True self._native_backup_session = session + if self._closing: + if job.lease is not None: self._retain_path_lease(job.lease) + return self.native_backup_timer.start() - self.status_label.setText(f'正在打开 {session.block} 的原生备份窗口,请在其中选择版本。') - self.output.append(f'{session.block} · 原生版本与备份\n{session.job}') - self.busy = True; self._update() - self.stop.clear() - self.worker = ServiceWorker(self._queued_action(lambda: launcher(request))) - self.worker.signals.succeeded.connect(opened) - def failed(error): - self.status_label.setText(f'无法打开版本与备份:{error}') - if paused_check is not None: paused_check.resume() - self.worker.signals.failed.connect(failed) - self.worker.signals.finished.connect(self._finished) - self.pool.start(self.worker) + if self._job_current(job): + self.status_label.setText(f'{session.block} 的原生窗口已打开,请在其中手动操作。') + self.output.append(f'{session.block} · {mode}\n{session.job}') + self._update() + # Existing injected version launchers accept only the positional request. + diagnostic = self._diagnostic_evidence.get(target.name) if mode == 'repair' else None + def action(): + if diagnostic is not None: + diagnosis = json.loads(diagnostic.read_text('utf-8')) + database = diagnosis.get('database_path') + if not isinstance(database,str) or not database: + raise ValueError('诊断未绑定唯一数据库,请重新检查目标。') + return launcher(request, mode=mode, target_database=database) + return launcher(request, mode=mode) if mode != 'versions' else launcher(request) + self._start(action, opened, job=job, stale=opened) def _release_native_backup_session(self, session): - self._native_backup_session = None - if session.path_lease is not None and session.path_lease is not self.library_lease: + if self._native_backup_session is session: self._native_backup_session = None + job = getattr(session, 'ui_job', None) + if job is not None: + job.keep_session = False + self._finish_job(job) + elif session.path_lease is not None and session.path_lease is not self.library_lease: self._close_path_lease(session.path_lease) - if self._icdb_active(): self.icdb_task.resume() + self._update() def _poll_native_backup(self): session = self._native_backup_session - if session is None or self.busy or session.process.poll() is None: + if session is None or getattr(session, 'polling', False) or session.process.poll() is None: return + session.polling = True self.native_backup_timer.stop() + job = getattr(session, 'ui_job', None) + revision = self._view_revision + current = self._current_job same_library = self._native_backup_same_library() + context = BatchTaskContext(str(session.library)) + polling_foreground = not self.busy + if polling_foreground: + self.busy = True + self._update() def read_result(): - import json result = json.loads(session.job.with_name('result.json').read_text('utf-8')) - if (not self._native_backup_matches_library(result['library'], getattr(session, 'path_lease', None)) - or result['block'] != session.block): + aliases = _library_path_keys(session.library, session.path_lease) + if (not aliases & _library_path_keys(result.get('library'), session.path_lease) + or result.get('block') != session.block + or getattr(session,'operation_id','') and result.get('operation_id') != session.operation_id): raise ValueError('原生会话返回的工程身份不一致。') - refresh = (self._read_affected_records((session.block,), library=session.library) - if result.get('safe_to_continue') is True and same_library else None) - return result, refresh - def completed(payload): - result, refresh = payload + return result + def current_delivery(): + return (not self._closing and revision == self._view_revision and current is self._current_job + and same_library and (job is None or self._job_current(job))) + def completed(result): if result.get('safe_to_continue') is not True: unconfirmed(result.get('detail', '未取得会话释放结果。')) return + deliver = current_delivery() self._release_native_backup_session(session) - if refresh is not None: - self._apply_refreshed_records(refresh) - message = ('原生备份窗口已关闭。需要时可单独运行校验。' if result.get('status') == 'CLOSED' - else '原生备份操作未结束:' + result.get('detail', '请检查原生窗口。')) - self.status_label.setText(message) - self.output.append(f'{session.block} · {message}\n{session.job.with_name("result.json")}') - if same_library and session.block in self._row_by_name: - self.cbb_table.item(self._row_by_name[session.block], 3).setText(message) + if deliver: + message = ('原生窗口已关闭;恢复或修复结果仍需单独校验。' if result.get('status') == 'CLOSED' + else '原生操作未完成:'+str(result.get('detail') or result.get('status'))) + self.status_label.setText(message) + self.output.append(f'{session.block} · {result.get("status")}\n{session.job.with_name("result.json")}') + self.refresh_affected_records([session.block], callback=lambda _:self.status_label.setText(message)) def unconfirmed(error): - self.status_label.setText('原生窗口退出尚未确认,请关闭窗口后检查释放。') - self.output.append(f'{session.block} · 退出尚未确认:{error}\n{session.job}') - self.busy = True; self._update() - self.stop.clear() - self.worker = ServiceWorker(self._queued_action(read_result, library=session.library)) - self.worker.signals.succeeded.connect(completed) - self.worker.signals.failed.connect(unconfirmed) - self.worker.signals.finished.connect(self._finished) - self.pool.start(self.worker) + if session.path_lease is not None: self._retain_path_lease(session.path_lease) + if current_delivery(): + self.status_label.setText('原生窗口退出尚未确认,请检查释放。') + self.output.append(f'{session.block} · {error}\n{session.job}') + session.polling = False + worker = ServiceWorker(lambda:context.run(read_result, metadata_only=True)) + self._lifecycle_workers.add(worker) + worker.signals.succeeded.connect(completed) + worker.signals.failed.connect(unconfirmed) + worker.signals.finished.connect(lambda:self._lifecycle_workers.discard(worker)) + def finish_poll(): + if polling_foreground and revision == self._view_revision and current is self._current_job: + if not getattr(self, '_refreshing_records', False): self._finished() + worker.signals.finished.connect(finish_poll) + self.pool.start(worker) def restore_backup(self): if self.busy or not self.loaded_path or self._native_backup_same_library(): @@ -1286,15 +1630,35 @@ class MainWindow(QWidget): names = self._eligible_names(checked_only=bool(self.selected_records())) if not names: return - self.backup_dialog = BackupRecoveryDialog(names, self._backup_request, self) + requests = {name:self._request(name) for name in names} + job = self._new_job('recovery', targets=names) + def request(name): + if name not in requests: raise ValueError('目标不属于此恢复任务。') + if job.revision == self._view_revision: return self._backup_request(name) + return requests[name] + self.backup_dialog = BackupRecoveryDialog(names, request, self) + dialog = self.backup_dialog + self._dialogs.append(dialog) + dialog.ui_job = job + dialog.admit = lambda snapshot:self._admit_snapshot(job,snapshot) self.backup_dialog.native_queue = self.native_queue row = self.cbb_table.currentRow() if row >= 0 and self.cbb_table.item(row, 0).text() in names: self.backup_dialog.block_combo.setCurrentText(self.cbb_table.item(row, 0).text()) - self.backup_dialog.started.connect(self._backup_started) - self.backup_dialog.completed.connect(self._backup_completed) - self.backup_dialog.finished.connect(lambda _code: self._backup_dialog_closed()) - self.backup_dialog.setModal(True) + def started(name): + self._adopt_dialog_context(job, dialog) + if self._job_current(job): self._backup_started(name) + def completed(name, result): + job.submitted = False + if self._job_current(job): self._backup_completed(name, result) + else: self._stale_operation_results(job, [result]) + def closed(*_): + if self._job_current(job): self._backup_dialog_closed() + self._finish_job(job) + self.backup_dialog.started.connect(started) + self.backup_dialog.completed.connect(completed) + self.backup_dialog.finished.connect(closed) + self.backup_dialog.setWindowModality(Qt.NonModal) self.backup_dialog.show() def _backup_request(self, name): @@ -1339,8 +1703,8 @@ class MainWindow(QWidget): if not getattr(self, '_refreshing_records', False): self._finished() - def _run(self, names, *, maintenance=False): - if maintenance: return self._start_icdb_check(names) + def _run(self, names, *, maintenance=False, request_snapshot=None): + if maintenance: return self._start_icdb_check(names, request_snapshot=request_snapshot) if self.busy or not self.loaded_path: return if self._native_backup_same_library(): self.status_label.setText('请先关闭该库的版本与备份窗口。') @@ -1351,8 +1715,16 @@ class MainWindow(QWidget): self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。') self._update() return - requests = [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names] + requests = ([request for request in request_snapshot if request.block_name in names] if request_snapshot is not None + else [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names]) + if not requests: return library = requests[0].lmc_file + if any(job.active and job.kind == 'verify' and job.requests == tuple(requests) + and _path_key(job.context.library) == _path_key(library) for job in self._jobs.values()): return + job = self._new_job('verify', library=library, targets=names) + job.requests = tuple(requests) + job.records = {name: self._records_by_name[name] for name in names} + eligibility_reader = self._execution_status_reader(job.context.operation_id, job.lease) self._batch_requests = tuple(requests) self._batch_records = {name: self._records_by_name[name] for name in names} self._reimport_offers = () @@ -1365,48 +1737,58 @@ class MainWindow(QWidget): self.icdb_progress.setValue(0) self.icdb_progress.setFormat('已处理 %v / %m 个 CBB') self.icdb_phase.setText('准备检查…') - self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False) + self.recovery_path = None; self.recovery_button.setEnabled(False) self.output.clear(); self.status_label.setText( f'正在 ICDB 批量检查:共 {len(names)} 个 CBB' if maintenance else f'正在校验:共 {len(names)} 个 CBB') def action(): from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify verify = self.verifier or (lambda req: run_verify( - req, progress=lambda e: self.signals.event.emit(e), + req, progress=lambda e: self._emit_job(job, 'event', e), flag_reader=read_library_flag_if_available, - version_prompt=self.signals.version_choice.emit, stop=self.stop)) + version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop)) def verifier(req): + if eligibility_reader is not None: + statuses = eligibility_reader((req.block_name,), req.lmc_file) + self._publish_check_statuses(req.lmc_file, statuses, job.lease) + if statuses.get(req.block_name) == 'READY': + from cbb_refresh_verify.verify_runner import VerifyResult + return VerifyResult('SKIPPED', stderr='工程已为 READY,未执行校验。') + if statuses.get(req.block_name) == 'NOT_REGISTERED': + from cbb_refresh_verify.verify_runner import VerifyResult + return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。') if maintenance: - self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'}) + self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'}) return verify(req) - results = run_batch(requests, verifier=verifier, stop=self.stop, - item_executor=lambda req, action: self._queued_action(action, library=req.lmc_file)(), - progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, + results = run_batch(requests, verifier=verifier, stop=job.context.stop, context=job.context, + item_executor=lambda req, action: self._queued_action(action, library=req.lmc_file, job=job)(), + progress=lambda name, result: self._emit_job(job, 'event', {'block': name, 'stage': result.status, 'error_category': result.error_category, 'evidence': str(result.evidence_path or ''), 'detail': result.stderr or result.stdout})) report = None try: - report = write_batch_report(requests, results, self.data_root/'reports') + report = BatchTaskContext(str(library)).run(lambda: + write_batch_report(requests, results, self.data_root/'reports')) if maintenance: from cbb_refresh_verify.icdb_maintenance import write_maintenance_report write_maintenance_report(requests, results, report, ()) except Exception as error: - self.signals.event.emit({'stage': 'report_failed', 'detail': str(error)}) + self._emit_job(job, 'event', {'stage': 'report_failed', 'detail': str(error)}) affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED'] safe = all(result.safe_to_continue for result in results) - self.signals.batch_ready.emit((results, report)) + self._emit_job(job, 'batch_ready', (results, report)) refresh = None - if safe and not self.stop.is_set(): + if safe and not job.context.stop.is_set(): from cbb_refresh_verify.operation_queue import QueueCancelled try: - refresh = self._queued_action(lambda: self._read_affected_records(affected, library=library), - label='批次已结束,状态刷新', library=library)() + refresh = self._queued_action(lambda: self._read_affected_records(affected, library=library, lease=job.lease), + label='批次已结束,状态刷新', library=library, job=job)() except QueueCancelled: pass # Cancelling the refresh must not erase completed item results. return results, report, affected, refresh - self._start(action, self._batch_refreshed, queued=False) + self._start(action, self._batch_refreshed, queued=False, job=job, bounded=False) - def _read_affected_records(self, names, *, library): + def _read_affected_records(self, names, *, library, lease=None): """Worker-only read; never derive library state from action outcomes.""" import pythoncom pythoncom.CoInitialize() @@ -1415,7 +1797,7 @@ class MainWindow(QWidget): try: statuses = self.status_refresher(tuple(names), path) # Publish before yielding the native queue, ahead of Qt callbacks. - self._publish_check_statuses(path, statuses) + self._publish_check_statuses(path, statuses, lease) reasons = {name: reason for name in names if (reason := preflight_skip_reason(path, name))} return tuple(names), statuses, reasons, '' @@ -1489,11 +1871,21 @@ class MainWindow(QWidget): self._refreshing_records = False if callback: callback(records) - library = self.mentor_lmc_path or self.loaded_path - self._start(lambda: self._read_affected_records(targets, library=library), refreshed) + library, lease = self.mentor_lmc_path or self.loaded_path, self.library_lease + job = self._new_job('status', library=library, targets=targets, lease=lease) + self._start(lambda: self._read_affected_records(targets, library=library, lease=lease), refreshed, job=job) return True def _progress(self, event): + if isinstance(event, tuple): + if len(event) == 3: + revision, owner, event = event + if self._closing or revision != self._view_revision or owner is not self._current_job: return + library = self.mentor_lmc_path or self.loaded_path + if not library or not _library_path_keys(library,self.library_lease) & _library_path_keys(event.get('library')): return + else: + job, event = event + if not self._job_current(job): return from shiboken6 import isValid if not isValid(self) or not isValid(self.cbb_table): return @@ -1557,12 +1949,30 @@ class MainWindow(QWidget): if previous is not None: previous.close() summary = QMessageBox(self) + summary.view_revision = self._view_revision + summary.operation_job = self._current_job + summary.dismissed = False + summary.setWindowModality(Qt.NonModal) + summary.setStandardButtons(QMessageBox.Close) + arm_default(summary, summary.button(QMessageBox.Close)) setattr(self, attribute, summary) summary.setAttribute(Qt.WA_DeleteOnClose) summary.finished.connect(lambda _: self._forget_result_summary(summary)) return summary + def _summary_current(self, summary): + from shiboken6 import isValid + return (summary is not None and isValid(summary) and not self._closing and not summary.dismissed + and summary.view_revision == self._view_revision and summary.operation_job is self._current_job) + + def _bind_summary_action(self, summary, button, callback): + # QMessageBox closes ActionRole buttons before their own clicked slots; + # its buttonClicked signal still carries the live notification identity. + summary.buttonClicked.connect(lambda clicked:callback() + if clicked is button and self._summary_current(summary) else None) + def _forget_result_summary(self, summary): + summary.dismissed = True if getattr(self, '_batch_summary', None) is summary: self._reimport_summary_action = None self._residual_release_action = None @@ -1592,7 +2002,17 @@ class MainWindow(QWidget): else '批次已结束。') def _batch_done(self, outcome): + bound_job = None + if isinstance(outcome, tuple) and outcome and hasattr(outcome[0], 'context'): + job, outcome = outcome + bound_job = job + if job.lease is not None and any(not result.safe_to_continue for result in outcome[0]): + self._retain_path_lease(job.lease, hold_busy=self._job_current(job)) + if not self._job_current(job): return results, report = outcome[:2] + for request, result in zip(bound_job.requests if bound_job is not None else self._batch_requests, results): + if result.error_category == 'ICDB_REPAIR_REQUIRED' and result.evidence_path: + self._diagnostic_evidence[request.block_name] = result.evidence_path.parent/'diagnostics'/'icdb-recovery.json' failure_report = failure_report_path(report) if report is not None else '未写入' report = report if report is not None else '未写入' from cbb_refresh_verify.reimport_recovery import offers_reimport @@ -1600,10 +2020,10 @@ class MainWindow(QWidget): for req, result in zip(self._batch_requests, results) if req.maintenance and req.block_name in self._batch_records and offers_reimport(result)) self._batch_refreshed(outcome) - if self.library_lease is not None and any(not result.safe_to_continue for result in results): + if bound_job is None and self.library_lease is not None and any(not result.safe_to_continue for result in results): self._retain_path_lease(self.library_lease, hold_busy=True) for result in results: - if not result.safe_to_continue and result.evidence_path: + if result.evidence_path and result.status not in ('PASS', 'SKIPPED', 'CHECKED'): self.recovery_path = result.evidence_path.parent self.recovery_button.setEnabled(self.recovery_path.is_dir()) passed = sum(r.status == 'PASS' for r in results) @@ -1648,6 +2068,7 @@ class MainWindow(QWidget): status_text += guidance self.status_label.setText(status_text.replace('\n', ' ')); self.output.append(text) self.summary = self._new_result_summary('_batch_summary') + summary = self.summary self.summary.setWindowTitle('ICDB 批量检查结果' if self._global_icdb_run else 'CBB 校验结果') self.summary.setText(status_text) self.summary.setDetailedText(text) @@ -1658,20 +2079,21 @@ class MainWindow(QWidget): self._resume_batch = None if any(not result.safe_to_continue for result in results): self._residual_release_action = self.summary.addButton('查看残留并释放…', QMessageBox.ActionRole) - self._residual_release_action.clicked.connect(self.check_library_release) + self._bind_summary_action(summary, self._residual_release_action, self.check_library_release) self._residual_release_action.setEnabled(False) names = [req.block_name for req, result in zip(self._batch_requests, results) if result.status == 'SKIPPED'] if names: self._resume_batch = {'library': self._batch_requests[0].lmc_file, 'names': names, - 'maintenance': self._global_icdb_run, 'released': False} + 'maintenance': self._global_icdb_run, 'released': False, + 'revision':self._view_revision, + 'requests':tuple(req for req in self._batch_requests if req.block_name in names)} self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole) - self._resume_batch_action.clicked.connect(self._resume_released_batch) + self._bind_summary_action(summary, self._resume_batch_action, self._resume_released_batch) self._resume_batch_action.setEnabled(False) if self._reimport_offers: - self.summary.setStandardButtons(QMessageBox.Close) self._reimport_summary_action = self.summary.addButton('选择副本恢复…', QMessageBox.ActionRole) - self._reimport_summary_action.clicked.connect(self.reimport_failed) + self._bind_summary_action(summary, self._reimport_summary_action, self.reimport_failed) self._reimport_summary_action.setEnabled(False) # Enabled after the worker finishes. # Modeless notification: do not force activation or steal keyboard focus. from PySide6.QtCore import Qt @@ -1681,7 +2103,11 @@ class MainWindow(QWidget): def _show_version_choice(self, choice): from .pcb_restore_dialog import PcbRestoreDialog - if not self.busy or self.stop.is_set(): + job = None + if isinstance(choice, tuple): job, choice = choice + active = (job.active and self._jobs.get(job.context.operation_id) is job and not job.context.stop.is_set() + if job else self.busy and not self.stop.is_set()) + if self._closing or not active: choice.choose('cancel') return from ..pcb_open_consent import OpenChoice @@ -1696,13 +2122,19 @@ class MainWindow(QWidget): dialog_class = (WriteOwnerDialog if isinstance(choice,WriteOwnerChoice) else PcbOpenDialog if isinstance(choice,OpenChoice) else PcbRestoreDialog) self.version_dialog = dialog_class(choice,parent) + self.version_dialog.ui_job = job detail = ('等待确认库未被其他程序使用' if isinstance(choice,WriteOwnerChoice) else '等待读写打开确认' if isinstance(choice,OpenChoice) else '等待选择 PCB 恢复版本') - self.status_label.setText(f'{choice.block}:{detail}。') - self.icdb_phase.setText(f'{choice.block} · {detail}') + if job is None or self._job_current(job): + self.status_label.setText(f'{choice.block}:{detail}。') + self.icdb_phase.setText(f'{choice.block} · {detail}') self.version_dialog.show() def request_stop(self): + for job in tuple(self._jobs.values()): + job.context.cancel() + if job.kind == 'read': job.context.close(timeout_seconds=0) + self.native_queue.wake() if self._icdb_active(): self._stop_icdb_check() if not self.busy: return @@ -1726,7 +2158,8 @@ class MainWindow(QWidget): def _finished(self): if self._defer_mapping_finish(self._finished): return - if self.version_dialog is not None: + choice_job = getattr(self.version_dialog, 'ui_job', None) + if self.version_dialog is not None and (choice_job is None or not choice_job.active or choice_job.context.stop.is_set()): self.version_dialog.reject() self.version_dialog = None # Foreground completion must not erase an independent check's wait. @@ -1738,8 +2171,8 @@ class MainWindow(QWidget): def open_logs(self): try: - self.data_root.mkdir(parents=True, exist_ok=True) - os.startfile(str(self.data_root)) + (self.data_root/'logs').mkdir(parents=True, exist_ok=True) + os.startfile(str(self.data_root/'logs')) except Exception as error: self._display_error(error) @@ -1753,24 +2186,50 @@ class MainWindow(QWidget): event.accept() elif self._closing: event.ignore() - elif self._icdb_active(): - self._stop_icdb_check(); event.ignore() - elif self.busy: - self.request_stop(); event.ignore() else: self._closing = True + self._close_started = time.monotonic() + owned = {**self._retention_intents, **{id(job.lease):job.lease for job in self._jobs.values() + if job.lease is not None and (job.active or job.keep_session or job.context.snapshot()['pending'])}} + for dialog in self._dialogs: + lease = getattr(dialog,'path_lease',None) + if lease is not None and getattr(dialog,'busy',False): owned[id(lease)] = lease + if self._native_backup_session is not None: + lease = self._native_backup_session.path_lease + if lease is not None: owned[id(lease)] = lease + self._shutdown_leases.update(owned) + handoffs = [job.context.shutdown() for job in tuple(self._jobs.values())] + for context in tuple(self._lease_contexts): context.close(timeout_seconds=0) + for context in tuple(self._lifecycle_contexts): context.close(timeout_seconds=0) + self.native_queue.wake() + for task in self.icdb_tasks: + if task.active: task.cancel() + if self.version_dialog is not None: self.version_dialog.reject() + for name in ('management_dialog', 'backup_dialog', 'release_dialog'): + dialog = getattr(self, name, None) + if dialog is not None and getattr(dialog, 'busy', False): + dialog.stop.set() + context = getattr(dialog, 'context', None) + if context is not None: handoffs.append(context.shutdown()) self.busy = True; self._update() self.setWindowTitle('CBB 刷新校验 · 等待任务安全结束') self.status_label.setText('正在等待当前操作安全结束,完成后关闭。') self.close_wait_timer.start() - retained = None if self._native_backup_session is not None: self.native_backup_timer.stop() - retained = self._native_backup_session.path_lease lease, self.library_lease = self.library_lease, None def release(): - if retained is not None: retained.retain_for_recovery() - if lease is not None and lease is not retained: lease.close() + for retained in owned.values(): retained.retain_for_recovery() + if lease is not None and id(lease) not in owned: lease.close() + # Original worker/session registrations already precede native + # admission; this receipt records the UI shutdown, never release. + from cbb_refresh_verify.session_record import write_session_record + receipt = self.data_root/'shutdown'/('close-'+str(time.time_ns())+'.json') + receipt.parent.mkdir(parents=True, exist_ok=True) + write_session_record(receipt, + dict(status='UNCONFIRMED',safe_to_continue=False,task_scopes=handoffs, + retained_mappings=[dict(display=str(getattr(item,'display_path','')), + mentor=str(getattr(item,'mentor_path',''))) for item in owned.values()])) self._lease_action(release) self._close_when_idle() event.ignore() @@ -1781,10 +2240,10 @@ class MainWindow(QWidget): self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。') def _close_when_idle(self): - owners = [self, *self.icdb_tasks] + owners = [self, *self.icdb_tasks, *self._dialogs] for name in ('management_dialog', 'backup_dialog', 'release_dialog'): owners.append(getattr(self, name, None)) - active = bool(self.lifecycle_pool.activeThreadCount()) + active = bool(self._lifecycle_workers or self.lifecycle_pool.activeThreadCount() or self.lease_pool.activeThreadCount()) for owner in owners: try: pool = getattr(owner, 'pool', None) diff --git a/src/cbb_refresh_verify/ui/management_dialog.py b/src/cbb_refresh_verify/ui/management_dialog.py index 212ed5d..8f3ba4e 100644 --- a/src/cbb_refresh_verify/ui/management_dialog.py +++ b/src/cbb_refresh_verify/ui/management_dialog.py @@ -1,15 +1,17 @@ """Explicit preview and asynchronous, checkpointed CBB management batch.""" from dataclasses import replace from pathlib import Path -from threading import Event from PySide6.QtCore import QObject, QThreadPool, Signal, Qt from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel, QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout) +from shiboken6 import isValid from .workers import ServiceWorker from .backup_notice import MANUAL_BACKUP_NOTICE +from . import timed_prompt from ..management import run_management_batch +from ..operation_queue import BatchTaskContext RESULT_LABELS = { 'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验', @@ -58,12 +60,16 @@ class ManagementDialog(QDialog): evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs) self.busy = False self.executed = False - self.stop = Event() + self.context = BatchTaskContext(str(self.template.library), native_policy='external') + self.stop = self.context.stop + self.ui_job = None + self.admit = None + self.setWindowModality(Qt.NonModal) self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) self.signals = ManagementSignals(self) self.signals.progress.connect(self._progress) - if parent is not None and hasattr(parent, '_show_version_choice'): - self.signals.choice.connect(parent._show_version_choice) + self._choice_handler = getattr(parent, '_show_version_choice', None) + self.signals.choice.connect(self._choice) self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation]) self.resize(850, 450) self.table = QTableWidget(0, 4) @@ -95,7 +101,7 @@ class ManagementDialog(QDialog): self.execute_button = QPushButton('预览并确认执行…') self.execute_button.clicked.connect(self._execute) self.stop_button = QPushButton('当前项结束后停止'); self.stop_button.setEnabled(False) - self.stop_button.clicked.connect(self.stop.set) + self.stop_button.clicked.connect(lambda:self.context.stop_after_current.set()) self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject) layout = QVBoxLayout(self) layout.addWidget(QLabel(f'目标库:{self.template.library}')) @@ -151,10 +157,13 @@ class ManagementDialog(QDialog): try: if not requests: raise ValueError('请先选择来源工程。') + if hasattr(self.adapter, 'validate_source'): + for request in requests: + self.adapter.validate_source(request, probe_files=False) # Per-item input errors belong in batch results, so valid rows still run. if len({(r.partition.casefold(), r.name.casefold()) for r in requests}) != len(requests): raise ValueError('批次包含重复目标名称。') - except ValueError as error: + except (OSError, ValueError) as error: self.status_label.setText(str(error)); return preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests) description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update' @@ -163,50 +172,75 @@ class ManagementDialog(QDialog): if self.recovery_from: description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;' '导入失败时需要用备份恢复。请确认副本版本。') - answer = QMessageBox.question(self, '确认管理操作', + answer = timed_prompt.question(self, '确认管理操作', f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n' '确认继续执行?', QMessageBox.Yes | QMessageBox.No, - QMessageBox.No) + QMessageBox.Yes) if answer != QMessageBox.Yes: return + requests = [replace(request, check_previous_release=True) for request in requests] + if self.admit is not None and not self.admit(tuple(requests)): + self.status_label.setText('相同任务已提交,未重复执行。') + return + self.context = BatchTaskContext(str(self.template.library), targets=tuple(r.name for r in requests), native_policy='external') + context = self.context + self.stop = context.stop self.busy = True; self.executed = True self._enabled(False) self.before_execute.emit([r.name for r in requests]) def execute(): - choices={'version_prompt':self.signals.choice.emit} if self.runner is run_management_batch or self.recovery_from else {} - action = lambda: self.runner(requests, adapter=self.adapter, stop=self.stop, - progress=self.signals.progress.emit,**choices) - if self.native_queue is None: return action() + choices={'version_prompt':lambda choice:self._emit(context, 'choice',choice)} if self.runner is run_management_batch or self.recovery_from else {} + action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop, + progress=lambda event:self._emit(context, 'progress',event),**choices) + if self.native_queue is None: return context.run(action) from ..operation_queue import QueueCancelled from ..session_record import library_available, library_wait_reason try: if self.runner is run_management_batch: def item(request, action): - return self.native_queue.run(action, stop=self.stop, - ready=lambda: library_available(request.library), + return self.native_queue.run(action, stop=context.stop, context=context, wait_state=lambda: library_wait_reason(request.library), - waiting=lambda: self.signals.progress.emit({'stage': 'waiting_native_slot', + waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot', 'retained': not library_available(request.library), 'detail': library_wait_reason(request.library) or '已排队,等待当前原生操作结束'})) - return self.runner(requests, adapter=self.adapter, stop=self.stop, - progress=self.signals.progress.emit, item_executor=item, - version_prompt=self.signals.choice.emit) - return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit( + return self.runner(requests, adapter=self.adapter, stop=context.stop, + progress=lambda event:self._emit(context, 'progress',event), item_executor=item, + version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context) + return self.native_queue.run(action, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress', {'stage': 'waiting_native_slot', 'retained': not library_available(self.template.library), 'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}), - ready=lambda: library_available(self.template.library), wait_state=lambda: library_wait_reason(self.template.library)) except QueueCancelled as error: + from ..operation_queue import TaskHandoff from ..management import ManagementResult return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify, - 'complete', 'BLOCKED', True, str(error)) for r in requests] + 'complete', 'RECOVERY_REQUIRED' if isinstance(error,TaskHandoff) else 'CANCELLED', + not isinstance(error,TaskHandoff), str(error)) for r in requests] self.worker = ServiceWorker(execute) - self.worker.signals.succeeded.connect(self._result) - self.worker.signals.failed.connect(self._failed) - self.worker.signals.finished.connect(self._finished) + current = lambda: self.context if isValid(self) else None + self.worker.signals.succeeded.connect(context.guard_callback(self._result, current=current)) + self.worker.signals.failed.connect(context.guard_callback(self._failed, current=current)) + self.worker.signals.finished.connect(lambda:self._finished() if current() is context else None) self.pool.start(self.worker) + def _emit(self, context, signal, value): + if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set(): + if signal == 'choice': value.choose('cancel') + return + try: + delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)() + if not delivered and signal == 'choice': value.choose('cancel') + except RuntimeError: + if signal == 'choice': value.choose('cancel') + + def _choice(self, payload): + context, choice = payload + if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None: + choice.choose('cancel') + return + self._choice_handler((self.ui_job,choice) if self.ui_job else choice) + def _enabled(self, enabled): for widget in (self.table, self.sources_button, self.auto_verify, self.close_button): widget.setEnabled(enabled) @@ -214,6 +248,9 @@ class ManagementDialog(QDialog): self.stop_button.setEnabled(not enabled) def _progress(self, event): + if isinstance(event, tuple): + context, event = event + if context is not self.context or not self.busy: return stage = str(event.get('stage', '')) self.release_wait_button.setVisible(stage == 'waiting_native_slot' and bool(event.get('retained'))) text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}' @@ -270,6 +307,6 @@ class ManagementDialog(QDialog): def closeEvent(self, event): if self.busy: - self.stop.set(); event.ignore() + self.context.stop_after_current.set(); event.ignore() else: super().closeEvent(event) diff --git a/src/cbb_refresh_verify/ui/pcb_open_dialog.py b/src/cbb_refresh_verify/ui/pcb_open_dialog.py index feb23a9..897f74a 100644 --- a/src/cbb_refresh_verify/ui/pcb_open_dialog.py +++ b/src/cbb_refresh_verify/ui/pcb_open_dialog.py @@ -1,4 +1,5 @@ from PySide6.QtWidgets import QMessageBox +from .timed_prompt import arm_default class PcbOpenDialog(QMessageBox): @@ -13,9 +14,11 @@ class PcbOpenDialog(QMessageBox): self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole) self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole) self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole) - self.setDefaultButton(self.cancel_button) + self.setDefaultButton(self.skip_button) self.setEscapeButton(self.cancel_button) self.setModal(True) self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else - 'skip' if b is self.skip_button else 'cancel')) + 'skip' if b is self.skip_button else 'cancel', + origin=self.property('selectionOrigin') or 'user')) self.finished.connect(lambda _: choice.choose('cancel')) + arm_default(self, self.skip_button) diff --git a/src/cbb_refresh_verify/ui/pcb_restore_dialog.py b/src/cbb_refresh_verify/ui/pcb_restore_dialog.py index bb3c57b..d413598 100644 --- a/src/cbb_refresh_verify/ui/pcb_restore_dialog.py +++ b/src/cbb_refresh_verify/ui/pcb_restore_dialog.py @@ -1,5 +1,6 @@ -"""Show the native version dates without preselecting a recovery version.""" +"""Prefer the authorized last manually saved version after a visible countdown.""" from PySide6.QtWidgets import QMessageBox +from .timed_prompt import arm_default class PcbRestoreDialog(QMessageBox): @@ -14,7 +15,7 @@ class PcbRestoreDialog(QMessageBox): '原生程序检测到上次异常退出,需要选择 PCB 恢复版本。\n' f'最后手动保存:{manual["date"]}\n自动保存:{auto["date"]}\n\n' '选择历史版本可能丢失此版本之后的修改。选择后继续校验、保存和状态确认;恢复版本仍需核对。' - '\n取消将停止本项并保留原生现场,不自动选取版本。') + '\n默认选择最后手动保存;该版本不可用时取消本项。') self.manual_button = self.addButton(f'最后手动保存({manual["date"]})', QMessageBox.ActionRole) self.auto_button = self.addButton(f'自动保存({auto["date"]})', QMessageBox.ActionRole) self.manual_button.setEnabled(manual['enabled']) @@ -25,7 +26,9 @@ class PcbRestoreDialog(QMessageBox): self.buttonClicked.connect(self._chosen) self.finished.connect(lambda _: choice.choose('cancel')) self.setModal(True) + arm_default(self, self.manual_button if manual['enabled'] else self.cancel_button) def _chosen(self, button): self.choice.choose('last_user_saved' if button is self.manual_button else - 'autosave' if button is self.auto_button else 'cancel') + 'autosave' if button is self.auto_button else 'cancel', + origin=self.property('selectionOrigin') or 'user') diff --git a/src/cbb_refresh_verify/ui/residual_release_dialog.py b/src/cbb_refresh_verify/ui/residual_release_dialog.py index fb601d1..9482ab6 100644 --- a/src/cbb_refresh_verify/ui/residual_release_dialog.py +++ b/src/cbb_refresh_verify/ui/residual_release_dialog.py @@ -2,11 +2,14 @@ from pathlib import Path from threading import Event -from PySide6.QtCore import QThreadPool, Signal +from PySide6.QtCore import QThreadPool, Signal, Qt from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox) from .workers import ServiceWorker +from .timed_prompt import arm_default +from . import timed_prompt +from ..operation_queue import BatchTaskContext from ..residual_sessions import force_block_reason, release_targets_complete @@ -22,10 +25,12 @@ class ResidualReleaseDialog(QDialog): self.release_finalizer = None self.busy = False self.stop = Event() + self.context = None + self._workers = set() self._refresh_after = False self.pool = QThreadPool(self) self.setWindowTitle('释放残留会话') - self.setModal(True) + self.setWindowModality(Qt.NonModal) self.resize(1040, 400) layout = QVBoxLayout(self) self.message = QLabel('正在检查当前库关联的会话…') @@ -63,7 +68,9 @@ class ResidualReleaseDialog(QDialog): self.table.itemSelectionChanged.connect(self._update_prompt) self.refresh() - def _start(self, action, completed): + def _start(self, action, completed, *, metadata_only=False): + context = BatchTaskContext(str(self.library)) + self.context, self.stop = context, context.stop self.busy = True self.confirm_button.setEnabled(False) self.refresh_button.setEnabled(False) @@ -71,10 +78,12 @@ class ResidualReleaseDialog(QDialog): self.force_button.setEnabled(False) self.cancel_native_button.setEnabled(False) self.close_button.setText('停止释放') - self.worker = ServiceWorker(action) - self.worker.signals.succeeded.connect(completed) - self.worker.signals.failed.connect(lambda error: self.message.setText(str(error))) - self.worker.signals.finished.connect(self._finished) + self.worker = ServiceWorker(lambda:context.run(action, metadata_only=metadata_only)) + worker = self.worker + self._workers.add(worker) + self.worker.signals.succeeded.connect(context.guard_callback(completed, current=lambda:self.context)) + self.worker.signals.failed.connect(context.guard_callback(lambda error: self.message.setText(str(error)), current=lambda:self.context)) + self.worker.signals.finished.connect(lambda:(self._workers.discard(worker), self._finished() if self.context is context else None)) self.pool.start(self.worker) def _finished(self): @@ -128,6 +137,9 @@ class ResidualReleaseDialog(QDialog): details.extend(c.get('text', '') for c in window.get('children', []) if c.get('class') == 'Static') box.setDetailedText('\n'.join(details)) + box.setWindowModality(Qt.NonModal) + box.setStandardButtons(QMessageBox.Close) + arm_default(box, box.button(QMessageBox.Close)) box.show() def cancel_native(self): @@ -136,13 +148,13 @@ class ResidualReleaseDialog(QDialog): if row < 0: return session = self.plan['sessions'][row] if not session.get('cancel_prompt'): return - answer = QMessageBox.question(self, '请求原生取消', + answer = timed_prompt.question(self, '请求原生取消', f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n' '取消后的工程状态仍需核对;不会强制结束进程。', - QMessageBox.Yes | QMessageBox.No, QMessageBox.No) + QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if answer != QMessageBox.Yes: return from cbb_refresh_verify.residual_sessions import request_native_cancel - self.before_release.emit(); self.stop.clear() + self.before_release.emit(); self.stop = Event() def execute(): action = lambda: self._finalize_release_result( request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop)) @@ -187,9 +199,9 @@ class ResidualReleaseDialog(QDialog): session = self.plan['sessions'][row] prompt = session.get('prompt') if not prompt: return - choice = QMessageBox.question(self, '关闭工程前保存', prompt['text']+ + choice = timed_prompt.question(self, '关闭工程前保存', prompt['text']+ '\n\n是:保存后关闭;否:放弃未保存更改;取消:保留会话。', - QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel) + QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Yes) code = {QMessageBox.Yes: 6, QMessageBox.No: 7, QMessageBox.Cancel: 2}[choice] from cbb_refresh_verify.residual_sessions import answer_save_question self._start(lambda: answer_save_question(session, code), @@ -226,14 +238,14 @@ class ResidualReleaseDialog(QDialog): states.update({str(Path(row['path']).absolute()).casefold(): row for row in discover_sessions(self.evidence_dir.parent, library=library)}) return {**plan, 'runtime_sessions': list(states.values())} - self._start(inspect, ready) + self._start(inspect, ready, metadata_only=True) def force_release(self): if self.busy or not self.plan or not self.plan['sessions']: return targets = [r for r in self.plan['sessions'] if not force_block_reason(r)] if not targets: return names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets) - answer = QMessageBox.warning(self, '强制结束客户端', + answer = timed_prompt.warning(self, '强制结束客户端', '仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。' '\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+ '\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel) @@ -242,7 +254,7 @@ class ResidualReleaseDialog(QDialog): def confirm_release(self, checked=False, *, force=False): if self.busy or self.plan is None: return from cbb_refresh_verify.library_lock import release_residual_sessions - self.stop.clear() + self.stop = Event() plan = self.plan self.before_release.emit() self.message.setText('正在逐项释放,请稍候…') diff --git a/src/cbb_refresh_verify/ui/timed_prompt.py b/src/cbb_refresh_verify/ui/timed_prompt.py new file mode 100644 index 0000000..1cbcaf1 --- /dev/null +++ b/src/cbb_refresh_verify/ui/timed_prompt.py @@ -0,0 +1,98 @@ +"""Visible, one-shot defaults for confirmation prompts in unattended batches.""" +from math import ceil +import logging + +from PySide6.QtCore import QElapsedTimer, QEvent, QObject, QTimer, Slot +from PySide6.QtWidgets import QMessageBox + +DEFAULT_TIMEOUT_MS = 3000 + + +class _Countdown(QObject): + def __init__(self, box, button): + super().__init__(box) + self.box, self.button = box, button + self.label = button.text() + self.duration = DEFAULT_TIMEOUT_MS + self.elapsed = QElapsedTimer() + self.timer = QTimer(self) + self.timer.setInterval(50) + self.timer.timeout.connect(self.tick) + self.done = False + box.setDefaultButton(button) + box.buttonClicked.connect(self.stop) + box.finished.connect(self.stop) + box.installEventFilter(self) + if box.isVisible(): + self.start() + + @Slot() + def start(self): + if self.done: + return + self.elapsed.start() + self.timer.start() + self.button.setText(f'{self.label}({ceil(self.duration / 1000)} 秒)') + + def eventFilter(self, watched, event): + if event.type() == QEvent.Show: + self.start() + elif event.type() in (QEvent.Hide, QEvent.Close): + self.timer.stop() + return False + + @Slot() + def stop(self): + self.done = True + self.timer.stop() + from shiboken6 import isValid + if isValid(self.button): self.button.setText(self.label) + + @Slot() + def tick(self): + if self.done or not self.box.isVisible(): + self.timer.stop() + return + remaining = self.duration - self.elapsed.elapsed() + if remaining > 0: + self.button.setText(f'{self.label}({ceil(remaining / 1000)} 秒)') + return + self.timer.stop() + self.done = True + if not self.button.isEnabled(): + self.box.setProperty('selectionOrigin', 'timeout_default') + self.box.reject() + return + self.box.setProperty('selectionOrigin', 'timeout_default') + self.button.click() + + +def arm_default(box, button): + countdown = _Countdown(box, button) + box._default_countdown = countdown + return countdown + + +def _ask(icon, parent, title, text, buttons, default): + box = QMessageBox(icon, title, text, buttons, parent) + arm_default(box, box.button(default)) + try: + result = QMessageBox.StandardButton(box.exec()) + owner = parent + while owner is not None and getattr(owner, 'logging_context', None) is None: + owner = owner.parentWidget() + context = getattr(owner, 'logging_context', None) + logger = context.logger if context is not None else logging.getLogger('cbb_refresh_verify') + logger.info('prompt_decision title=%s result=%s origin=%s', title, result.name, + box.property('selectionOrigin') or 'user') + return result + finally: + box.deleteLater() + + +def question(parent, title, text, buttons, default): + return _ask(QMessageBox.Question, parent, title, text, buttons, default) + + +def warning(parent, title, text, buttons, default): + return _ask(QMessageBox.Warning, parent, title, text, buttons, default) diff --git a/src/cbb_refresh_verify/ui/write_owner_dialog.py b/src/cbb_refresh_verify/ui/write_owner_dialog.py index 236e3b1..6983901 100644 --- a/src/cbb_refresh_verify/ui/write_owner_dialog.py +++ b/src/cbb_refresh_verify/ui/write_owner_dialog.py @@ -1,4 +1,5 @@ from PySide6.QtWidgets import QMessageBox +from .timed_prompt import arm_default class WriteOwnerDialog(QMessageBox): @@ -15,9 +16,11 @@ class WriteOwnerDialog(QMessageBox): self.continue_button = self.addButton('已确认未使用此库,继续', QMessageBox.ActionRole) self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole) self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole) - self.setDefaultButton(self.cancel_button) + self.setDefaultButton(self.skip_button) self.setEscapeButton(self.cancel_button) self.setModal(True) self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else - 'skip' if b is self.skip_button else 'cancel')) + 'skip' if b is self.skip_button else 'cancel', + origin=self.property('selectionOrigin') or 'user')) self.finished.connect(lambda _: choice.choose('cancel')) + arm_default(self, self.skip_button) diff --git a/src/cbb_refresh_verify/verify_runner.py b/src/cbb_refresh_verify/verify_runner.py index 0a63eae..005951c 100644 --- a/src/cbb_refresh_verify/verify_runner.py +++ b/src/cbb_refresh_verify/verify_runner.py @@ -230,7 +230,7 @@ def _run_process(command, timeout_seconds, cwd, *, evidence_root=None): return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root) -def _stop_worker(process, *, timeout=5): +def _stop_worker(process, *, timeout=5, wait_for_native_write=True): """Request stop without interrupting a possibly unreturned native call.""" try: if hasattr(process, 'request_stop'): @@ -243,7 +243,8 @@ def _stop_worker(process, *, timeout=5): process.wait(timeout=timeout) except Exception: pending = getattr(process, 'native_write_pending', lambda: False)() - if pending is not False and not getattr(process, '_stop_wait_complete', False): + wait_required = wait_for_native_write() if callable(wait_for_native_write) else wait_for_native_write + if wait_required and pending is not False and not getattr(process, '_stop_wait_complete', False): from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS try: process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout)) @@ -412,6 +413,42 @@ def phase_for_event(event, current=None): return mapping.get(stage, current or DialogPhase.PCB_STARTING) +def _diagnostic_close_event(job, event, target_pid): + close_id = event.get('close_id') + return (job.get('diagnostic_only') is True and event.get('stage') == 'diagnostic_close_requested' + and target_pid is not None and event.get('pcb_pid') == target_pid + and type(event.get('hwnd')) is int and event['hwnd'] > 0 + and isinstance(close_id, str) and len(close_id) == 32 and all(c in '0123456789abcdef' for c in close_id) + and bool(job.get('operation_id')) and event.get('operation_id') == job['operation_id'] + and all(job.get(key) and event.get(key) == job[key] for key in ('project', 'pcb', 'desktop'))) + + +def _acknowledge_diagnostic_close(job, event, stop): + from .operation_queue import check_active + check_active() + if stop is not None and stop.is_set() or Path(job['cancel_signal']).exists(): + raise InterruptedError('VERIFY_CANCELLED: diagnostic handoff cancelled') + ack = Path(job['root'])/'diagnostic-close-ack.json' + pending = ack.with_suffix('.pending') + pending.write_text(json.dumps({key: event[key] for key in + ('pcb_pid', 'hwnd', 'operation_id', 'desktop', 'project', 'pcb', 'close_id')}), encoding='utf-8') + check_active() + if stop is not None and stop.is_set() or Path(job['cancel_signal']).exists(): + raise InterruptedError('VERIFY_CANCELLED: diagnostic handoff cancelled') + pending.replace(ack) + + +def _close_intent_after_poll(job, events, offset, target_pid): + if not job.get('diagnostic_only') or not events.exists(): return None + with events.open(encoding='utf-8') as stream: + stream.seek(offset) + for line in stream: + try: event = json.loads(line) + except json.JSONDecodeError: break + if _diagnostic_close_event(job, event, target_pid): return event + return None + + def classify_verify_dispatch(*, verify_invoked, invoke_returned, target_pid, observation): """Classify a returned Verify command that never started its PCB. @@ -545,14 +582,59 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, l def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None, - dialog_supervisor_factory=None, version_prompt=None, stop=None): - # Cover contents checking, native work and final state reads with one - # session-wide mutex. The worker-stage lock below is reentrant on Windows. - import win32event, win32con + dialog_supervisor_factory=None, version_prompt=None, stop=None, context=None, + admission_timeout_seconds=10): + from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop + if stop is not None and stop.is_set() or context is not None and context.stop.is_set(): + return VerifyResult('CANCELLED', stderr='已取消,未启动原生操作。', safe_to_continue=True) + options = dict(progress=progress, flag_reader=flag_reader, process_runner=process_runner, + port_check=port_check, dialog_supervisor_factory=dialog_supervisor_factory, + version_prompt=version_prompt) + bound = current_context() + if bound is None: + # Management may call Verify while holding a same-thread lease. Do not + # transfer that transaction to a different thread. + import threading + from .library_lock import _guard, _owners + with _guard: + nested = any(v['thread'] == threading.get_ident() and v['depth'] > 0 + for v in _owners.values()) + if not nested: + from .operation_queue import request_library_keys + bound = context or BatchTaskContext(library=str(request.lmc_file), + aliases=tuple(sorted(request_library_keys(request))), targets=(request.block_name,)) + try: + return bound.run(lambda: run_verify(request, stop=stop, **options), + stop=stop, timeout_seconds=admission_timeout_seconds) + except TaskHandoff as error: + result = _handoff_verify_result(error) + _notify_progress(bound.guard_callback(progress) if progress else None, + dict(stage='task_handoff', operation_id=bound.operation_id, + library=bound.library, status=result.status, resource_scope=error.scope)) + return result + if bound is not None and progress is not None: + options['progress'] = bound.guard_callback(progress) + return _run_verify_task(request, stop=task_stop(stop), **options) + + +def _handoff_verify_result(error): + known = error.result if isinstance(error.result, VerifyResult) else None + result = known or VerifyResult('CANCELLED' if error.cancelled else 'TIMEOUT') + return replace(result, status='FAIL' if result.status == 'PASS' else result.status, + stderr=result.stderr or str(error), safe_to_continue=False, + error_stage=result.error_stage or 'admission_or_finalization', + error_category=result.error_category or 'TASK_HANDOFF', + release_proof=dict(lease_state='PENDING', resource_scope=error.scope, + blocked_resources=error.scope.get('resources', []))) + + +def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None, + dialog_supervisor_factory=None, version_prompt=None, stop=None): + # Admission/finalization keep only the library lease. Native launch paths + # acquire the host channel after slow metadata has returned. + from .operation_queue import check_active from .com_runtime import initialize_com, uninitialize_com initialized = initialize_com() - mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') - acquired = False library_lock = None previous_release = None release_confirmed = True @@ -563,11 +645,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, from .library_lock import _supervisor_alive return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients) try: - acquired = win32event.WaitForSingleObject(mutex, 0) in ( - win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) - if not acquired: - return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。', - safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY') + check_active() if request.maintenance: from .maintenance_entry import run_icdb_check return run_icdb_check(request, progress=progress, stop=stop) @@ -576,10 +654,13 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, if Path(request.lmc_file).is_file(): try: previous_release = recheck_previous_release(request.lmc_file, - Path(request.evidence_dir)/'previous-release', block_name=request.block_name, progress=progress) + Path(request.evidence_dir)/'previous-release', block_name=request.block_name, + progress=progress, stop=stop) + check_active() library_lock = LibraryLock(request.lmc_file, checkpoint=False, safe_to_release=clients_released) library_lock.__enter__() + check_active() except LibraryBusy as error: return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE') except (OSError, ValueError, RuntimeError, pywintypes.error) as error: @@ -691,14 +772,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, if library_lock is not None: library_lock.__exit__(None, None, None) finally: - if acquired: - win32event.ReleaseMutex(mutex) - mutex.Close() uninitialize_com(initialized) def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None, dialog_supervisor_factory=None, version_prompt=None, stop=None): + from .operation_queue import remember_result timing = RunTimings() result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader, process_runner=process_runner, port_check=port_check, @@ -722,6 +801,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_ result = replace(result, status='FAIL', stderr='原生会话或自动化客户端尚未退出。') except (OSError, ValueError, KeyError): pass + remember_result(result) if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP', 'CANCELLED'} and result.evidence_path: job_path = result.evidence_path.with_name('request.json') if job_path.is_file(): @@ -735,13 +815,13 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_ finally: timing.end('failure_diagnostics') if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}: - from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_session_loss, recovery_detail - recovery = parse_session_loss(result.stderr) + from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_recovery_request, recovery_detail + recovery = parse_recovery_request(result.stderr) if recovery is None and result.evidence_path: try: saved = json.loads(result.evidence_path.with_name('diagnostics').joinpath( 'icdb-recovery.json').read_text('utf-8')) - recovery = parse_session_loss(saved.get('native_message', '')) + recovery = parse_recovery_request(saved.get('native_message', '')) except (OSError, ValueError, AttributeError): pass if recovery or ERROR_CODE.casefold() in result.stderr.casefold(): @@ -764,6 +844,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_ if result.status not in {"PASS", "SKIPPED"} else ""), error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution') if result.status not in {"PASS", "SKIPPED"} else "")) + remember_result(result) if result.evidence_path: _write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)}) _write_optional_evidence(result.evidence_path.with_name('performance.json'), { @@ -819,7 +900,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run except Exception: # Cleanup must never hide or change the verification result. pass - return replace(result, evidence_path=result_path) + from .operation_queue import remember_result + return remember_result(replace(result, evidence_path=result_path)) if stop is not None and stop.is_set(): return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。')) @@ -843,7 +925,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run 'detail': ' '.join(command)}) timing.begin('content_check') try: - exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent) + from .operation_queue import native_channel + with native_channel(read_only=True): + exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent) finally: timing.end('content_check') combined = '\n'.join(part for part in (stdout, stderr) if part) @@ -886,7 +970,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run 'cancel_signal': str(root/'cancel-worker.signal'), 'start_gate': str(root/'start-worker.signal')} job.update(operation_id=root.name, operation='verify', library=str(request.lmc_file), - block=request.block_name, session_record_path=str(root/'session.json')) + block=request.block_name, session_record_path=str(root/'session.json'), start_gate_protocol='event-v1') from .session_record import process_identity job['supervisor_identity'] = process_identity(os.getpid()) consent = None @@ -902,11 +986,22 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run except Exception as error: return finish(VerifyResult('FAIL', stderr=str(error))) events = root/'events.jsonl' + prewrite_eligible = not (request.diagnostic_only or request.interactive_input or request.native_lm_verify or consent) + def startup_phase(stage,**facts): + record={k:job[k] for k in ('operation_id','project','pcb','desktop')} + with events.open('a',encoding='utf-8') as stream: + stream.write(json.dumps(dict(stage=stage,**record,**facts))+'\n') + def before_dialog_action(snapshot,action): + name=action.get('action') if isinstance(action,dict) else action + if name not in ('dismiss_tip','accept_license','decline_database_log'): + startup_phase('startup_supervisor_write_possible',action=name,pid=snapshot.pid,hwnd=snapshot.hwnd) offset = 0 target_pid = None + diagnostic_closing = False launcher_pid = None lm_pid = None verify_invoked = False + lm_dispatch_deadline = None invoke_returned = False pcb_baseline = set() last_observation = 0.0 @@ -915,17 +1010,21 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run from .desktop_worker import DesktopWorker from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend from .dialog_models import DialogPhase - import win32event, win32con - mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') - lock_status = win32event.WaitForSingleObject(mutex, 0) - if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED): - mutex.Close() - return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行;本次未启动。', - safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY')) + from .operation_queue import TaskHandoff, check_active, native_channel + check_active() worker_launch_attempted = False + native = native_channel() + phase_entered = False + def end_native_phase(): + nonlocal phase_entered + if phase_entered: + native.__exit__(None, None, None) + phase_entered = False try: + if prewrite_eligible:startup_phase('startup_supervisor_no_write') timing.begin('worker_setup') with (root/'worker.log').open('w', encoding='utf-8') as log: + check_active() worker_launch_attempted = True if request.interactive_input: process = DesktopWorker( @@ -949,14 +1048,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run from .dialog_rules import default_rules_path, load_rules dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop) dialog_supervisor = DialogSupervisor( - AgentDialogBackend(dialog_agent, pids=lambda: { + AgentDialogBackend(dialog_agent, before_action=before_dialog_action if prewrite_eligible else None, pids=lambda: { int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}), - rules=load_rules(default_rules_path()), + rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only), ) else: dialog_supervisor = DialogSupervisor(Win32DialogBackend( lambda: ({value for value in (target_pid, lm_pid) if value is not None}), - desktop=process.desktop, + desktop=process.desktop,before_action=before_dialog_action if prewrite_eligible else None, )) else: dialog_supervisor = dialog_supervisor_factory( @@ -965,7 +1064,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run ) if stop is not None and stop.is_set(): raise InterruptedError('VERIFY_CANCELLED: 启动已取消,未启动 PCB') - Path(job['start_gate']).touch() + check_active() + try: + native.__enter__() + phase_entered = True + except RuntimeError as error: + return finish(VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False, + error_category='NATIVE_CHANNEL_BUSY')) + from .operation_queue import commit_worker_start + commit_worker_start(process, job) while process.poll() is None: if stop is not None and stop.is_set(): save_markers = timing._save_markers @@ -974,7 +1081,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run '已请求停止,等待当前原生操作返回') _notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name, 'detail': detail}) - _stop_worker(process) + from .failed_session import cancelled_prewrite_startup + _stop_worker(process, wait_for_native_write=False if request.diagnostic_only else + lambda:cancelled_prewrite_startup(job,target_pid) is None) return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。', safe_to_continue=False, error_stage=phase.value)) if events.exists(): @@ -986,10 +1095,16 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run except json.JSONDecodeError: break timing.record(event) + if _diagnostic_close_event(job, event, target_pid): + _acknowledge_diagnostic_close(job, event, stop) + diagnostic_closing = True if event.get('pcb_pid'): target_pid = event['pcb_pid'] if event.get('launcher_pid'): launcher_pid = event['launcher_pid'] if event.get('lm_pid'): lm_pid = event['lm_pid'] stage = event.get('stage') + if stage == 'lm_launch' and lm_dispatch_deadline is None: + from .mentor_adapter import lm_dispatch_timeout_seconds + lm_dispatch_deadline = (event.get('monotonic_seconds') or time.monotonic()) + lm_dispatch_timeout_seconds(request.timeout_seconds) if stage == 'verify_invoke': verify_invoked = True if stage == 'verify_invoke_returned': invoke_returned = True if stage == 'pcb_baseline': pcb_baseline = set(event.get('pids', ())) @@ -1021,7 +1136,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run except Exception as error: observation = {'error': str(error)} last_post_verify_observation = observation - if dialog_agent is not None and target_pid is None: + if diagnostic_closing: + # The exact diagnostic worker owns its bounded close/No sequence. + from .dialog_supervisor import DialogPollResult + dialog_result = DialogPollResult(activity=False) + elif dialog_agent is not None and target_pid is None: # The Library Manager Verify route starts its own window # before it launches Expedition PCB. Do not feed that # large MFC main window to the PCB dialog probe; it can @@ -1039,6 +1158,13 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run dialog_result = dialog_supervisor.poll() else: dialog_result = dialog_supervisor.poll() + if not diagnostic_closing: + intent = _close_intent_after_poll(job, events, offset, target_pid) + if intent is not None: + _acknowledge_diagnostic_close(job, intent, stop) + diagnostic_closing = True + from .dialog_supervisor import DialogPollResult + dialog_result = DialogPollResult(activity=False) if (version_prompt is not None and consent is None and dialog_agent is not None and not request.diagnostic_only and not request.native_lm_verify and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED' @@ -1107,7 +1233,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run error_stage=phase.value, safe_to_continue=False, )) - if deadline.expired(): + if deadline.expired() or (lm_dispatch_deadline is not None and target_pid is None + and time.monotonic() >= lm_dispatch_deadline): _write_failure_windows(root, latest_snapshots) # Stop automation without killing PCB/iCDB during a write. _write_process_tree(root, process, target_pid) @@ -1123,7 +1250,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run target_pid=target_pid, observation=last_post_verify_observation, ) - _stop_worker(process) + _stop_worker(process, wait_for_native_write=not request.diagnostic_only) if dispatch_failure is not None: status, detail = dispatch_failure if progress: @@ -1136,6 +1263,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run return finish(VerifyResult(status, stderr=detail, safe_to_continue=False)) return finish(VerifyResult('TIMEOUT', stderr='操作超时,当前项未完成。', error_stage=phase.value, safe_to_continue=False)) time.sleep(.2) + end_native_phase() # Exact worker exit precedes all optional outcome/evidence I/O. worker_result = root/'outcome.json' if not worker_result.exists(): return finish(VerifyResult('FAIL', stderr=f'执行器异常退出 ({process.returncode}),见 worker.log', safe_to_continue=False)) @@ -1145,7 +1273,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run result = VerifyResult(**outcome) except Exception as error: if 'process' in locals() and process.poll() is None: - _stop_worker(process) + _stop_worker(process, wait_for_native_write=not request.diagnostic_only) launch_release = getattr(error, 'worker_launch_release', None) if 'process' not in locals() else None if not worker_launch_attempted: launch_release = {'process_created': False, 'worker_exited': True, @@ -1164,7 +1292,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run finally: close_errors = [] worker_exited = False + observer_started = False automation_release = {'safe_to_continue': False} + if 'process' not in locals() or process.poll() is not None or getattr(process, 'session_record_path', None): + # A gated worker owns its writer barrier and inherited sidecar. + # Parent admission must not block controls needed for its exit. + end_native_phase() if 'dialog_agent' in locals() and dialog_agent is not None: try: dialog_agent.close() @@ -1174,20 +1307,27 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run try: worker_exited = process.poll() is not None if not worker_exited: - worker_exited = _stop_worker(process) + worker_exited = _stop_worker(process, wait_for_native_write=not request.diagnostic_only) if hasattr(process, 'automation_release_state'): automation_release = process.automation_release_state() else: automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []} - if worker_exited: - process.close() - elif getattr(process, 'session_record_path', None): + if not worker_exited and getattr(process, 'session_record_path', None): from .session_record import handoff_session handoff_session(process.session_record_path, evidence_root=root, process=process, progress=lambda state: _notify_progress(progress, {'stage': 'session_observation', 'block': request.block_name, **state})) + observer_started = True _notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name, 'detail': '已转后台观察,可查看状态'}) + from .operation_queue import hold_native_handoff + hold_native_handoff(process, process.session_record_path) + except TaskHandoff as error: + handoff_result = _handoff_verify_result(error) + if handoff_result.evidence_path: + _write_optional_evidence(handoff_result.evidence_path, + {'block_name': request.block_name, **asdict(handoff_result)}) + raise except Exception as error: close_errors.append(str(error)) if 'process' in locals(): @@ -1232,6 +1372,25 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run 'automation_release': automation_release, 'worker_exited': worker_exited} release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', [])) | set(automation_release.get('remaining_pids', []))) + if worker_exited: + try: + if (release_result.get('safe_to_continue') is not True + and getattr(process, 'session_record_path', None)): + if not observer_started: + from .session_record import handoff_session + # Retain the exact worker handle until registered + # native clients exit and the observer obtains proof. + handoff_session(process.session_record_path, evidence_root=root, + process=process, progress=lambda state: _notify_progress(progress, + {'stage': 'session_observation', 'block': request.block_name, **state})) + observer_started = True + _notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name, + 'detail': '工作进程已退出,原生会话继续后台观察'}) + else: + process.close() + except Exception as error: + release_result = {**release_result, 'safe_to_continue': False, + 'close_errors': [*close_errors, str(error)]} try: from .operation_lifecycle import classify_save_state save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines() @@ -1279,8 +1438,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run except OSError: pass finally: - win32event.ReleaseMutex(mutex) - mutex.Close() + end_native_phase() if result.status == 'PASS' and not request.diagnostic_only: timing.begin('library_flag') @@ -1290,9 +1448,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run if progress: _notify_progress(progress, {'stage': 'library_flag_probe', 'block': request.block_name, **record}) try: - probe = read_library_flag_with_retry( - flag_reader or read_library_flag_if_available, Path(request.lmc_file), - request.block_name, on_attempt=record_attempt) + with native_channel(read_only=True): + probe = read_library_flag_with_retry( + flag_reader or read_library_flag_if_available, Path(request.lmc_file), + request.block_name, on_attempt=record_attempt) result = apply_post_verify_status(result, probe) result = replace(result, bridge_attempts=tuple(bridge_records)) _write_optional_evidence(root/'bridge-status.json', bridge_records) @@ -1304,20 +1463,27 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run return finish(result) -def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None): +def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None, + context=None): """Run serially and stop when database/session safety is unconfirmed.""" if max_workers != 1: raise ValueError('Only serial Verify is supported for the shared Library Manager session') + if context is not None: + stop = stop if stop is not None else context.stop + progress = context.guard_callback(progress) if progress is not None else None if verifier is None: - verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available, stop=stop) # noqa: E731 + verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available, + stop=stop, context=context) # noqa: E731 results = [] queue_stop = False retained_libraries = set() for request in requests: - library_key = str(getattr(request, 'lmc_file', '__injected_verifier_scope__')).casefold() - if queue_stop or (stop is not None and stop.is_set()): + from .operation_queue import request_library_keys + library_keys = request_library_keys(request, context) + if (queue_stop or stop is not None and stop.is_set() + or context is not None and context.stop.is_set()): result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB') - elif library_key in retained_libraries: + elif library_keys.intersection(retained_libraries): result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入') else: try: @@ -1325,18 +1491,19 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non result = verifier(request) if not result.safe_to_continue: from .operation_lifecycle import recheck_failed_release - result = recheck_failed_release(request.lmc_file, request.block_name, result) + result = recheck_failed_release(request.lmc_file, request.block_name, result, stop=stop) return result result = item_executor(request, execute) if item_executor is not None else execute() except Exception as error: - from .operation_queue import QueueCancelled + from .operation_queue import QueueCancelled, TaskHandoff # An unexpected exception cannot establish database safety. - result = VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL', - stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)) + result = (_handoff_verify_result(error) if isinstance(error, TaskHandoff) else + VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL', + stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))) results.append(result) # Never start another writer after an unconfirmed native shutdown. if not result.safe_to_continue: - retained_libraries.add(library_key) + retained_libraries.update(library_keys) queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} if queue_stop and stop is not None: stop.set() diff --git a/src/cbb_refresh_verify/write_admission.py b/src/cbb_refresh_verify/write_admission.py index 78f7928..cd61556 100644 --- a/src/cbb_refresh_verify/write_admission.py +++ b/src/cbb_refresh_verify/write_admission.py @@ -63,7 +63,9 @@ class WriteAdmission: if decision != 'continue': if decision == 'cancel' and self.stop is not None: self.stop.set() - raise WriteAdmissionDeclined(decision) + detail = ('确认等待超时默认跳过本项,未授予未知进程写入许可。' + if decision == 'skip' and choice.decision_origin == 'timeout_default' else None) + raise WriteAdmissionDeclined(decision, detail) current, _ = self._identities(owners) if not set(current).issubset(identities): raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 确认期间进程身份已变化,请重新检查。') @@ -73,5 +75,6 @@ class WriteAdmission: _write_json(root/('write-owner-consent-'+uuid4().hex+'.json'), dict( intent='user_confirmed_unknown_clients_do_not_use_target_library', library=str(Path(library).resolve()), block=block, scope='current_batch_library', owners=rows, choice='continue', + decision_origin=choice.decision_origin, proves_native_ownership=False, requires_fresh_resource_checks=True)) self._grants.setdefault(key, set()).update(current) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..d7f734f --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,10 @@ +"""Keep subprocess imports on the worktree being tested.""" +import os +from pathlib import Path + + +def pytest_configure(): + source = str(Path(__file__).resolve().parents[1] / 'src') + existing = os.environ.get('PYTHONPATH', '').split(os.pathsep) + os.environ['PYTHONPATH'] = os.pathsep.join( + [source, *(entry for entry in existing if entry and entry != source)]) diff --git a/tests/support/async_add_lifecycle_fixture.py b/tests/support/async_add_lifecycle_fixture.py new file mode 100644 index 0000000..7b45119 --- /dev/null +++ b/tests/support/async_add_lifecycle_fixture.py @@ -0,0 +1,97 @@ +"""Run the real Add dispatch with harmless process and Win32/UIA boundaries.""" +import json +import os +from pathlib import Path +import subprocess +import sys +from types import SimpleNamespace + +from pytest import MonkeyPatch + +from cbb_refresh_verify import desktop_worker, native_management as native +from cbb_refresh_verify.session_record import update_worker_state + + +def run(job_path): + job = json.loads(Path(job_path).read_text(encoding='utf-8')) + root = Path(job['root']) + signals = root.parent + mode = job['test_mode'] + lm_script = '''import subprocess,sys,time +from pathlib import Path +root=Path(sys.argv[1]) +input() +if sys.argv[2] == 'pending': + code='import sys,time; from pathlib import Path; p=Path(sys.argv[1]); '+\ + '\\nwhile not p.exists(): time.sleep(.02)' + child=subprocess.Popen([sys.executable,'-c',code,str(root/'native-done')]) + (root/'descendant-pid').write_text(str(child.pid)) +while not (root/'lm-exit').exists(): time.sleep(.02) +''' + lm = subprocess.Popen([sys.executable, '-c', lm_script, str(signals), mode], stdin=subprocess.PIPE, text=True) + (signals/'lm-pid').write_text(str(lm.pid)) + update_worker_state(job, 'POSTCALL', identities=[('native', lm.pid)], required=True) + desktop_worker.start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'], + session_record_path=job['session_record_path'], operation_id=job['operation_id'], + supervisor_identity=job['supervisor_identity']) + state = {'new': False, 'posted': False, 'closed': False} + patch = MonkeyPatch() + import win32gui, win32process + if mode == 'assignment-failed': + def deny_job(*args): + raise OSError('exact native job admission denied') + patch.setattr(desktop_worker.win32job, 'AssignProcessToJobObject', deny_job) + if mode == 'cancel-after-registration': + assign = desktop_worker.win32job.AssignProcessToJobObject + def cancel_after_assign(*args): + result = assign(*args) + (root/'cancel-native-add.signal').touch() + return result + patch.setattr(desktop_worker.win32job, 'AssignProcessToJobObject', cancel_after_assign) + tab = SimpleNamespace(window_text=lambda: 'Logical - Physical', is_selected=lambda: True) + patch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=lambda **kw: SimpleNamespace( + window=lambda **kw: SimpleNamespace(descendants=lambda **kw: [tab])))) + patch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, lm.pid)) + patch.setattr(win32gui, 'IsWindowVisible', lambda _: True) + patch.setattr(win32gui, 'IsWindowEnabled', lambda _: True) + patch.setattr(win32gui, 'GetWindowText', lambda h: { + 100: 'Reusable Blocks', 200: 'New Reusable Block', 300: 'Native result', + 301: 'New Logical-Physical Reuse Block was successfully added.'}.get(int(h), '')) + patch.setattr(win32gui, 'GetDlgItem', lambda h, c: + 110 if h == 100 and c == 1066 else 112 if h == 100 else 210 if c == 1083 else 302 if h == 300 else c+1000) + patch.setattr(win32gui, 'GetClassName', lambda _: 'Edit') + patch.setattr(win32gui, 'IsWindow', lambda _: not state['closed']) + patch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg: + fn(301, arg) if h == 300 and mode == 'acknowledged' else None) + # Only the external native text-control setter is substituted. + patch.setattr(native, '_set_probe_field', lambda hwnd, control, value, root, *, read_only=False: None) + def post(hwnd, *args): + if hwnd == 110: state['new'] = True + if hwnd == 210: + state['posted'] = True + lm.stdin.write('Add\n') + lm.stdin.flush() + (signals/'add-dispatched').touch() + if hwnd == 112: state['closed'] = True + patch.setattr(win32gui, 'PostMessage', post) + def windows(): + if state['closed']: return [] + return ([100, 200, 300] if state['posted'] and mode == 'acknowledged' else + [100, 200] if state['new'] else [100]) + desktop = SimpleNamespace(EnumDesktopWindows=windows) + try: + native._probe_add_dialog(SimpleNamespace(OnReusableBlocksEditor=lambda: None), + job, desktop, {lm.pid}, root) + result = {'success': True, 'safe_to_continue': False} + except (TimeoutError, OSError, RuntimeError) as error: + result = {'success': False, 'safe_to_continue': False, 'detail': str(error)} + finally: + patch.undo() + (root/'result.json').write_text(json.dumps(result)) + update_worker_state(job, 'UNCONFIRMED') + (signals/'add-unwound').touch() + return 0 + + +if __name__ == '__main__': + desktop_worker.run_native_worker(run, Path(sys.argv[1])) diff --git a/tests/support/manifest_process_exit.py b/tests/support/manifest_process_exit.py new file mode 100644 index 0000000..3b649f7 --- /dev/null +++ b/tests/support/manifest_process_exit.py @@ -0,0 +1,41 @@ +"""Real application close while one disposable metadata boundary is held.""" +from pathlib import Path +import sys,time + +from PySide6.QtCore import QTimer +from PySide6.QtWidgets import QApplication +from cbb_refresh_verify import scoped_manifest as manifest +from cbb_refresh_verify.operation_queue import check_active +from cbb_refresh_verify.ui.main_window import MainWindow + +root=Path(sys.argv[1]);mode=sys.argv[2] +source=root/'source';source.mkdir() +(source/('one.log' if mode=='copy' else 'one.dat')).write_bytes(b'isolated fixture') +def held(): + (root/'entered').touch() + while not (root/'release').exists():time.sleep(.02) +def hash_file(path): + held() + return manifest.hash_file(path) +if mode=='copy': + original=manifest.shutil.copy2 + def copy_file(*args,**kwargs): + held() + return original(*args,**kwargs) + manifest.shutil.copy2=copy_file +def action(): + if mode=='hash':manifest.build_manifest(source,hash_function=hash_file) + else:manifest.copy_verified(source,root/'partial-copy',hash_function=hash_file) + check_active() + (root/'late-dispatch').touch() +app=QApplication([]) +window=MainWindow(reader=lambda _:None,data_root=root/'data');window.show() +job=window._new_job('management',library=root/'library.lmc') +window._start(action,lambda _:None,queued=False,job=job) +def close_when_entered(): + if (root/'entered').exists():window.close() + else:QTimer.singleShot(20,close_when_entered) +QTimer.singleShot(20,close_when_entered) +code=app.exec() +(root/'main-returning').touch() +raise SystemExit(code) diff --git a/tests/support/runtime_lifecycle_frozen_smoke.py b/tests/support/runtime_lifecycle_frozen_smoke.py index e43534f..99a6402 100644 --- a/tests/support/runtime_lifecycle_frozen_smoke.py +++ b/tests/support/runtime_lifecycle_frozen_smoke.py @@ -9,6 +9,7 @@ from uuid import uuid4 workspace = Path(sys.argv[1]).resolve() bundle_root = Path(sys.argv[2]).resolve() sys.path.insert(0, str(workspace/'src')) +from cbb_refresh_verify import __version__ exe = bundle_root/'dist/CbbRefreshVerify-Background/CbbRefreshVerify.exe' root = bundle_root/('smoke-' + uuid4().hex[:8]) root.mkdir() @@ -64,7 +65,7 @@ finally: from PyInstaller.archive.readers import ZlibArchiveReader pyz = bundle_root/'build/CbbRefreshVerify/PYZ-00.pyz' code = ZlibArchiveReader(str(pyz)).extract('cbb_refresh_verify') -assert '0.2.4b3' in code.co_consts +assert __version__ in code.co_consts toc = ast.literal_eval((bundle_root/'build/CbbRefreshVerify/Analysis-00.toc').read_text('utf-8')) stack, rows = [toc], [] while stack: @@ -77,6 +78,6 @@ while stack: stack.extend(value) assert rows and all(Path(row[1]).is_relative_to(workspace/'src') for row in rows) results['module_origins'] = {'status': 'passed', 'module_count': len(rows), 'source_root': str(workspace/'src')} -results['version'] = '0.2.4b3' +results['version'] = __version__ (root/'result.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), 'utf-8') print(json.dumps({'evidence': str(root/'result.json'), **results}, ensure_ascii=False), flush=True) diff --git a/tests/test_all_buttons.py b/tests/test_all_buttons.py index e6844a8..64f5242 100644 --- a/tests/test_all_buttons.py +++ b/tests/test_all_buttons.py @@ -130,7 +130,7 @@ def test_main_logs_and_evidence_buttons_open_the_correct_paths(controls, qtbot): w.recovery_path = evidence w.recovery_button.setEnabled(True) press(qtbot, w.recovery_button) - assert controls.opened == [w.data_root, evidence] + assert controls.opened == [w.data_root/'logs', evidence] @pytest.mark.parametrize('attribute', ['selected_batch_button', 'batch_button', 'icdb_repair_button']) @@ -152,7 +152,7 @@ def test_main_check_buttons_have_real_confirm_and_cancel_paths(controls, qtbot, assert details is not None press(qtbot, details) assert summary.findChild(QTextEdit).isVisible() - press(qtbot, summary.button(QMessageBox.Ok)) + press(qtbot, summary.button(QMessageBox.Close)) assert not isValid(summary) or not summary.isVisible() @@ -280,7 +280,7 @@ def test_management_confirm_cancel_execute_stop_and_repeated_click(controls, qtb qtbot.mouseClick(dialog.close_button, Qt.LeftButton) assert len(calls) == 1 and dialog.isVisible() press(qtbot, dialog.stop_button) - assert dialog.stop.is_set() + assert dialog.context.stop_after_current.is_set() and not dialog.stop.is_set() finally: finish.set() qtbot.waitUntil(lambda: not dialog.busy) @@ -411,7 +411,7 @@ def test_residual_refresh_details_confirm_and_close(residual, qtbot): expand = next(b for b in details.findChildren(QPushButton) if 'Details' in b.text()) press(qtbot, expand) assert details.findChild(QTextEdit).isVisible() - press(qtbot, details.button(QMessageBox.Ok)) + press(qtbot, details.button(QMessageBox.Close)) press(qtbot, d.confirm_button) qtbot.waitUntil(lambda: not d.busy) assert len(residual.releases) == 1 and residual.releases[0]['force'] is False diff --git a/tests/test_background_icdb.py b/tests/test_background_icdb.py index da9507f..c1f5260 100644 --- a/tests/test_background_icdb.py +++ b/tests/test_background_icdb.py @@ -69,9 +69,10 @@ def test_completed_old_library_result_does_not_release_new_library(qtbot, tmp_pa qtbot.waitUntil(lambda: not window._icdb_active()) summary = window.icdb_summary window.lmc_edit.setText('other.lmc') + message = window.status_label.text() next(button for button in summary.buttons() if '释放' in button.text()).click() assert getattr(window, 'release_dialog', None) is None - assert '切' in window.status_label.text() + assert window.status_label.text() == message def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch): @@ -109,4 +110,4 @@ def test_check_release_action_tracks_busy_and_retained_queue(qtbot, tmp_path, mo assert opened == [{'queued': True}] window.busy = False window._update() - assert action.isEnabled() + assert not action.isEnabled(), 'A dismissed one-shot result cannot be reactivated' diff --git a/tests/test_backup_recovery_dialog.py b/tests/test_backup_recovery_dialog.py index 03e747d..444b41b 100644 --- a/tests/test_backup_recovery_dialog.py +++ b/tests/test_backup_recovery_dialog.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt from pathlib import Path from threading import Event @@ -8,7 +9,7 @@ import pytest @pytest.fixture(autouse=True) def accept_manual_backup_reminder(monkeypatch): from PySide6.QtWidgets import QMessageBox - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path): diff --git a/tests/test_batch_item_yield.py b/tests/test_batch_item_yield.py index 1ee8318..02d737f 100644 --- a/tests/test_batch_item_yield.py +++ b/tests/test_batch_item_yield.py @@ -71,7 +71,7 @@ def test_verify_failure_recheck_finishes_before_yielding_native_queue(qtbot,tmp_ try:return action() finally:active.pop() return run - def recheck(library,block,result): + def recheck(library,block,result,**kwargs): seen.append(bool(active)) return replace(result,safe_to_continue=True) monkeypatch.setattr(window,'_queued_action',queued) @@ -92,7 +92,7 @@ def test_management_failure_recheck_finishes_before_yielding_native_queue(tmp_pa active.append(True) try:return action() finally:active.pop() - def recheck(library,block,result): + def recheck(library,block,result,**kwargs): seen.append(bool(active)) return replace(result,safe_to_continue=True) monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck) diff --git a/tests/test_cancelled_diagnostic_report.py b/tests/test_cancelled_diagnostic_report.py new file mode 100644 index 0000000..5f6f13e --- /dev/null +++ b/tests/test_cancelled_diagnostic_report.py @@ -0,0 +1,34 @@ +from threading import Event + +import pytest + +from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff, hold_native_handoff +from cbb_refresh_verify.ui.icdb_check_task import IcdbCheckTask +from cbb_refresh_verify.verify_runner import VerifyResult +from test_verify_runner import fixture, request + + +def test_cancelled_diagnostic_report_survives_ongoing_handoff_finalization(qtbot,tmp_path): + fixture(tmp_path) + req=request(tmp_path,diagnostic_only=True) + context=BatchTaskContext(str(req.lmc_file),native_policy='external') + entered,finish=Event(),Event() + def finalize(): + try: + hold_native_handoff(None,tmp_path/'session.json') + except TaskHandoff: + entered.set() + assert finish.wait(5) + try: + with pytest.raises(TaskHandoff):context.run(finalize) + assert entered.is_set() + task=IcdbCheckTask([req],NativeQueue(),tmp_path/'reports') + task.active=True + task.results=[VerifyResult('CANCELLED',safe_to_continue=False,stderr='已转后台观察')] + task._report() + qtbot.waitUntil(lambda:not task.active,timeout=3000) + assert task.report is not None and task.report.exists(),task.report_error + assert not task.report_error and task.results[0].status=='CANCELLED' + finally: + finish.set() + context.close(timeout_seconds=2) diff --git a/tests/test_cancelled_loaded_startup.py b/tests/test_cancelled_loaded_startup.py new file mode 100644 index 0000000..f2b8427 --- /dev/null +++ b/tests/test_cancelled_loaded_startup.py @@ -0,0 +1,178 @@ +"""Cancellation may race native loading after COM/document admission stopped.""" +from copy import deepcopy +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from cbb_refresh_verify import diagnostic_open, failed_session, residual_sessions +from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot +from test_failed_startup import startup_fixture +from test_diagnostic_open import write_logs + + +def loaded_fixture(tmp_path, monkeypatch, *, empty_close_first=False, obstacle=''): + import win32con, win32gui + job, records, messages = startup_fixture(tmp_path, monkeypatch) + job.update(project=str(tmp_path/'IP101GR/IP101GR.prj'), pcb=str(tmp_path/'IP101GR/PCB/IP101GR.pcb'), + diagnostic_only=True, cancel_signal=str(tmp_path/'cancel.signal')) + Path(job['pcb']).parent.mkdir(parents=True) + Path(job['pcb']).touch(); Path(job['cancel_signal']).touch() + records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11) + job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job) + write_logs(job, pid=99 if obstacle == 'foreign_log_pid' else 12, foreign=obstacle == 'foreign_log_path') + if obstacle == 'stale_logs': job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job) + if obstacle == 'write': (tmp_path/'save.log').write_text('save entered') + if obstacle == 'ordinary': job['diagnostic_only'] = False + if obstacle == 'not_cancelled': Path(job['cancel_signal']).unlink() + state = dict(ticks=0., tip=not empty_close_first, declined=False, closing=False) + clock = SimpleNamespace(monotonic=lambda:state['ticks'], + sleep=lambda seconds:state.__setitem__('ticks', state['ticks']+seconds)) + monkeypatch.setattr(failed_session, 'time', clock) + monkeypatch.setattr(diagnostic_open, 'time', clock) + target = dict(hwnd=100, pid=12, **{'class':'Afx:main'}, + text='Expedition PCB - Reusable Block - [IP101GR]', enabled=False, + children=[dict(hwnd=101, **{'class':'MDIClient'}, text='', parent=100), + dict(hwnd=102, **{'class':'Afx:document'}, text='IP101GR', parent=101)]) + if obstacle == 'foreign_mdi': target['children'][1]['text'] = 'Other' + forward = dict(hwnd=200, pid=12, **{'class':'#32770'}, text='Expedition PCB', owner=100, + children=[dict(hwnd=30, **{'class':'Static'}, id=6172, + text='New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'), + dict(hwnd=31, **{'class':'Button'}, id=7, text='&No', enabled=True), + dict(hwnd=32, **{'class':'Button'}, id=6, text='&Yes', enabled=True)]) + if obstacle == 'foreign_prompt': forward['owner'] = 999 + if obstacle == 'unknown': forward['text'] = 'Unknown action' + def windows(pid): + if state['tip'] or empty_close_first and not state['closing']: return [] + frame = deepcopy(target) + frame['enabled'] = state['declined'] + if not state['declined'] or obstacle == 'progress': + frame['children'].append(dict(hwnd=103, **{'class':'msctls_progress32'}, text='', visible=True)) + return [frame] + ([] if state['declined'] else [deepcopy(forward)]) + monkeypatch.setattr(diagnostic_open, '_windows', windows) + monkeypatch.setattr(diagnostic_open, '_request_close_handoff', lambda *a, **kw: + pytest.fail('cancelled supervisor must not be asked for a normal admission ack')) + monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn,arg: + [fn(h,arg) for h in ((200,) if state['tip'] else (100,200))]) + monkeypatch.setattr(win32gui, 'GetClassName', lambda h:'#32770' if h == 200 else 'Afx:main') + monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: + 'Expedition PCB' if empty_close_first and not state['closing'] else target['text']) + monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: h != 200 or state['tip'] or not empty_close_first) + tip = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Tip of the Day', + DialogPhase.PCB_STARTING,(ControlSnapshot(201,1,'Button','OK',enabled=True),)) + unknown = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB', + DialogPhase.PCB_STARTING,()) + monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *a:tip if state['tip'] else unknown) + def post(hwnd, message, *_): + messages.append((hwnd,message)) + if hwnd == 201: state['tip'] = False + elif hwnd == 31: + state['declined'] = True + if state['closing']: records.clear() + elif hwnd == 100 and message == win32con.WM_CLOSE: + state['closing'] = True + if state['declined']: records.clear() + monkeypatch.setattr(win32gui, 'PostMessage', post) + return job, records, messages, state + + +@pytest.mark.parametrize('empty_close_first', [False, True]) +def test_cancelled_diagnostic_tip_to_loaded_forward_no_closes_once_without_ack(tmp_path, monkeypatch, empty_close_first): + job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, empty_close_first=empty_close_first) + events = [] + result = failed_session.close_failed_startup(job,12,timeout_seconds=1, + emit=lambda **event:events.append(event)) + assert result['status'] == 'CLOSED' and result['release']['safe_to_continue'] + assert messages == ([(100,16),(31,245)] if empty_close_first else [(201,245),(31,245),(100,16)]) + assert not records and Path(job['cancel_signal']).exists() + assert not any(e.get('stage') in ('diagnostic_complete','diagnostic_native_open_confirmed','save_start') for e in events) + assert sum(e['stage']=='startup_close_requested' for e in events)==1 + + +@pytest.mark.parametrize('obstacle', ['foreign_log_pid','foreign_log_path','stale_logs','foreign_mdi', + 'foreign_prompt','unknown','progress','write','ordinary','not_cancelled']) +def test_cancelled_loaded_cleanup_cannot_override_identity_write_or_unknown_guards(tmp_path, monkeypatch, obstacle): + job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, obstacle=obstacle) + result = failed_session.close_failed_startup(job,12,timeout_seconds=.5) + assert result['status']=='RETAINED' and records + assert messages == ([(201,245),(31,245)] if obstacle=='progress' else [(201,245)]) + + +def test_cancelled_diagnostic_keeps_one_thirty_second_cleanup_budget(tmp_path, monkeypatch): + job, records, messages, state = loaded_fixture(tmp_path,monkeypatch,obstacle='progress') + result = failed_session.close_failed_startup(job,12) + assert result['status']=='RETAINED' and records + assert 30 <= state['ticks'] <= 30.2 + assert messages==[(201,245),(31,245)] + + +def test_unknown_sibling_vetoes_known_forward_no(tmp_path,monkeypatch): + job,records,messages,state=loaded_fixture(tmp_path,monkeypatch) + original=diagnostic_open._windows + def windows(pid): + values=original(pid) + return values+[dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown action',children=[])] if values else values + monkeypatch.setattr(diagnostic_open,'_windows',windows) + result=failed_session.close_failed_startup(job,12,timeout_seconds=.5) + assert result['status']=='RETAINED' and records + assert messages==[(201,245)] + + +@pytest.mark.parametrize('filename',['IP101GR.pcb','Foreign.pcb']) +def test_cancelled_loaded_close_only_declines_exact_owned_save_question(tmp_path,monkeypatch,filename): + import win32gui + job,records,messages,state=loaded_fixture(tmp_path,monkeypatch) + original_windows=diagnostic_open._windows + def windows(pid): + if not state['closing']:return original_windows(pid) + return [dict(hwnd=400,pid=12,**{'class':'#32770'},text='Expedition PCB',owner=100, + children=[dict(hwnd=40,**{'class':'Static'},text=f'Save changes to {filename}?'), + dict(hwnd=41,**{'class':'Button'},id=7,text='No',enabled=True), + dict(hwnd=42,**{'class':'Button'},id=6,text='Yes',enabled=True), + dict(hwnd=43,**{'class':'Button'},id=2,text='Cancel',enabled=True)])] + monkeypatch.setattr(diagnostic_open,'_windows',windows) + original_post=win32gui.PostMessage + def post(hwnd,message,*args): + if hwnd==100: + messages.append((hwnd,message));state['closing']=True + elif hwnd==41: + messages.append((hwnd,message));records.clear() + else:original_post(hwnd,message,*args) + monkeypatch.setattr(win32gui,'PostMessage',post) + result=failed_session.close_failed_startup(job,12,timeout_seconds=1) + assert result['status']==('CLOSED' if filename=='IP101GR.pcb' else 'RETAINED') + assert messages==[(201,245),(31,245),(100,16)]+([(41,245)] if filename=='IP101GR.pcb' else []) + + +def test_supervisor_finishes_inflight_poll_before_signalling_cleanup_and_never_polls_again(tmp_path,monkeypatch): + import json + from threading import Event + from cbb_refresh_verify import desktop_worker + from cbb_refresh_verify.verify_runner import run_verify + from cbb_refresh_verify.dialog_supervisor import DialogPollResult + from test_verify_runner import fixture, request, PORTS_OK + fixture(tmp_path); stop=Event(); state={'polling':False,'polls':0,'cleanup':False} + class Worker: + desktop=None;pid=700;companion_pids=[];returncode=None + def __init__(self,command,name): + self.name=name + state['path']=Path(command[-1]);state['job']=json.loads(state['path'].read_text()) + state['path'].with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started',pcb_pid=901))+'\n') + def poll(self):return self.returncode + def request_stop(self): + assert not state['polling'] and state['polls']==1 + Path(state['job']['cancel_signal']).touch() + def wait(self,timeout=5): + assert Path(state['job']['cancel_signal']).exists() and not state['polling'] + state['cleanup']=True;self.returncode=1;return 1 + def close(self):pass + class Supervisor: + def poll(self,*args): + assert not state['cleanup'] and not Path(state['job']['cancel_signal']).exists() + state['polling']=True;state['polls']+=1;stop.set();state['polling']=False + return DialogPollResult() + monkeypatch.setattr(desktop_worker,'DesktopWorker',Worker) + result=run_verify(request(tmp_path,diagnostic_only=True),port_check=PORTS_OK,stop=stop, + dialog_supervisor_factory=lambda **kw:Supervisor()) + assert result.status=='CANCELLED' and state['cleanup'] and state['polls']==1 + assert not state['path'].with_name('diagnostic-close-ack.json').exists() diff --git a/tests/test_cancelled_ordinary_startup.py b/tests/test_cancelled_ordinary_startup.py new file mode 100644 index 0000000..1fa7d5a --- /dev/null +++ b/tests/test_cancelled_ordinary_startup.py @@ -0,0 +1,198 @@ +import json +from pathlib import Path + +import pytest + +from cbb_refresh_verify import failed_session,session_record,diagnostic_open +from test_cancelled_loaded_startup import loaded_fixture + + +def ordinary_proof(job,root,baseline,*,worker=None,pid=12): + worker=worker or dict(pid=11,created_handle='worker-created',image='C:/App/python.exe',owner_sid='current',session_id=1) + job.update(diagnostic_only=False,operation='verify',operation_id=job.get('operation_id','verify-ordinary'), + library=job['lmc_file'],session_record_path=str(root/'session.json'),interactive_input=False) + job.pop('diagnostic_log_baseline',None) + session_record.write_session_record(root/'session.json',dict(operation_id=job['operation_id'],operation='verify', + library=job['library'],block=job.get('block',job.get('block_name')),desktop=job['desktop'],cancel_signal=job['cancel_signal'],processes=[dict(role='worker',**worker)], + resource_scope=dict(scope_state='DECLARED',library=job['library'],operation_id=job['operation_id'],projects=[job['project']]))) + binding={k:job[k] for k in ('operation_id','project','pcb','desktop')} + events=[dict(stage='startup_supervisor_no_write',**binding), + dict(stage='startup_prewrite_ready',worker_identity=worker,baseline=baseline,**binding), + dict(stage='pcb_baseline',pids=[]),dict(stage='pcb_worker_started',pcb_pid=pid), + dict(stage='startup_cancelled_prewrite',pcb_pid=pid,identity_verified=False,write_admitted=False,**binding)] + (root/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events)) + return events + + +@pytest.mark.parametrize('prior_close',[False,True]) +def test_proved_ordinary_cancel_finishes_tip_to_loaded_without_annotation_or_second_close(tmp_path,monkeypatch,prior_close): + job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=prior_close) + ordinary_proof(job,tmp_path,job['diagnostic_log_baseline']) + result=failed_session.close_failed_startup(job,12,timeout_seconds=1) + assert result['status']=='CLOSED' and not records + assert messages==([(100,16),(31,245)] if prior_close else [(201,245),(31,245),(100,16)]) + + +@pytest.mark.parametrize('obstacle',['missing_ready','missing_cancel_phase','supervisor_write','worker_write', + 'missing_supervisor','missing_baseline','foreign_worker','foreign_target','save','missing_cancel','interactive','native_lm']) +def test_ordinary_cleanup_requires_positive_bound_no_write_evidence(tmp_path,monkeypatch,obstacle): + job,records,messages,state=loaded_fixture(tmp_path,monkeypatch) + events=ordinary_proof(job,tmp_path,job['diagnostic_log_baseline']) + if obstacle=='missing_ready':events=[e for e in events if e['stage']!='startup_prewrite_ready'] + if obstacle=='missing_cancel_phase':events=[e for e in events if e['stage']!='startup_cancelled_prewrite'] + if obstacle=='missing_supervisor':events=events[1:] + if obstacle=='supervisor_write':events.append(dict(stage='startup_supervisor_write_possible')) + if obstacle=='worker_write':events.append(dict(stage='startup_write_admitted')) + if obstacle=='missing_baseline':events[1].pop('baseline') + if obstacle=='foreign_worker':events[1]['worker_identity']['created_handle']='other' + if obstacle=='foreign_target':events[-1]['pcb']='C:/foreign.pcb' + if obstacle=='save':(tmp_path/'save.log').write_text('SAVE_ENTERED') + if obstacle=='missing_cancel':Path(job['cancel_signal']).unlink() + if obstacle=='interactive':job['interactive_input']=True + if obstacle=='native_lm':job['native_lm_verify']=True + (tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events)) + result=failed_session.close_failed_startup(job,12,timeout_seconds=.3) + assert result['status']=='RETAINED' and records + assert not any(h==31 or m==16 for h,m in messages) + + +def test_worker_publishes_bound_baseline_before_launch_and_revokes_before_integration(tmp_path,monkeypatch): + from test_verify_worker_stability import exercise_worker + from cbb_refresh_verify import mentor_adapter,integration + job,events,execute=exercise_worker(tmp_path,monkeypatch) + job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test', + session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False) + launch=mentor_adapter.launch_pcb_process + def start(*args): + assert any(e['stage']=='startup_prewrite_ready' and 'baseline' in e for e in events) + return launch(*args) + def write(*args,**kwargs): + assert any(e['stage']=='startup_write_admitted' for e in events) + monkeypatch.setattr(mentor_adapter,'launch_pcb_process',start) + monkeypatch.setattr(integration,'refresh_integration',write) + assert execute()['status']=='PASS' + + +def test_cancelled_worker_records_positive_prewrite_phase_before_startup_cleanup(tmp_path,monkeypatch): + from test_verify_worker_stability import exercise_worker + from cbb_refresh_verify import pcb_bridge + job,events,execute=exercise_worker(tmp_path,monkeypatch) + job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test', + session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False, + cancel_signal=str(tmp_path/'cancel.signal')) + def cancel(*args,**kwargs): + Path(job['cancel_signal']).touch();raise RuntimeError('VERIFY_CANCELLED') + monkeypatch.setattr(pcb_bridge,'wait_for_target_document',cancel) + observed=[] + def cleanup(*args,**kwargs):observed.extend(events);return {'status':'RETAINED'} + monkeypatch.setattr(failed_session,'close_failed_startup',cleanup) + with pytest.raises(RuntimeError,match='VERIFY_CANCELLED'):execute() + assert any(e['stage']=='startup_cancelled_prewrite' and e['write_admitted'] is False + and e['identity_verified'] is False for e in observed) + + +@pytest.mark.parametrize('journal_fails',[False,True]) +def test_dialog_backend_records_write_revocation_before_action(journal_fails): + from types import SimpleNamespace + from cbb_refresh_verify.dialog_supervisor import Win32DialogBackend,DialogSnapshot,DialogControl + calls=[] + gui=SimpleNamespace(PostMessage=lambda *args:calls.append('native')) + backend=Win32DialogBackend((),win32gui=gui,win32process=object(),win32con=SimpleNamespace(BM_CLICK=245)) + def before(snapshot,action): + calls.append('journal') + if journal_fails:raise OSError('cannot record phase') + backend.before_action=before + snapshot=DialogSnapshot(100,12,'Expedition PCB',(DialogControl(101,6,'Button','Yes',True),)) + if journal_fails: + with pytest.raises(OSError):backend.perform(snapshot,'confirm_forward_annotation') + assert calls==['journal'] + else: + backend.perform(snapshot,'confirm_forward_annotation');assert calls==['journal','native'] + + +def test_positive_ordinary_cancel_phase_yields_after_initial_wait(tmp_path,monkeypatch): + from test_cancelled_session_handoff import worker_fixture + state,stop,run=worker_fixture(tmp_path,monkeypatch) + # The real worker publishes its cancellation fact during the first wait. + from cbb_refresh_verify import desktop_worker + Worker=desktop_worker.DesktopWorker;wait=Worker.wait + def complete_proof(worker,timeout=5): + job=state['job'] + baseline={'started_ns':1,'files':{}} + ordinary_proof(job,state['path'].parent,baseline,pid=901, + worker=dict(pid=700,created_handle='worker',image='C:/App/python.exe',owner_sid='current',session_id=1)) + return wait(worker,timeout) + monkeypatch.setattr(Worker,'wait',complete_proof) + assert run(False).status=='CANCELLED' + assert state['waits']==[5] + + +@pytest.mark.parametrize('proof_present',[True,False]) +def test_normal_release_of_ordinary_retained_startup_requires_new_complete_prewrite_proof(tmp_path,monkeypatch,proof_present): + from test_registered_startup_release import registered_fixture + from cbb_refresh_verify import residual_sessions + load=diagnostic_open._load_evidence + job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch) + monkeypatch.setattr(diagnostic_open,'_load_evidence',load) + job['diagnostic_only']=False + if proof_present:ordinary_proof(job,tmp_path,state['prelaunch_baseline']) + (tmp_path/'request.json').write_text(json.dumps(job)) + result=residual_sessions._request_close(row) + assert result['release_status']==('RELEASED' if proof_present else 'WAITING'),result + assert messages==([(31,245),(100,16)] if proof_present else []) + + +@pytest.mark.parametrize('obstacle',['unknown','hidden_document','progress','foreign_log_pid','foreign_log_path','revoked']) +def test_ordinary_cleanup_keeps_native_window_write_and_identity_vetoes(tmp_path,monkeypatch,obstacle): + job,records,messages,state=loaded_fixture(tmp_path,monkeypatch, + obstacle=obstacle if obstacle in ('unknown','progress','foreign_log_pid','foreign_log_path') else '') + ordinary_proof(job,tmp_path,job['diagnostic_log_baseline']) + read=diagnostic_open._windows + def windows(pid): + values=read(pid) + if values and obstacle=='hidden_document': + values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False)) + if state['declined'] and obstacle=='revoked': + with (tmp_path/'events.jsonl').open('a') as stream:stream.write(json.dumps(dict(stage='startup_write_admitted'))+'\n') + return values + monkeypatch.setattr(diagnostic_open,'_windows',windows) + result=failed_session.close_failed_startup(job,12,timeout_seconds=.5) + assert result['status']=='RETAINED' and records + assert not any(message==16 for _,message in messages) + assert messages==[(201,245)]+([(31,245)] if obstacle in ('progress','revoked') else []) + + +def test_proved_cancelled_startup_cannot_ack_tip_after_absolute_deadline(tmp_path,monkeypatch): + job,records,messages,state=loaded_fixture(tmp_path,monkeypatch) + ordinary_proof(job,tmp_path,job['diagnostic_log_baseline']) + assert failed_session.close_failed_startup(job,12,timeout_seconds=0)['status']=='RETAINED' + assert not messages and records + + +def test_agent_backend_cannot_dispatch_before_phase_journal(): + from types import SimpleNamespace + from cbb_refresh_verify.dialog_supervisor import AgentDialogBackend + from cbb_refresh_verify.dialog_models import WindowSnapshot,DialogPhase + calls=[] + backend=AgentDialogBackend(SimpleNamespace(perform=lambda **kwargs:calls.append('native')), + before_action=lambda *args:calls.append('journal')) + snapshot=WindowSnapshot(100,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',DialogPhase.PCB_STARTING,()) + backend.perform(snapshot,{'action':'confirm_forward_annotation'},DialogPhase.PCB_STARTING) + assert calls==['journal','native'] + + +@pytest.mark.parametrize('action',['tip','empty_close']) +def test_startup_deadline_is_rechecked_after_window_read_before_post(tmp_path,monkeypatch,action): + import win32gui + job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=action=='empty_close') + ordinary_proof(job,tmp_path,job['diagnostic_log_baseline']) + if action=='tip': + snapshot=failed_session._startup_snapshot + def read(*args): + value=snapshot(*args);state['ticks']=2;return value + monkeypatch.setattr(failed_session,'_startup_snapshot',read) + else: + def children(*args):state['ticks']=2 + monkeypatch.setattr(win32gui,'EnumChildWindows',children) + assert failed_session.close_failed_startup(job,12,timeout_seconds=1)['status']=='RETAINED' + assert not messages diff --git a/tests/test_cancelled_session_handoff.py b/tests/test_cancelled_session_handoff.py new file mode 100644 index 0000000..158faff --- /dev/null +++ b/tests/test_cancelled_session_handoff.py @@ -0,0 +1,154 @@ +import json +from pathlib import Path +from threading import Event + +import pytest + +from cbb_refresh_verify import desktop_worker, session_record, verify_runner as runner +from cbb_refresh_verify.dialog_supervisor import DialogPollResult +from test_verify_runner import fixture, request, PORTS_OK + + +def worker_fixture(tmp_path, monkeypatch, *, exited=False): + fixture(tmp_path) + state = dict(waits=[], closed=False, observers=[], polling=False, polls=0) + stop = Event() + class Worker: + desktop=None; pid=700; companion_pids=[]; returncode=1 if exited else None + def __init__(self, command, name): + self.name=name + path=Path(command[-1]); state.update(path=path,job=json.loads(path.read_text()),worker=self) + self.session_record_path=path.with_name('session.json') + session_record.write_session_record(self.session_record_path, dict( + operation_id=state['job']['operation_id'],library=state['job']['library'], + block=state['job']['block'])) + path.with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started',pcb_pid=901))+'\n') + path.with_name('outcome.json').write_text(json.dumps(dict(status='CANCELLED',safe_to_continue=False))) + def poll(self):return self.returncode + def request_stop(self): + assert not state['polling'] + Path(state['job']['cancel_signal']).touch() + def native_write_pending(self):return True + def wait(self,timeout=5): + state['waits'].append(timeout) + if timeout <= 5:raise TimeoutError('native startup still closing') + self.returncode=1;return 1 + def automation_release_state(self):return {'safe_to_continue':self.poll() is not None,'remaining_pids':[]} + def close(self):state['closed']=True + class Supervisor: + def poll(self,*args): + assert not state['observers'] + state['polling']=True;state['polls']+=1;stop.set();state['polling']=False + return DialogPollResult() + monkeypatch.setattr(desktop_worker,'DesktopWorker',Worker) + monkeypatch.setattr(runner,'_cleanup_session_processes',lambda *a,**kw: + {'safe_to_continue':False,'remaining_pids':[901]}) + monkeypatch.setattr(session_record,'handoff_session',lambda path,**kw: + state['observers'].append((path,kw,state['closed']))) + # Keep the task runner deterministic while exercising real supervisor ownership decisions. + monkeypatch.setattr('cbb_refresh_verify.operation_queue.hold_native_handoff',lambda *a:None) + return state,stop,lambda diagnostic:runner.run_verify(request(tmp_path,diagnostic_only=diagnostic), + port_check=PORTS_OK,stop=stop,dialog_supervisor_factory=lambda **kw:Supervisor()) + + +@pytest.mark.parametrize('diagnostic',[True,False]) +def test_diagnostic_cancel_yields_after_five_seconds_but_write_wait_is_unchanged(tmp_path,monkeypatch,diagnostic): + state,stop,run=worker_fixture(tmp_path,monkeypatch) + assert run(diagnostic).status=='CANCELLED' + assert state['waits']==([5] if diagnostic else [5,115]) + assert state['observers'] and state['observers'][0][1]['process'] is state['worker'] + assert not state['observers'][0][2] and not state['closed'] + assert state['polls']==1 + + +def test_exited_worker_with_live_native_clients_keeps_ownership_for_observer(tmp_path,monkeypatch): + state,stop,run=worker_fixture(tmp_path,monkeypatch,exited=True) + result=run(True) + assert result.status=='CANCELLED' and not result.safe_to_continue + assert len(state['observers'])==1, 'worker exit must not orphan the still-live registered native client' + path,options,already_closed=state['observers'][0] + assert path==state['worker'].session_record_path + assert options['process'] is state['worker'] and not already_closed and not state['closed'] + original=json.loads(state['path'].with_name('result.json').read_text()) + assert original['status']=='CANCELLED' and not original['safe_to_continue'] + + +def test_failed_observer_registration_preserves_original_cancelled_result_and_handle(tmp_path,monkeypatch): + state,stop,run=worker_fixture(tmp_path,monkeypatch,exited=True) + def fail(*args,**kwargs):raise OSError('observation journal unavailable') + monkeypatch.setattr(session_record,'handoff_session',fail) + result=run(True) + assert result.status=='CANCELLED' and not result.safe_to_continue + assert not state['closed'] + + +def test_missing_operation_identity_cannot_promote_cold_observation(tmp_path,monkeypatch): + from types import SimpleNamespace + path=tmp_path/'session.json';path.write_text('{invalid') + entered,finish=Event(),Event();modes=[] + def observe(*args,**kwargs): + mode=kwargs['observe_only'];modes.append(mode() if callable(mode) else mode) + entered.set();assert finish.wait(3) + return dict(status='UNCONFIRMED',operation_id=None) + monkeypatch.setattr(session_record,'observe_retained_session',observe) + owner=SimpleNamespace(cbb_library=str(tmp_path/'lib.lmc'),poll=lambda:0,close=lambda:None) + thread=None + try: + session_record.handoff_session(path,evidence_root=tmp_path,process=owner,observe_only=True) + assert entered.wait(2) + thread=session_record._observers[str(path.absolute()).casefold()][0] + assert modes==[True] + finally: + finish.set() + if thread:thread.join(3) + + +@pytest.mark.parametrize('cold_observer',[False,True]) +def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without_click(tmp_path,monkeypatch,cold_observer): + import subprocess,sys,time + from concurrent.futures import ThreadPoolExecutor + from types import SimpleNamespace + from cbb_refresh_verify import library_lock + from cbb_refresh_verify.operation_queue import NativeQueue,BatchTaskContext + from test_issue15_resource_release import library_file,cleanup + library=library_file(tmp_path) + gate=tmp_path/'native-exit' + native=subprocess.Popen([sys.executable,'-c', + 'from pathlib import Path; import time,sys\nwhile not Path(sys.argv[1]).exists(): time.sleep(.02)',str(gate)]) + evidence=tmp_path/'evidence';evidence.mkdir();path=evidence/'session.json' + session_record.write_session_record(path,dict(operation_id='cancelled-owned',operation='verify', + library=str(library),block='A',processes=[dict(role='native',**session_record.process_identity(native.pid))])) + original=evidence/'result.json';original.write_text('{"status":"CANCELLED","safe_to_continue":false}') + before=original.read_bytes() + with library_lock.LibraryLock(library,block_name='A',safe_to_release=lambda:False) as lease:pass + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *a,**kw:[]) + active=Event();stop=Event();closed=[] + owner=SimpleNamespace(pid=700,poll=lambda:0,close=lambda:closed.append(native.poll())) + thread=None + try: + session_record.handoff_session(path,evidence_root=evidence,process=owner,stop=stop,observe_only=cold_observer, + progress=lambda state:active.set() if state['status']=='ACTIVE' else None) + assert active.wait(3) and not closed + key=str(path.absolute()).casefold() + thread=session_record._observers[key][0] + if cold_observer: + session_record.handoff_session(path,evidence_root=evidence,observe_only=False) + assert session_record._observers[key][0] is thread + assert not session_record.library_available(library) + queue=NativeQueue() + def admitted(): + with library_lock.LibraryLock(library,checkpoint=False):return 'fresh admission' + with ThreadPoolExecutor(1) as pool: + future=pool.submit(queue.run,admitted,context=BatchTaskContext(str(library)),stop=stop) + time.sleep(.15);assert not future.done() + gate.touch();native.wait(5) + assert future.result(8)=='fresh admission' + thread.join(3) + assert not thread.is_alive() and closed==[0] + observations=[json.loads(p.read_text()) for p in evidence.glob('observation-*.json')] + assert any(o.get('status')=='RELEASED' and o['release_proof']['proof_block_name']=='A' for o in observations) + assert original.read_bytes()==before + finally: + gate.touch();native.wait(5);stop.set() + if thread:thread.join(3) + cleanup(lease) diff --git a/tests/test_desktop_worker.py b/tests/test_desktop_worker.py index 539d237..12c516e 100644 --- a/tests/test_desktop_worker.py +++ b/tests/test_desktop_worker.py @@ -115,7 +115,28 @@ def test_reader_never_creates_a_desktop_or_process(monkeypatch, tmp_path, reader import win32service import win32process import cbb_refresh_verify.mentor_adapter as module - from pywinauto import Desktop + import sys + import pythoncom + if 'pywinauto' not in sys.modules: + # Match the real worker's STA apartment. pywinauto's first import probes + # MTA and may report its fallback; validate that exact diagnostic only. + import warnings + pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) + try: + with warnings.catch_warnings(record=True) as diagnostics: + warnings.simplefilter('always') + from pywinauto import Desktop + for diagnostic in diagnostics: + if diagnostic.category is UserWarning and str(diagnostic.message) in ( + 'Revert to STA COM threading mode', 'Apply externally defined coinit_flags: 2'): + assert sys.coinit_flags == pythoncom.COINIT_APARTMENTTHREADED + else: + warnings.warn_explicit(diagnostic.message, diagnostic.category, + diagnostic.filename, diagnostic.lineno) + finally: + pythoncom.CoUninitialize() + else: + from pywinauto import Desktop monkeypatch.setattr(Desktop, 'windows', lambda *_: []) closed = [] diff --git a/tests/test_diagnostic_close_handoff.py b/tests/test_diagnostic_close_handoff.py new file mode 100644 index 0000000..09c8aa1 --- /dev/null +++ b/tests/test_diagnostic_close_handoff.py @@ -0,0 +1,53 @@ +import json +from pathlib import Path + +import pytest + +from test_verify_runner import fixture, request, PORTS_OK + + +@pytest.mark.parametrize('fault', ['', 'no_event', 'wrong_pid', 'wrong_operation', 'wrong_project', 'wrong_desktop', 'ordinary']) +def test_only_current_diagnostic_close_leaves_prompt_actions_to_checker(tmp_path, monkeypatch, fault): + from cbb_refresh_verify import desktop_worker + from cbb_refresh_verify.verify_runner import run_verify + from cbb_refresh_verify.dialog_supervisor import DialogPollResult + fixture(tmp_path); polls = [] + class Worker: + desktop = None + pid = 700 + companion_pids = [] + returncode = None + count = 0 + def __init__(self, command, name): + self.name = name + path = Path(command[-1]); job = json.loads(path.read_text()) + event = dict(stage='diagnostic_close_requested', close_id='b'*32, pcb_pid=901, hwnd=900, + operation_id=job['operation_id'], desktop=job['desktop'], project=job['project'], pcb=job['pcb']) + for condition, key, value in [('wrong_pid','pcb_pid',999),('wrong_operation','operation_id','foreign'), + ('wrong_project','project','foreign.prj'),('wrong_desktop','desktop','Default')]: + if fault == condition: event[key] = value + events = [dict(stage='pcb_worker_started', pcb_pid=901)] + if fault != 'no_event': events.append(event) + path.with_name('events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events)) + path.with_name('outcome.json').write_text(json.dumps({'status':'FAIL','safe_to_continue':False, + 'stderr':'DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown prompt retained'})) + def poll(self): + self.count += 1 + if self.count > 2: self.returncode = 1 + return self.returncode + def close(self): pass + def wait(self, timeout=5): self.returncode = 1; return 1 + class Supervisor: + def poll(self, *args): + polls.append(True) + return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='competing save prompt') + monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker) + result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK, + dialog_supervisor_factory=lambda **kwargs:Supervisor()) + assert result.status == 'FAIL' + assert json.loads(result.evidence_path.with_name('outcome.json').read_text())['safe_to_continue'] is False + if not fault: + assert polls == [] + assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr + else: + assert polls and 'UNKNOWN_DIALOG' in result.stderr diff --git a/tests/test_diagnostic_close_protocol.py b/tests/test_diagnostic_close_protocol.py new file mode 100644 index 0000000..f10a665 --- /dev/null +++ b/tests/test_diagnostic_close_protocol.py @@ -0,0 +1,136 @@ +import json +from pathlib import Path +import time +from types import SimpleNamespace + +import pytest + +from test_verify_runner import fixture, request, PORTS_OK +from test_diagnostic_open import job, write_logs, frame, Session + + +@pytest.mark.parametrize('fault', ['', 'foreign_operation', 'ordinary', 'missing_nonce']) +def test_close_handoff_arriving_during_poll_prevents_competing_abort(tmp_path, monkeypatch, fault): + from cbb_refresh_verify import desktop_worker + from cbb_refresh_verify.verify_runner import run_verify + from cbb_refresh_verify.dialog_supervisor import DialogPollResult + fixture(tmp_path); state = {} + class Worker: + desktop = None; pid = 700; companion_pids = []; returncode = None; count = 0 + def __init__(self, command, name): + self.name = name + path = Path(command[-1]); state.update(path=path, job=json.loads(path.read_text())) + path.with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started', pcb_pid=901))+'\n') + path.with_name('outcome.json').write_text(json.dumps(dict(status='FAIL', safe_to_continue=False, + stderr='DIAGNOSTIC_CLOSE_UNCONFIRMED: checker retained unknown prompt'))) + def poll(self): + self.count += 1 + if self.count > 2: self.returncode = 1 + return self.returncode + def close(self): pass + def wait(self, timeout=5): self.returncode = 1; return 1 + class Supervisor: + def poll(self, *args): + j = state['job'] + event = dict(stage='diagnostic_close_requested', close_id='a'*32, pcb_pid=901, hwnd=900, + operation_id=j['operation_id'], desktop=j['desktop'], project=j['project'], pcb=j['pcb']) + if fault == 'foreign_operation': event['operation_id'] = 'foreign' + if fault == 'missing_nonce': event.pop('close_id') + with state['path'].with_name('events.jsonl').open('a') as stream: + stream.write(json.dumps(event)+'\n') + return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='in-flight competing save prompt') + monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker) + result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK, + dialog_supervisor_factory=lambda **kw: Supervisor()) + assert result.status == 'FAIL' + ack = state['path'].with_name('diagnostic-close-ack.json') + if fault: + assert 'UNKNOWN_DIALOG' in result.stderr and not ack.exists() + else: + assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr + assert 'UNKNOWN_DIALOG' not in result.stderr + assert json.loads(ack.read_text())['close_id'] == 'a'*32 + + +def test_checker_never_posts_close_before_bound_supervisor_ack(job, monkeypatch): + from cbb_refresh_verify import diagnostic_open as diagnostic + job['operation_id'] = 'verify-protocol' + Path(job['root']).mkdir(exist_ok=True) + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + write_logs(job); events = [] + ack = Path(job['root'])/'diagnostic-close-ack.json' + class AcknowledgedSession(Session): + def post(self, hwnd, message): + assert ack.exists(), 'WM_CLOSE raced ahead of supervisor ownership acknowledgement' + assert events[-1]['stage'] == 'diagnostic_close_requested' + super().post(hwnd, message) + def emit(**event): + events.append(event) + if event['stage'] == 'diagnostic_close_requested': + ack.write_text(json.dumps({k:v for k,v in event.items() if k != 'stage'})) + monkeypatch.setattr(diagnostic, '_NativeSession', AcknowledgedSession) + monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else []) + assert diagnostic.check_target_window(job, 42, emit=emit, error_reader=lambda: None)['status'] == 'PASS' + assert Session.instances[-1].posted == [(10, 0x10)] + + +@pytest.mark.parametrize('fault', ['missing', 'stale_nonce', 'foreign_pid', 'foreign_project', + 'foreign_desktop', 'cancel_wait', 'cancel_ack', 'late_ack']) +def test_missing_stale_cancelled_or_late_ack_preserves_native(job, monkeypatch, fault): + from cbb_refresh_verify import diagnostic_open as diagnostic + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + write_logs(job) + offset = [0]; clock = time.monotonic + cancel = Path(job['root'])/'cancel.signal'; job['cancel_signal'] = str(cancel) + def wait(_): + if fault == 'cancel_wait': cancel.touch() + else: offset[0] += 31 + monkeypatch.setattr(diagnostic, 'time', SimpleNamespace(monotonic=lambda:clock()+offset[0], sleep=wait)) + monkeypatch.setattr(diagnostic, '_NativeSession', Session) + monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)]) + def emit(**event): + if event['stage'] != 'diagnostic_close_requested': return + if fault in ('missing', 'cancel_wait'): return + ack = {k:v for k,v in event.items() if k != 'stage'} + for condition,key,value in [('stale_nonce','close_id','0'*32),('foreign_pid','pcb_pid',99), + ('foreign_project','project','foreign'),('foreign_desktop','desktop','Default')]: + if fault == condition: ack[key] = value + (Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps(ack)) + if fault == 'cancel_ack': cancel.touch() + if fault == 'late_ack': offset[0] += 31 + with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if fault.startswith('cancel') else 'DIAGNOSTIC_CLOSE_UNCONFIRMED'): + diagnostic.check_target_window(job,42,emit=emit,error_reader=lambda:None) + assert Session.instances[-1].alive and Session.instances[-1].posted == [] + + +@pytest.mark.parametrize('change', ['progress', 'disabled', 'hwnd', 'pid', 'unknown', 'forward', 'native_error', 'cancel_recheck']) +def test_ready_frame_and_prompt_are_revalidated_after_ack(job, monkeypatch, change): + from cbb_refresh_verify import diagnostic_open as diagnostic + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + write_logs(job); acknowledged = [] + job['cancel_signal'] = str(Path(job['root'])/'cancel.signal') + monkeypatch.setattr(diagnostic, '_NativeSession', Session) + def windows(pid): + target = frame(job); rows = [target] + if not acknowledged: return rows + if change == 'progress': target['children'].append({'class':'msctls_progress32','visible':True}) + if change == 'disabled': target['enabled'] = False + if change == 'hwnd': target['hwnd'] = 99 + if change == 'pid': target['pid'] = 99 + if change == 'cancel_recheck': Path(job['cancel_signal']).touch() + if change == 'unknown': rows.append({'hwnd':20,'pid':42,'class':'#32770','text':'Unknown','children':[]}) + if change == 'forward': rows.append({'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10, + 'children':[{'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'}, + {'hwnd':21,'class':'Button','id':7,'text':'No'}, {'hwnd':22,'class':'Button','id':6,'text':'Yes'}]}) + return rows + monkeypatch.setattr(diagnostic, '_windows', windows) + def emit(**event): + if event['stage'] == 'diagnostic_close_requested': + (Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps({k:v for k,v in event.items() if k!='stage'})) + acknowledged.append(True) + def error(): + return 'ICDB_INCONSISTENT: fresh error after handoff' if change == 'native_error' and acknowledged else None + expected = {'native_error':'ICDB_INCONSISTENT', 'cancel_recheck':'VERIFY_CANCELLED'}.get(change, 'DIAGNOSTIC_CLOSE_UNCONFIRMED') + with pytest.raises(RuntimeError, match=expected): + diagnostic.check_target_window(job,42,emit=emit,error_reader=error) + assert acknowledged and Session.instances[-1].posted == [] diff --git a/tests/test_diagnostic_open.py b/tests/test_diagnostic_open.py index ab269c4..72624fb 100644 --- a/tests/test_diagnostic_open.py +++ b/tests/test_diagnostic_open.py @@ -1,14 +1,25 @@ import importlib import importlib.util +import json from pathlib import Path import pytest @pytest.fixture -def diagnostic(): +def diagnostic(monkeypatch): assert importlib.util.find_spec('cbb_refresh_verify.diagnostic_open') is not None, 'diagnostic open module is missing' - return importlib.import_module('cbb_refresh_verify.diagnostic_open') + module = importlib.import_module('cbb_refresh_verify.diagnostic_open') + check = module.check_target_window + def acknowledged(job, pid, *, emit, **kwargs): + def parent(**event): + emit(**event) + if event['stage'] == 'diagnostic_close_requested': + (Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps( + {key:value for key,value in event.items() if key != 'stage'})) + return check(job, pid, emit=parent, **kwargs) + monkeypatch.setattr(module, 'check_target_window', acknowledged) + return module @pytest.fixture @@ -17,8 +28,9 @@ def job(tmp_path): pcb = project / 'PCB/IP101GR.pcb' pcb.parent.mkdir(parents=True) pcb.write_bytes(b'pcb') + (tmp_path/'evidence').mkdir() return {'project': str(project / 'IP101GR.prj'), 'pcb': str(pcb), 'root': str(tmp_path / 'evidence'), - 'desktop': 'CbbDiagnosticTest', 'timeout': .03} + 'desktop': 'CbbDiagnosticTest', 'operation_id': 'verify-fixture', 'timeout': .03} def write_logs(job, *, pid=42, foreign=False, success=True): @@ -83,6 +95,58 @@ def test_target_title_without_target_mdi_does_not_pass(diagnostic, job): assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None +def test_visible_loading_progress_is_not_ready_for_diagnostic_close(diagnostic, job): + window = frame(job) + progress = {'hwnd': 13, 'class': 'msctls_progress32', 'text': '', 'visible': True} + window['children'].append(progress) + assert diagnostic._target_frame([window], 'IP101GR') is None + progress['visible'] = False + assert diagnostic._target_frame([window], 'IP101GR') == window + + +@pytest.mark.parametrize('cancel', [False, True]) +def test_persistent_loading_progress_keeps_deadline_and_never_closes(diagnostic, job, monkeypatch, cancel): + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + write_logs(job) + signal = Path(job['root']).parent/'cancel-progress' + job['cancel_signal'] = str(signal) + target = frame(job) + target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True}) + def windows(pid): + if cancel: signal.touch() + return [target] + monkeypatch.setattr(diagnostic,'_NativeSession',Session) + monkeypatch.setattr(diagnostic,'_windows',windows) + with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if cancel else 'DIAGNOSTIC_OPEN_UNCONFIRMED'): + diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None) + assert Session.instances[-1].posted == [] + + +def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch): + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + write_logs(job); job['timeout'] = 1 + class ForwardSession(Session): + declined = False + def post(self, hwnd, message): + self.posted.append((hwnd,message)) + if hwnd == 31: self.declined = True + else: self.alive = False + def windows(pid): + state = Session.instances[-1] + target = frame(job) + if state.declined: return [target] if state.alive else [] + target['enabled'] = False + target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True}) + return [target, {'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10, + 'children':[{'hwnd':30,'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'}, + {'hwnd':31,'class':'Button','id':7,'text':'&No','enabled':True}, + {'hwnd':32,'class':'Button','id':6,'text':'&Yes','enabled':True}]}] + monkeypatch.setattr(diagnostic,'_NativeSession',ForwardSession) + monkeypatch.setattr(diagnostic,'_windows',windows) + assert diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)['status']=='PASS' + assert Session.instances[-1].posted == [(31,0xF5),(10,0x10)] + + class Session: instances = [] def __init__(self, job, pid, launcher): @@ -127,6 +191,87 @@ def test_success_posts_one_exact_close_and_reports_only_open_check(diagnostic, j assert Session.instances[-1].closed +@pytest.mark.parametrize('incomplete_scan', [1, 2, 3]) +def test_transient_incomplete_scan_is_retried_without_acting_on_partial_windows(diagnostic, job, monkeypatch, incomplete_scan): + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + job['timeout'] = 1 + write_logs(job) + class ClosingSession(Session): + closing = False + def post(self, hwnd, message): + self.posted.append((hwnd, message)) + self.closing = True + monkeypatch.setattr(diagnostic, '_NativeSession', ClosingSession) + scans = [] + def windows(pid): + scans.append(True) + if len(scans) == incomplete_scan: + raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s') + if Session.instances[-1].closing: + Session.instances[-1].alive = False + return [] + return [frame(job)] + monkeypatch.setattr(diagnostic, '_windows', windows) + events = [] + result = diagnostic.check_target_window(job, 42, emit=lambda **event:events.append(event), error_reader=lambda:None) + assert result['status'] == 'PASS' + assert Session.instances[-1].posted == [(10, 0x10)] + assert any(e['stage'] == 'diagnostic_window_retry' for e in events) + + +def test_incomplete_scans_keep_original_open_deadline_and_never_close(diagnostic, job, monkeypatch): + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + monkeypatch.setattr(diagnostic, '_NativeSession', Session) + calls = [] + def windows(pid): + calls.append(True) + raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s') + monkeypatch.setattr(diagnostic, '_windows', windows) + with pytest.raises(RuntimeError, match='DIAGNOSTIC_WINDOW_LIMIT'): + diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None) + assert len(calls) <= 3 + assert Session.instances[-1].posted == [] + + +def test_cancel_during_incomplete_scan_stops_retry_without_close(diagnostic, job, monkeypatch): + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + job['timeout'] = 10 + cancel = Path(job['root']).parent/'cancel-scan' + job['cancel_signal'] = str(cancel) + monkeypatch.setattr(diagnostic, '_NativeSession', Session) + calls = [] + def windows(pid): + calls.append(True) + cancel.touch() + raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s') + monkeypatch.setattr(diagnostic, '_windows', windows) + with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'): + diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None) + assert len(calls) == 1 and Session.instances[-1].posted == [] + + +def test_incomplete_close_scan_cannot_extend_thirty_second_deadline(diagnostic, job, monkeypatch): + job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) + write_logs(job) + clock, offset = diagnostic.time.monotonic, [0] + monkeypatch.setattr(diagnostic.time, 'monotonic', lambda:clock()+offset[0]) + class ClosingSession(Session): + closing = False + def post(self, hwnd, message): + self.posted.append((hwnd, message)) + self.closing = True + monkeypatch.setattr(diagnostic, '_NativeSession', ClosingSession) + def windows(pid): + if Session.instances[-1].closing: + offset[0] = 31 + raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s') + return [frame(job)] + monkeypatch.setattr(diagnostic, '_windows', windows) + with pytest.raises(RuntimeError, match='DIAGNOSTIC_WINDOW_LIMIT'): + diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None) + assert Session.instances[-1].posted == [(10, 0x10)] + + def test_transient_startup_window_cannot_abort_before_target_is_loaded(diagnostic, job, monkeypatch): job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) write_logs(job) @@ -336,3 +481,37 @@ def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monke monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99)) with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'): session.post(10, 0x10) + + +@pytest.mark.parametrize('fault', ['', 'foreign_pid', 'cycle', 'other_frame', 'visible', 'enabled', 'class', 'title', 'desktop', 'incomplete', 'filename']) +def test_diagnostic_save_accepts_only_complete_hidden_owner_chain(diagnostic, job, fault): + target = frame(job) + owner = {'hwnd': 15, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB', + 'owner': 10, 'visible': False, 'enabled': False, 'same_desktop': True} + end = {**target, 'same_desktop': True} + window = {'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB', + 'owner': 15, 'owner_chain': [owner, end], 'children': [ + {'hwnd': 30, 'class': 'Static', 'text': 'Save changes to IP101GR.pcb?', 'id': -1}, + {'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7}, + {'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6}, + {'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]} + if fault == 'foreign_pid': owner['pid'] = 99 + if fault == 'cycle': owner['owner'] = 15 + if fault == 'other_frame': end['hwnd'] = 99 + if fault == 'visible': owner['visible'] = True + if fault == 'enabled': owner['enabled'] = True + if fault == 'class': owner['class'] = 'VendorDialog' + if fault == 'title': owner['text'] = 'Unknown recovery' + if fault == 'desktop': owner['same_desktop'] = False + if fault == 'incomplete': window['owner_chain'] = [owner] + if fault == 'filename': window['children'][0]['text'] = 'Save changes to Foreign.pcb?' + session = Session(job, 42, None) + action = lambda:diagnostic._pending_prompt([window], closing=True, frame=target, + session=session, clicked=set(), pcb_name='IP101GR.pcb') + if not fault: + assert action() is False + assert session.posted == [(31, 0xF5)] + else: + with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'): + action() + assert session.posted == [] diff --git a/tests/test_dialog_probe.py b/tests/test_dialog_probe.py index 736a6f4..500ddaa 100644 --- a/tests/test_dialog_probe.py +++ b/tests/test_dialog_probe.py @@ -179,3 +179,13 @@ def test_probe_skips_project_integration_panel_during_com_phase(): snapshots = make_probe(gui, (10,)).capture(DialogPhase.PROJECT_INTEGRATION) assert snapshots == () + + +def test_save_integration_panel_uses_complete_win32_controls_without_huge_uia_tree(): + gui=FakeGui({10:{'class_name':'#32770','text':'Project Integration','owner':99}, + 11:{'class_name':'Button','text':'&Close','control_id':2}},children={10:(11,)}) + probe=make_probe(gui,(10,),FakeUia(error=AssertionError('unnecessary large UIA panel scan'))) + probe.process_name_reader=lambda _: 'ExpeditionPCB.exe' + snapshot=probe.capture(DialogPhase.SAVE,pids={1010})[0] + assert snapshot.controls[0].control_id==2 + assert snapshot.diagnostics==() diff --git a/tests/test_dialog_rules.py b/tests/test_dialog_rules.py index 7e252f2..7a2d578 100644 --- a/tests/test_dialog_rules.py +++ b/tests/test_dialog_rules.py @@ -15,6 +15,15 @@ from cbb_refresh_verify.dialog_rules import ( ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets" +def test_diagnostic_forward_prompt_is_observed_while_ordinary_verify_still_confirms(): + text = 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?' + snapshot = prompt(text) + ordinary = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json')) + diagnostic = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json', diagnostic_only=True)) + assert ordinary.action == 'confirm_forward_annotation' + assert diagnostic.category == 'OBSERVE_PROGRESS' and not diagnostic.action + + def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770", control_types=("Text", "Button")): controls = tuple( @@ -244,3 +253,41 @@ def test_database_open_failure_is_classified_and_declines_log_view(): assert decision.category == 'FATAL_ACK' assert decision.error_code == 'MENTOR_DATABASE_LOAD_FAILED' assert dict(decision.target)['control_id'] == 7 # IDNO, never launch another log viewer + + +def completed_integration_panel(): + texts={1033:'No connectivity changes to be forward annotated', + 1032:'No pending schematic CES changes to load into PCB', + 1035:'No pending PCB changes to be back annotated', + 1034:'No pending CES changes to load into PCB'} + return WindowSnapshot(hwnd=10,pid=20,process_name='ExpeditionPCB.exe',process_role='pcb', + window_class='#32770',title='Project Integration',phase=DialogPhase.SAVE,owner_hwnd=99, + controls=(ControlSnapshot(handle=12,control_id=2,class_name='Button',name='&Close'), + *(ControlSnapshot(handle=i,control_id=i,class_name='Static',name=text) for i,text in texts.items()))) + + +@pytest.mark.parametrize('phase',[DialogPhase.SAVE,DialogPhase.CLOSE]) +def test_completed_integration_panel_only_closes_its_exact_close_control(phase): + from dataclasses import replace + decision=decide(replace(completed_integration_panel(),phase=phase),load_rules(ASSETS/'dialog_rules.v1.json')) + assert decision.action=='close_completed_integration' + assert decision.channels==('win32_button_click',) + assert dict(decision.target)=={'control_id':2} + assert decision.postcondition=='window_gone' and not decision.error_code + + +@pytest.mark.parametrize('fault',['pending','missing','duplicate','partial','foreign','unowned','disabled','early','error']) +def test_integration_panel_without_complete_owned_idle_proof_never_closes(fault): + from dataclasses import replace + panel=completed_integration_panel() + if fault=='pending': panel=replace(panel,controls=(*panel.controls[:-1],replace(panel.controls[-1],name='CES changes are pending'))) + elif fault=='missing': panel=replace(panel,controls=panel.controls[:-1]) + elif fault=='duplicate': panel=replace(panel,controls=(*panel.controls,panel.controls[-1])) + elif fault=='partial': panel=replace(panel,diagnostics=('WINDOW_ENUM_INCOMPLETE',)) + elif fault=='foreign': panel=replace(panel,process_name='Unrelated.exe',process_role='unknown') + elif fault=='unowned': panel=replace(panel,owner_hwnd=0) + elif fault=='disabled': panel=replace(panel,controls=(replace(panel.controls[0],enabled=False),*panel.controls[1:])) + elif fault=='early': panel=replace(panel,phase=DialogPhase.DOCUMENT_ATTACH) + elif fault=='error': panel=replace(panel,controls=(*panel.controls, + ControlSnapshot(handle=500,control_id=500,class_name='Static',name='There were errors during Project Integration.'))) + assert decide(panel,load_rules(ASSETS/'dialog_rules.v1.json')).action!='close_completed_integration' diff --git a/tests/test_extended_safety.py b/tests/test_extended_safety.py index f6c2329..1ec0be5 100644 --- a/tests/test_extended_safety.py +++ b/tests/test_extended_safety.py @@ -54,7 +54,7 @@ def test_preflight_rejects_pcb_junction_outside_current_block(tmp_path): preflight(VerifyRequest(library, 'CBB', tmp_path/'evidence')) -def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch): +def test_nonnative_preparation_leaves_real_host_channel_available(tmp_path, monkeypatch): from cbb_refresh_verify import verify_runner as runner entered, release = Event(), Event() calls, results = [], [] @@ -70,14 +70,14 @@ def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch): thread.start() assert entered.wait(3) try: - second = runner.run_verify(VerifyRequest(tmp_path/'lib.lmc', 'second', tmp_path/'evidence')) - assert second.status == 'BLOCKED' - assert second.safe_to_continue - assert second.error_category == 'NATIVE_CHANNEL_BUSY' + from cbb_refresh_verify.operation_queue import native_channel + with native_channel(): + pass assert calls == ['first'] finally: release.set() thread.join(6) + assert results[0].status == 'PASS' def test_recovery_retains_temporary_network_mapping(): diff --git a/tests/test_failed_startup.py b/tests/test_failed_startup.py index 57caab6..b3a04cd 100644 --- a/tests/test_failed_startup.py +++ b/tests/test_failed_startup.py @@ -7,8 +7,9 @@ from cbb_refresh_verify import failed_session, mentor_adapter def startup_fixture(tmp_path, monkeypatch): - import win32gui, win32process - from cbb_refresh_verify import native_repair_ui + from contextlib import nullcontext + import win32gui, win32process, win32event, win32con + from cbb_refresh_verify import native_repair_ui, residual_sessions job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'), 'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'), 'desktop': 'CbbVerify_test'} @@ -20,6 +21,12 @@ def startup_fixture(tmp_path, monkeypatch): records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe', f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)] monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records)) + monkeypatch.setattr(residual_sessions, '_process_handle', lambda *a, **kw: nullcontext(123)) + monkeypatch.setattr(residual_sessions, '_handle_identity', lambda h: + {'created_handle': 'original', 'image': r'C:\Mentor\wg\ExpeditionPCB.exe'}) + monkeypatch.setattr(residual_sessions, '_process_windows', lambda pids: {12: []}) + monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a: + win32con.WAIT_TIMEOUT if records else win32con.WAIT_OBJECT_0) monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test') monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg)) monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None) diff --git a/tests/test_global_stop_queue_semantics.py b/tests/test_global_stop_queue_semantics.py new file mode 100644 index 0000000..20aa405 --- /dev/null +++ b/tests/test_global_stop_queue_semantics.py @@ -0,0 +1,32 @@ +from threading import Event,Thread + +from cbb_refresh_verify.operation_queue import QueueCancelled +from test_issue15_ui_integration import window_for + + +def test_actual_global_stop_button_cancels_running_and_same_app_queued_jobs(qtbot,tmp_path,monkeypatch): + window=window_for(qtbot,tmp_path,monkeypatch) + first=window._new_job('verify',library=tmp_path/'lib.lmc') + second=window._new_job('native_session',library=tmp_path/'lib.lmc') + entered,release,waiting,done=Event(),Event(),Event(),Event();calls=[];errors=[] + def current(): + calls.append('first');entered.set();release.wait(3) + def run_first(): + try:window.native_queue.run(current,context=first.context,stop=first.context.stop) + except QueueCancelled:pass + def queued(): + try:window.native_queue.run(lambda:calls.append('second'),context=second.context, + stop=second.context.stop,waiting=waiting.set) + except QueueCancelled as error:errors.append(error) + finally:done.set() + a=Thread(target=run_first);b=Thread(target=queued) + a.start();assert entered.wait(2);b.start() + try: + qtbot.waitUntil(waiting.is_set);window._update() + assert window.stop_button.isEnabled() + window.stop_button.click() + qtbot.waitUntil(done.is_set) + assert first.context.stop.is_set() and second.context.stop.is_set() + assert calls==['first'] and len(errors)==1 + finally: + release.set();a.join(3);b.join(3) diff --git a/tests/test_icdb_batch_check.py b/tests/test_icdb_batch_check.py index 6fb3112..0bcb98b 100644 --- a/tests/test_icdb_batch_check.py +++ b/tests/test_icdb_batch_check.py @@ -1,4 +1,5 @@ """Batch ICDB checks open diagnostically without dispatching Repair.""" +from cbb_refresh_verify.ui import timed_prompt from dataclasses import replace import json @@ -93,7 +94,7 @@ def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_pa verifier=lambda req: (requests.append(req) or VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')), status_refresher=lambda names, _: {name: 'PENDING' for name in names}) - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes)) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes)) window.search_edit.setText('Beta') window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active()) assert requests[0].maintenance and not requests[0].auto_repair diff --git a/tests/test_icdb_recovery.py b/tests/test_icdb_recovery.py index 73c87a2..daf17c1 100644 --- a/tests/test_icdb_recovery.py +++ b/tests/test_icdb_recovery.py @@ -277,7 +277,8 @@ def test_contents_session_loss_records_each_item_without_launching_pcb_or_repair assert results[1].error_category == 'ICDB_REPAIR_REQUIRED' -def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch): +@pytest.mark.parametrize('fault', ['session_loss', 'inconsistent']) +def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch, fault): from test_verify_runner import fixture, request from cbb_refresh_verify.icdb_recovery import snapshot_log from cbb_refresh_verify.verify_diagnostics import failure_logs_main @@ -292,7 +293,8 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon (root/'diagnostics').mkdir() (root/'diagnostics/startup-log-baseline.json').write_text(json.dumps({ 'source': str(log), 'baseline': snapshot_log(log)}), encoding='utf-8') - log.write_text(ERROR, encoding='utf-8') + from test_issue15_native_entry import inconsistency + log.write_text(ERROR if fault == 'session_loss' else inconsistency(work/'database'), encoding='utf-8') (root/'outcome.json').write_text(json.dumps({ 'status': 'FAIL', 'stderr': 'MENTOR_DATABASE_LOAD_FAILED: opening failed', 'safe_to_continue': False}), encoding='utf-8') @@ -305,7 +307,11 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon assert result.error_category == 'ICDB_REPAIR_REQUIRED' assert result.safe_to_continue is True assert 'opening failed' in result.stderr - assert '200091-CBB' in result.stderr - assert '__ReusableBlocksSymb' in result.stderr - assert '2026-10-24 08.22.29-10308' in result.stderr + if fault == 'session_loss': + assert '200091-CBB' in result.stderr + assert '__ReusableBlocksSymb' in result.stderr + assert '2026-10-24 08.22.29-10308' in result.stderr + else: + assert str(work/'database') in result.stderr + assert '未修复' in result.stderr assert json.loads(result.evidence_path.read_text('utf-8'))['error_category'] == 'ICDB_REPAIR_REQUIRED' diff --git a/tests/test_import_without_export_gate.py b/tests/test_import_without_export_gate.py index ed7f911..ae1631d 100644 --- a/tests/test_import_without_export_gate.py +++ b/tests/test_import_without_export_gate.py @@ -1,4 +1,5 @@ """Normal imports must not depend on optional schematic export tools.""" +from cbb_refresh_verify.ui import timed_prompt from dataclasses import replace import json @@ -57,7 +58,7 @@ def test_bad_source_row_does_not_prevent_valid_rows_from_starting(qtbot, tmp_pat r.auto_verify, 'complete', 'UPLOAD_FAILED' if r.name == 'Missing' else 'UPLOADED', True, 'per-item result') for r in requests] dialog = ManagementDialog(rows, runner=runner); qtbot.addWidget(dialog) - monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_kw: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *_a, **_kw: QMessageBox.Yes) dialog.execute_button.click() qtbot.waitUntil(lambda: bool(seen) and not dialog.busy) assert [r.name for r in seen] == ['Missing', 'Good'] @@ -96,7 +97,7 @@ def test_native_project_normalization_is_a_recorded_difference_not_import_failur def worker(adapter, job, evidence): result = original_worker(adapter, job, evidence) if job['operation'] == 'add' and result.get('success'): - project = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj' + project = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj' with project.open('a') as stream: stream.write('SECTION VBPCBIndicators\nKEY VBPCBForwardAnno "0"\nKEY CADBackAnno "0"\nENDSECTION\n') return result @@ -105,7 +106,7 @@ def test_native_project_normalization_is_a_recorded_difference_not_import_failur assert result.status == 'UPLOADED' and result.safe_to_continue, result.detail comparison = json.loads((result.evidence_path.parent/'add/identity-comparison.json').read_text()) assert comparison['identity_matches'] and not comparison['assets_match'] - assert 'Source.prj' in comparison['asset_differences']['modified'] + assert 'Block.prj' in comparison['asset_differences']['modified'] @pytest.mark.parametrize('registered_top,expected', [('Block', 'UPLOADED'), ('Foreign', 'RECOVERY_REQUIRED')]) @@ -116,7 +117,7 @@ def test_native_top_block_may_match_registration_name_but_not_an_unrelated_name( def worker(adapter, job, evidence): result = original_worker(adapter, job, evidence) if job['operation'] == 'add' and result.get('success'): - project = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj' + project = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj' project.write_text(project.read_text().replace('KEY RootBlock "Top"', f'KEY RootBlock "{registered_top}"')) return result monkeypatch.setattr(native.NativeManagementAdapter, '_worker', worker) diff --git a/tests/test_issue15_confirmed_management_retry.py b/tests/test_issue15_confirmed_management_retry.py new file mode 100644 index 0000000..e716295 --- /dev/null +++ b/tests/test_issue15_confirmed_management_retry.py @@ -0,0 +1,68 @@ +"""A fresh confirmed operation may recover data; historical requests never replay.""" +from dataclasses import replace +import json +from pathlib import Path + +import pytest + +from test_management import setup, execute + + +@pytest.mark.parametrize('proof_case', ['fresh','none','wrong_library','wrong_block','cached','live_writer']) +def test_confirmed_retry_requires_fresh_exact_resource_proof(setup,monkeypatch,proof_case): + request,adapter,source=setup + old=request.evidence_dir/'old';old.mkdir(parents=True) + record={'operation':'update','library':str(request.library),'name':'Block','stage':'complete', + 'status':'RECOVERY_REQUIRED','safe_to_continue':True,'history':[{'stage':'native_add'}]} + path=old/'checkpoint.json';path.write_text(json.dumps(record));before=path.read_bytes() + observed=[] + def proof(library,evidence,*,block_name,required,**kw): + observed.append((library,evidence,block_name,required)) + if proof_case=='live_writer':raise RuntimeError('NATIVE_WRITER_ACTIVE') + if proof_case=='none':return None + target=library if proof_case!='wrong_library' else library.with_name('other.lmc') + block=block_name if proof_case!='wrong_block' else 'Other' + receipt=(old if proof_case=='cached' else evidence/'fresh')/'release.json' + receipt.parent.mkdir(parents=True,exist_ok=True) + result={'status':'RELEASE_CONFIRMED','lease_state':'RELEASED','library':str(target), + 'proof_scope':'BLOCK','proof_block_names':[block], + 'resource_scope':{'scope_state':'OBSERVED','library':str(target),'block_names':[block]}, + 'evidence_path':str(receipt)} + receipt.write_text(json.dumps(result));return result + monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release',proof) + result=execute(replace(request,operation='update',source=source,auto_verify=False,check_previous_release=True),adapter) + assert observed and observed[0][2:]==('Block',True) + assert path.read_bytes()==before + if proof_case=='fresh': + assert result.status=='UPLOADED' and result.safe_to_continue + assert adapter.calls[0]=='remove' and adapter.calls[1][0]=='add' + else: + assert result.status=='BLOCKED' and adapter.calls==[] + + +def test_old_request_without_current_confirmation_remains_blocked(setup,monkeypatch): + request,adapter,source=setup + old=request.evidence_dir/'old';old.mkdir(parents=True) + (old/'checkpoint.json').write_text(json.dumps({'library':str(request.library),'name':'Block', + 'stage':'complete','status':'RECOVERY_REQUIRED','safe_to_continue':True,'history':[{'stage':'native_add'}]})) + result=execute(replace(request,operation='update',source=source,auto_verify=False),adapter) + assert result.status=='BLOCKED' and adapter.calls==[] + + +def test_ui_adds_fresh_recheck_only_after_current_yes(qtbot,tmp_path,monkeypatch): + from PySide6.QtWidgets import QMessageBox + from cbb_refresh_verify.management import ManagementRequest,ManagementResult + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + from cbb_refresh_verify.ui import timed_prompt + request=ManagementRequest('remove',tmp_path/'lib.lmc','Block') + captured=[] + def runner(requests,**kw): + captured.extend(requests) + return [ManagementResult('remove',request.library,'Block','Logical-Physical',None,False,'complete','REMOVED',True)] + dialog=ManagementDialog([request],runner=runner);qtbot.addWidget(dialog);dialog.show() + answer=[QMessageBox.No] + monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:answer[0]) + dialog._execute();assert not captured and not dialog.requests()[0].check_previous_release + answer[0]=QMessageBox.Yes;dialog._execute() + qtbot.waitUntil(lambda:not dialog.busy) + assert len(captured)==1 and captured[0].check_previous_release diff --git a/tests/test_issue15_manifest_progress.py b/tests/test_issue15_manifest_progress.py new file mode 100644 index 0000000..b42cbbb --- /dev/null +++ b/tests/test_issue15_manifest_progress.py @@ -0,0 +1,135 @@ +"""Large advancing manifests stay usable; a stalled member still hands off.""" +from threading import Event +import time + +import pytest + +from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, check_active +from cbb_refresh_verify.scoped_manifest import build_manifest, hash_file + + +def test_advancing_manifest_outlives_aggregate_metadata_deadline(tmp_path, monkeypatch): + for i in range(768): + (tmp_path/f'part-{i:04}.dat').write_bytes(str(i).encode()) + clock, offset = time.monotonic, [0] + monkeypatch.setattr(time, 'monotonic', lambda:clock()+offset[0]) + def progress(event): + if event['hashed_files']: + offset[0] += 8 + time.sleep(.06) # Let the actual context waiter observe each advancing batch. + context = BatchTaskContext(str(tmp_path/'library.lmc'), native_policy='external') + try: + result = context.run(lambda:build_manifest(tmp_path, progress=progress), timeout_seconds=10) + assert len(result['files']) == 768 + assert offset[0] == 24 + finally: + context.close(timeout_seconds=2) + + +def test_stalled_manifest_member_cannot_resume_into_native_write(tmp_path): + (tmp_path/'one.dat').write_bytes(b'content') + entered, release = Event(), Event() + writes = [] + def stalled(path): + entered.set() + assert release.wait(3) + return hash_file(path) + def action(): + build_manifest(tmp_path, hash_function=stalled) + check_active() + writes.append('native') + context = BatchTaskContext(str(tmp_path/'library.lmc'), native_policy='external') + try: + with pytest.raises(TaskHandoff): + context.run(action, timeout_seconds=.1) + assert entered.is_set() + release.set() + context.close(timeout_seconds=2) + assert writes == [] + finally: + release.set() + + +def test_manifest_progress_does_not_interrupt_admitted_native_continuation(tmp_path): + from cbb_refresh_verify.operation_queue import native_phase + (tmp_path/'one.dat').write_bytes(b'content') + context = BatchTaskContext(str(tmp_path/'library.lmc')) + effects = [] + def transaction(): + with native_phase(): + effects.append('Remove') + context.cancel() + assert len(build_manifest(tmp_path)['files']) == 1 + effects.append('Add') + context.run(transaction) + assert effects == ['Remove', 'Add'] + + +def test_completed_release_and_idle_checks_outlive_aggregate_deadline(tmp_path, monkeypatch): + from cbb_refresh_verify import library_lock, owner_probe + from cbb_refresh_verify.backup_recovery import _idle_check + library = tmp_path/'library.lmc'; library.touch() + clock, offset = time.monotonic, [0] + monkeypatch.setattr(time, 'monotonic', lambda:clock()+offset[0]) + def released(*args, **kwargs): + offset[0] += 7 + return {'status': 'RELEASE_CONFIRMED'} + def owners(names): + offset[0] += 4 + time.sleep(.06) + return [] + monkeypatch.setattr(library_lock, 'release_retained_library', released) + monkeypatch.setattr(owner_probe, 'query_owners', owners) + context = BatchTaskContext(str(library), native_policy='external') + def prepare(): + library_lock.recheck_previous_release(library, tmp_path/'evidence', required=True) + for name in ('target', 'source'): + _idle_check(library, tmp_path/name/'main.prj', tmp_path/name/'PCB/main.pcb') + check_active() + return 'ready for native dispatch' + try: + assert context.run(prepare, timeout_seconds=10) == 'ready for native dispatch' + assert offset[0] == 15 + finally: + context.close(timeout_seconds=2) + + +@pytest.mark.parametrize('cancel', [False, True]) +def test_completed_idle_check_cannot_revive_stalled_or_cancelled_work(tmp_path, monkeypatch, cancel): + from cbb_refresh_verify import owner_probe + from cbb_refresh_verify.backup_recovery import _idle_check + from cbb_refresh_verify.operation_queue import QueueCancelled + library = tmp_path/'library.lmc'; library.touch() + release = Event(); writes = [] + context = BatchTaskContext(str(library), native_policy='external') + def owners(names): + if cancel: context.cancel() + else: assert release.wait(3) + return [] + monkeypatch.setattr(owner_probe, 'query_owners', owners) + def prepare(): + _idle_check(library, tmp_path/'main.prj', tmp_path/'PCB/main.pcb') + writes.append('dispatch') + try: + with pytest.raises(QueueCancelled): + context.run(prepare, timeout_seconds=.1) + release.set(); context.close(timeout_seconds=2) + assert writes == [] + finally: + release.set() + + +def test_successful_idle_check_does_not_abort_admitted_native_continuation(tmp_path, monkeypatch): + from cbb_refresh_verify import owner_probe + from cbb_refresh_verify.backup_recovery import _idle_check + from cbb_refresh_verify.operation_queue import native_phase + library = tmp_path/'library.lmc'; library.touch() + monkeypatch.setattr(owner_probe, 'query_owners', lambda names: []) + context = BatchTaskContext(str(library)); writes = [] + def transaction(): + with native_phase(): + writes.append('Remove'); context.cancel() + _idle_check(library, tmp_path/'main.prj', tmp_path/'PCB/main.pcb') + writes.append('Add') + context.run(transaction) + assert writes == ['Remove', 'Add'] diff --git a/tests/test_issue15_metadata_context.py b/tests/test_issue15_metadata_context.py new file mode 100644 index 0000000..cb60498 --- /dev/null +++ b/tests/test_issue15_metadata_context.py @@ -0,0 +1,38 @@ +from threading import Event +import pytest +from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_phase + + +def test_metadata_can_refresh_while_abandoned_native_scope_stays_protected(): + entered, release = Event(), Event() + old = BatchTaskContext('a.lmc') + def stalled(): + entered.set(); release.wait(3) + try: + with pytest.raises(TaskHandoff): old.run(stalled, timeout_seconds=.01) + assert entered.is_set() + new = BatchTaskContext('a.lmc') + assert new.run(lambda: 'metadata', metadata_only=True) == 'metadata' + with pytest.raises(TaskHandoff): new.run(lambda: 'native') + finally: + release.set(); old.close(timeout_seconds=1) + + +def test_metadata_cannot_escalate_into_native_phase(): + context = BatchTaskContext('a.lmc') + def escalate(): + with native_phase(): + pytest.fail('metadata admitted native action') + with pytest.raises(RuntimeError, match='metadata'): + context.run(escalate, metadata_only=True) + + +def test_abandoned_metadata_does_not_block_next_native_admission(): + release = Event() + old = BatchTaskContext('a.lmc') + try: + with pytest.raises(TaskHandoff): + old.run(lambda: release.wait(3), timeout_seconds=.01, metadata_only=True) + assert BatchTaskContext('a.lmc').run(lambda: 'admitted') == 'admitted' + finally: + release.set(); old.close(timeout_seconds=1) diff --git a/tests/test_issue15_native_entry.py b/tests/test_issue15_native_entry.py new file mode 100644 index 0000000..40ac413 --- /dev/null +++ b/tests/test_issue15_native_entry.py @@ -0,0 +1,407 @@ +"""Issue 15 recovery entry regressions. Native boundaries never launch Mentor.""" +from contextlib import contextmanager +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +@pytest.fixture(autouse=True) +def no_real_owner_probe(monkeypatch): + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: []) + + +def test_ordinary_worker_aligns_both_bound_projects_and_retains_each_original(tmp_path, monkeypatch): + from test_verify_worker_stability import exercise_worker + from cbb_refresh_verify import mentor_adapter as adapter + job, events, execute = exercise_worker(tmp_path, monkeypatch) + main = Path(job['project']); aux = Path(job['pcb']).parent/'pcb.prj' + original_main = b'KEY CentralLibrary "old-main.lmc"\r\n#\x81\x40\r\n' + original_aux = b'\xff\xfe'+ 'KEY CentralLibrary "old-pcb.lmc"\r\n'.encode('utf-16-le') + main.write_bytes(original_main); aux.write_bytes(original_aux) + assert execute()['status'] == 'PASS' + from cbb_refresh_verify.backup_recovery import _project_text + for path in (main, aux): + import re + reference = re.search(r'KEY CentralLibrary "([^"]+)"', _project_text(path))[1] + assert (path.parent/reference).resolve() == Path(job['lmc_file']).resolve() + saved = [p.read_bytes() for p in (Path(job['root'])/'diagnostics').rglob('*.before-central-library')] + assert original_main in saved and original_aux in saved + + +def test_ordinary_legacy_binding_never_rewrites_template(tmp_path, monkeypatch): + from test_verify_worker_stability import exercise_worker + job, _, execute = exercise_worker(tmp_path, monkeypatch) + main = Path(job['project']); pcb = Path(job['pcb']) + main.write_text('KEY CentralLibrary "old.lmc"\n') + pcb.write_text('KEY ProjectFile "../CBB.prj"\n') + template = pcb.parent/'template.prj'; template.write_text('KEY CentralLibrary "do-not-touch.lmc"\n') + original = template.read_bytes() + assert execute()['status'] == 'PASS' + assert template.read_bytes() == original + assert 'old.lmc' not in main.read_text() + + +def inconsistency(database): + return (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. ' + "Please use iCDB Project Backup 'Repair project' functionality to fix this issue.") + + +def test_current_inconsistency_has_structured_database_and_old_error_is_not_reused(tmp_path): + from cbb_refresh_verify import icdb_recovery as recovery, mentor_adapter as adapter + source = tmp_path/'LogFiles/PCBLogFile.txt'; source.parent.mkdir() + db = tmp_path/'database'; message = inconsistency(db) + source.write_text(message+'\n') + baseline = recovery.snapshot_log(source) + assert recovery.read_log_failure(source, baseline)[1] is None + source.write_text('new header\n'+message+'\n') + assert recovery.read_log_failure(source, baseline)[1] is None + baseline = recovery.snapshot_log(source) + with source.open('a') as stream: stream.write(message+'\n') + text, record = recovery.read_log_failure(source, baseline) + assert record['database_path'] == str(db) and record['scope'] == 'project' + assert record['kind'] == 'database_inconsistent' + detail = adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline) + assert 'ICDB_REPAIR_REQUIRED' in detail and str(db) in detail and '未修复' in detail + + +def test_manual_repair_selects_diagnosed_bound_database_without_layout_or_healthy_header(tmp_path): + from test_native_backup import project_fixture + from cbb_refresh_verify import native_backup as native + request, main = project_fixture(tmp_path) + pcb = main.parent/'PCB/Block.pcb'; pcb.parent.mkdir() + pcb.write_text('KEY ProjectFile "../Block.prj"\n') + aux = pcb.parent/'pcb.prj'; aux.write_text('KEY iCDBDir "database"\n') + for prj in (main, aux): + (prj.parent/'database').mkdir(); (prj.parent/'database/icdb.dat').write_bytes(b'not-a-healthy-header') + assert native.native_backup_target(request, mode='repair')[0] == main + assert native.native_backup_target(request, mode='repair', target_database=aux.parent/'database')[0] == aux + with pytest.raises(ValueError, match='TARGET'): + native.native_backup_target(request, mode='repair', target_database=tmp_path/'foreign') + + +def test_versions_launcher_rechecks_parent_retained_lease_and_persists_before_gate(tmp_path, monkeypatch): + import subprocess, sys + from test_native_backup import project_fixture + from cbb_refresh_verify import native_backup as native, library_lock, session_record + request, project = project_fixture(tmp_path) + monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe') + calls = [] + monkeypatch.setattr(library_lock, 'recheck_previous_release', lambda *a, **k: calls.append('recheck')) + monkeypatch.setattr(session_record, 'process_identity', lambda pid: dict(pid=pid, created='now', executable='python', owner='test')) + child = subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True) + def spawn(command, **kw): + job = json.loads(Path(command[-1]).read_text()) + assert calls == ['recheck'] and not Path(job['start_gate']).exists() + calls.append('spawn') + return child + monkeypatch.setattr(native.subprocess, 'Popen', spawn) + try: + session = native.launch_native_backup(request, mode='repair') + finally: + child.communicate('\n',timeout=5) + record = json.loads(session.job.read_text()) + assert Path(record['start_gate']).is_file() + assert Path(record['session_record_path']).is_file() + assert session.mode == 'repair' and session.database == project.parent/'database' + assert session.operation_id == record['operation_id'] + assert record['automatic_repair'] is False + + +@pytest.mark.parametrize('failure', ['spawn', 'registration']) +def test_backup_failure_leaves_start_gate_closed(tmp_path, monkeypatch, failure): + from test_native_backup import project_fixture + from cbb_refresh_verify import native_backup as native, session_record + request, _ = project_fixture(tmp_path) + monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe') + def spawn(*a, **k): + if failure == 'spawn': raise OSError('start failed') + return SimpleNamespace(pid=123, poll=lambda: None) + monkeypatch.setattr(native.subprocess, 'Popen', spawn) + monkeypatch.setattr(session_record, 'register_worker_session', lambda *a: (_ for _ in ()).throw(OSError('register failed'))) + with pytest.raises(OSError): native.launch_native_backup(request) + job = next(request.evidence_dir.glob('native-backup-*/request.json')) + record = json.loads(job.read_text()) + assert not Path(record['start_gate']).exists() + assert Path(record['cancel_signal']).exists() + + +def test_changed_prj_bytes_refused_before_recovery_tool_dispatch(tmp_path, monkeypatch): + import hashlib + from test_native_backup import project_fixture + from cbb_refresh_verify import native_backup as native + request, project = project_fixture(tmp_path) + job = tmp_path/'request.json' + record = dict(library=str(request.lmc_file), block=request.block_name, project=str(project), + project_sha256=hashlib.sha256(project.read_bytes()).hexdigest()) + job.write_text(json.dumps(record)) + project.write_text(project.read_text()+'# changed identity\n') + monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe') + assert native.native_backup_worker_main(job, process_factory=lambda *a: pytest.fail('changed PRJ dispatched')) == 1 + assert '身份' in json.loads(job.with_name('result.json').read_text('utf-8'))['detail'] + + +def test_real_parent_retained_sidecar_is_reconciled_before_child_acquires_it_and_reopens(tmp_path, monkeypatch): + import subprocess, sys + from test_native_backup import project_fixture + from cbb_refresh_verify import native_backup as native, library_lock as locks + from cbb_refresh_verify.file_probe import hold_release_files + request, _ = project_fixture(tmp_path) + with locks.LibraryLock(request.lmc_file, safe_to_release=lambda: False, block_name='Block') as retained: + pass + @contextmanager + def proof(library, **kwargs): + with hold_release_files(library, (library.parent/'ReusableBlocksLP/Block/Work',)) as files: + yield {**files, 'native_owners': []} + monkeypatch.setattr(locks, '_prove_library_released', proof) + monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'not-launched.exe') + popen = subprocess.Popen + script = ( + 'import json,sys\nfrom pathlib import Path\n' + 'from cbb_refresh_verify.desktop_worker import run_native_worker\n' + 'from cbb_refresh_verify.library_lock import LibraryLock\n' + 'def action(path):\n' + ' j=json.loads(Path(path).read_text())\n' + ' with LibraryLock(j["library"],checkpoint=False):\n' + ' Path(path).with_name("child-acquired").write_text("owned")\n' + ' return 0\n' + 'raise SystemExit(run_native_worker(action,sys.argv[1]))\n') + def spawn(command, **kwargs): + if '--native-backup-worker' in command: + assert not locks.has_retained_library(request.lmc_file) + return popen([sys.executable, '-c', script, command[-1]], **kwargs) + return popen(command, **kwargs) + monkeypatch.setattr(native.subprocess, 'Popen', spawn) + try: + for mode in ('versions', 'repair'): + session = native.launch_native_backup(request, mode=mode) + assert session.process.wait(10) == 0 + assert session.job.with_name('child-acquired').read_text() == 'owned' + assert retained.path.is_file() + finally: + owner = locks._owners.pop(retained.key, None) + if owner: owner['handle'].Close() + + +def test_native_registration_failure_never_resumes_suspended_child(tmp_path): + import sys + from cbb_refresh_verify.native_backup import _NativeBackupProcess + marker = tmp_path/'must-not-run' + def refuse(process): raise OSError('required identity journal failed') + with pytest.raises(OSError, match='journal'): + _NativeBackupProcess([sys.executable, '-c', f'from pathlib import Path;Path({str(marker)!r}).touch()'], + tmp_path, before_resume=refuse) + assert not marker.exists() + + +def test_independent_backup_job_registration_retains_descendants_after_caller_handles_close(tmp_path): + import sys, time + from cbb_refresh_verify.native_backup import _NativeBackupProcess, _BackupJobWriter + script = tmp_path/'parent.py'; marker = tmp_path/'child.pid' + script.write_text('import subprocess,sys,time\nfrom pathlib import Path\n' + 'p=subprocess.Popen([sys.executable,"-c","import time;time.sleep(1)"])\n' + f'Path({str(marker)!r}).write_text(str(p.pid))\ntime.sleep(.1)\n') + process = _NativeBackupProcess([sys.executable, str(script)], tmp_path) + registered = _BackupJobWriter(process.job) + try: + deadline = time.monotonic()+5 + while process.poll() is None and time.monotonic()1 else 'Tip of the Day' + return 'OK' + monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(h, arg) for h in sorted(visible)]) + monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: + [fn(h, arg) for h in ((201, 202) if obstacle == 'duplicate' else (201,))] if hwnd == 200 else None) + monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__) + monkeypatch.setattr(win32gui, 'GetWindowText', title) + monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: 1) + def post(hwnd, message, wparam, lparam): + messages.append((hwnd, message)) + if hwnd == 201: visible.remove(200) + elif hwnd == 100: records.clear() + monkeypatch.setattr(win32gui, 'PostMessage', post) + result = close_failed_startup(job, 12, timeout_seconds=0) + if obstacle: + assert result['status'] == 'RETAINED' and not messages + else: + assert result['status'] == 'CLOSED' + assert messages == [(201, win32con.BM_CLICK), (100, win32con.WM_CLOSE)] + + +def test_late_release_recheck_is_bounded_and_keeps_business_failure(tmp_path, monkeypatch): + from cbb_refresh_verify.operation_lifecycle import recheck_failed_release + from cbb_refresh_verify.verify_runner import VerifyResult + from cbb_refresh_verify.session_record import write_session_record + library = tmp_path/'A/lib.lmc' + library.parent.mkdir() + library.touch() + evidence = tmp_path/'evidence' + evidence.mkdir() + result = VerifyResult('FAIL', stderr='native business failure', safe_to_continue=False, + evidence_path=evidence/'result.json') + result.evidence_path.write_text('{}') + record = evidence/'session.json' + write_session_record(record, dict(operation_id='failed', library=str(library), block='A', processes=[])) + entered, resume = Event(), Event() + original = Path.open + def withheld(path, *args, **kwargs): + if path == record: + entered.set() + assert resume.wait(3) + return original(path, *args, **kwargs) + monkeypatch.setattr(Path, 'open', withheld) + try: + started = time.monotonic() + returned = recheck_failed_release(library, 'A', result, timeout_seconds=.05) + assert time.monotonic()-started < .8 + assert entered.is_set() and returned is result + assert returned.status == 'FAIL' and not returned.safe_to_continue + finally: + resume.set() + + +def test_batch_context_cancel_records_all_remaining_items_and_new_batch_can_run(tmp_path): + from cbb_refresh_verify.operation_queue import BatchTaskContext + from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, run_batch + requests = [VerifyRequest(tmp_path/'lib.lmc', name, tmp_path/'evidence') for name in ('A', 'B', 'C')] + first = BatchTaskContext(library=str(requests[0].lmc_file), targets=('A', 'B', 'C')) + events = [] + def verify(request): + first.cancel() + return VerifyResult('CANCELLED') + results = run_batch(requests, verifier=verify, context=first, + progress=lambda name, result: events.append((name, result.status))) + assert [r.status for r in results] == ['CANCELLED', 'SKIPPED', 'SKIPPED'] + assert events == [('A', 'CANCELLED'), ('B', 'SKIPPED'), ('C', 'SKIPPED')] + second = BatchTaskContext(library=str(requests[0].lmc_file), targets=('A',)) + assert run_batch(requests[:1], verifier=lambda _: VerifyResult('PASS'), context=second)[0].status == 'PASS' + + +def test_batch_retention_matches_normalized_library_alias_not_business_failure(tmp_path): + from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, run_batch + library = tmp_path/'A/lib.lmc' + alias = tmp_path/'A/sub/../lib.lmc' + requests = [VerifyRequest(path, block, tmp_path/'evidence') for path, block in ( + (library, 'A'), (alias, 'B'), (tmp_path/'B/lib.lmc', 'C'), (tmp_path/'B/lib.lmc', 'D'))] + calls = [] + def verify(request): + calls.append(request.block_name) + return VerifyResult('FAIL', safe_to_continue=request.block_name != 'A') + results = run_batch(requests, verifier=verify) + assert calls == ['A', 'C', 'D'] + assert [r.status for r in results] == ['FAIL', 'SKIPPED', 'FAIL', 'FAIL'] + + +def test_queue_close_has_one_deadline_and_reports_pending_scope(tmp_path): + from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff + queue = NativeQueue() + context = BatchTaskContext(library=str(tmp_path/'A.lmc'), aliases=('Z:/A.lmc',)) + entered, resume, finished = Event(), Event(), Event() + def action(): + entered.set() + resume.wait(3) + def run(): + try: + queue.run(action, context=context) + except TaskHandoff: + pass + finally: + finished.set() + thread = Thread(target=run) + thread.start() + try: + assert entered.wait(2) + started = time.monotonic() + states = queue.close(timeout_seconds=.05) + assert time.monotonic()-started < .5 + assert states[0]['resource_scope']['aliases'] == ['Z:/A.lmc'] + assert states[0]['pending'] == 1 + assert finished.wait(1) + finally: + resume.set() + thread.join(2) + + +@pytest.mark.parametrize('native_policy', ['legacy', 'external']) +def test_real_management_transaction_does_not_handoff_between_remove_and_add(management_setup, monkeypatch, native_policy): + from dataclasses import replace + from types import SimpleNamespace + from test_management import execute + from cbb_refresh_verify import operation_queue + from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue + request, adapter, source = management_setup + offset = [0.0] + real_clock = time.monotonic + monkeypatch.setattr(operation_queue, 'time', SimpleNamespace(monotonic=lambda: real_clock()+offset[0])) + original = adapter.remove + def slow_remove(*args): + result = original(*args) + offset[0] += 100 # Native time exceeds admission budget without timing filesystem preparation. + time.sleep(.08) # Let the real admission monitor observe the active native phase. + return result + adapter.remove = slow_remove # Native external boundary; transaction stays real. + context = BatchTaskContext(library=str(request.library), targets=('Block',), native_policy=native_policy) + result = NativeQueue().run(lambda: execute(replace(request, operation='update', + source=source, auto_verify=False), adapter), context=context, timeout_seconds=10) + assert result.status == 'UPLOADED' + assert adapter.calls[0] == 'remove' and adapter.calls[1][0] == 'add' + + +def test_busy_native_channel_before_dispatch_does_not_retain_management_library(management_setup): + from test_management import execute + from cbb_refresh_verify.operation_queue import native_channel + request, adapter, _ = management_setup + entered, resume = Event(), Event() + def owner(): + with native_channel(): + entered.set() + resume.wait(3) + thread = Thread(target=owner) + thread.start() + try: + assert entered.wait(2) + result = execute(request, adapter) + assert result.safe_to_continue and not adapter.calls + with locks.LibraryLock(request.library): + pass + finally: + resume.set() + thread.join(3) + + +def test_only_explicit_repair_inspection_can_enter_while_worker_owns_writer_barrier(tmp_path): + import json + import os + from cbb_refresh_verify.desktop_worker import worker_native_channel, run_native_worker + from cbb_refresh_verify.operation_queue import native_channel + from cbb_refresh_verify.native_repair_ui import repair_worker_main + entered, resume = Event(), Event() + def owner(): + with worker_native_channel(): + entered.set() + resume.wait(3) + thread = Thread(target=owner) + thread.start() + job = dict(root=str(tmp_path), project=str(tmp_path/'A.prj'), database=str(tmp_path/'database'), + cancel_signal=str(tmp_path/'cancel'), supervisor_pid=os.getpid(), desktop='not-private') + path = tmp_path/'repair-request.json' + try: + assert entered.wait(2) + with native_channel(inspection_only=True): + pass + with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'): + with native_channel(): + pass + for mode in (False, 'true'): + path.write_text(json.dumps({**job, 'inspection_only': mode})) + with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'): + run_native_worker(repair_worker_main, path) + path.write_text(json.dumps({**job, 'inspection_only': True})) + with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'): + run_native_worker(lambda _: pytest.fail('arbitrary worker exempted'), path) + assert run_native_worker(repair_worker_main, path) == 1 + result = json.loads((tmp_path/'repair-result.json').read_text()) + assert result['native_started'] is False + assert 'REPAIR_PRIVATE_DESKTOP_REQUIRED' in result['detail'] + finally: + resume.set() + thread.join(3) + + +def test_inspection_session_does_not_take_over_retained_writer_lease(tmp_path): + import os + import win32api + from cbb_refresh_verify.desktop_worker import DesktopWorker + library = tmp_path/'A/lib.lmc' + library.parent.mkdir() + library.touch() + with locks.LibraryLock(library, safe_to_release=lambda: False) as lease: + pass + worker = object.__new__(DesktopWorker) + worker.handle, worker.pid = win32api.GetCurrentProcess(), os.getpid() + try: + worker.bind_session(dict(operation_id='inspection', operation='inspect', inspection_only=True, + library=str(library), project=str(tmp_path/'A.prj'), session_record_path=str(tmp_path/'session.json'))) + assert locks.has_retained_library(library) + from cbb_refresh_verify.session_record import read_session_record + record = read_session_record(tmp_path/'session.json', evidence_root=tmp_path) + assert record['worker_lease_handle'] is None + finally: + with locks._guard: + owner = locks._owners.pop(lease.key, None) + if owner: owner['handle'].Close() + + +def test_handoff_preserves_known_business_result_and_save_facts(tmp_path): + from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, remember_result + from cbb_refresh_verify.verify_runner import VerifyResult + context = BatchTaskContext(library=str(tmp_path/'A.lmc')) + native_result = VerifyResult('FAIL', stderr='native failure after Save', safe_to_continue=False, + write_outcome=dict(save_state='COMMITTED', close_state='UNKNOWN')) + resume, done = Event(), Event() + def finalize(): + remember_result(native_result) + try: + resume.wait(3) + finally: + done.set() + try: + with pytest.raises(TaskHandoff) as error: + context.run(finalize, timeout_seconds=.05) + assert error.value.result is native_result + assert error.value.result.write_outcome['save_state'] == 'COMMITTED' + assert error.value.result.status == 'FAIL' + from cbb_refresh_verify.verify_runner import _handoff_verify_result + returned = _handoff_verify_result(error.value) + assert returned.status == 'FAIL' and returned.stderr == native_result.stderr + assert returned.write_outcome == native_result.write_outcome and not returned.safe_to_continue + error.value.result = VerifyResult('PASS', write_outcome=native_result.write_outcome) + unfinished = _handoff_verify_result(error.value) + assert unfinished.status == 'FAIL' and unfinished.library_flag == 'UNKNOWN' + assert not unfinished.safe_to_continue + finally: + resume.set() + assert done.wait(2) + + +def test_registered_writer_owns_process_handle_after_callers_handle_closes(monkeypatch): + import subprocess + import sys + from cbb_refresh_verify import desktop_worker + monkeypatch.setattr(desktop_worker, '_automation_clients', []) + process = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True) + entered, done = Event(), Event() + errors = [] + def run(): + try: + with desktop_worker.worker_native_channel(): + desktop_worker.register_native_writer(process) + process._handle.Close() + entered.set() + except Exception as error: + errors.append(error) + finally: + done.set() + thread = Thread(target=run) + thread.start() + try: + assert entered.wait(2) + assert not done.wait(.1), 'a closed caller handle released an unreturned writer' + with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'): + desktop_worker.assert_native_writer_idle() + finally: + process.stdin.write('\n') + process.stdin.flush() + process.stdin.close() + thread.join(3) + # The duplicate's observed exit is authoritative; the original Popen + # handle was deliberately invalidated, so do not poll it in __del__. + process.returncode = 0 + assert done.is_set() and not errors diff --git a/tests/test_issue15_task_lifecycle_review.py b/tests/test_issue15_task_lifecycle_review.py new file mode 100644 index 0000000..b399328 --- /dev/null +++ b/tests/test_issue15_task_lifecycle_review.py @@ -0,0 +1,393 @@ +"""Real lifecycle regressions from the independent Task 2 review.""" +from dataclasses import replace +from pathlib import Path +from threading import Event, Thread +import time + +import pytest + +from test_management import setup as management_setup + + +def wait_done(context): + deadline = time.monotonic()+3 + while context.snapshot()['pending'] and time.monotonic()= .2: state['tip'] = True + clock = SimpleNamespace(monotonic=lambda: state['ticks'], sleep=advance) + monkeypatch.setattr(failed_session, 'time', clock) + monkeypatch.setattr(sessions, 'time', clock) + monkeypatch.setattr(sessions, '_process_windows', lambda pids: { + 12: deepcopy(windows if state['tip'] else [dict(windows[0], enabled=True)])}) + def post(hwnd, message, *_): + messages.append((hwnd, message)) + if hwnd == 201 and message == win32con.BM_CLICK: + state['exited'] = True + records.clear() + monkeypatch.setattr(win32gui, 'PostMessage', post) + monkeypatch.setattr(sessions, '_post_window_message', + lambda w, hwnd, pid, msg: post(hwnd, msg)) + monkeypatch.setattr(sessions, '_window_desktop', lambda *a, **kw: nullcontext()) + monkeypatch.setattr(win32gui, 'GetWindow', lambda hwnd, kind: + 100 if hwnd == 200 and kind == win32con.GW_OWNER else 0) + # Revalidation reads native controls, independently of the initial snapshot. + from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase + def snapshot(hwnd, pid): + w = next(w for w in windows if w['hwnd'] == hwnd) + return WindowSnapshot(hwnd, pid, 'ExpeditionPCB.exe', 'pcb', w['class'], w['title'], + DialogPhase.PCB_STARTING, tuple(ControlSnapshot(c['hwnd'], c['id'], c['class'], + c['text'], enabled=c['enabled']) for c in w['children'])) + monkeypatch.setattr(failed_session, '_startup_snapshot', snapshot) + row = dict(pid=12, name='ExpeditionPCB.exe', scope_confirmed=True, + library=job['lmc_file'], **identity) + return job, row, records, messages, windows, state, identity + + +@pytest.mark.parametrize('launcher_exits', [True, False]) +def test_late_tip_after_first_close_exits_without_a_second_close(tmp_path, monkeypatch, launcher_exits): + import win32con + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + launcher = SimpleNamespace(pid=11, poll=lambda: + 0 if launcher_exits and state['exited'] and state['ticks'] >= .6 else None) + events = [] + result = failed_session.close_failed_startup(job, 12, launcher_process=launcher, + timeout_seconds=1, emit=lambda **event: events.append(event)) + assert messages == [(100, win32con.WM_CLOSE), (201, win32con.BM_CLICK)] + assert result['release']['pcb_exited'] and not records + assert result['status'] == ('CLOSED' if launcher_exits else 'RETAINED') + assert result['release']['safe_to_continue'] is launcher_exits + assert .6 <= state['ticks'] <= 1.2 + assert sum(e['stage'] == 'startup_tip_dismissed' for e in events) == 1 + + +def test_normal_release_clears_owned_tip_and_waits_for_existing_close(tmp_path, monkeypatch): + import win32con + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + state['tip'] = True # Earlier cancelled startup has already posted WM_CLOSE. + result = sessions._request_close(row) + assert result['release_status'] == 'RELEASED' + assert messages == [(201, win32con.BM_CLICK)] + + +@pytest.mark.parametrize('obstacle', ['foreign_desktop', 'unknown', 'document', 'progress', + 'write', 'identity', 'scope', 'changed_prompt', 'disabled_tip', 'incomplete']) +def test_release_tip_never_overrides_unconfirmed_or_writing_state(tmp_path, monkeypatch, obstacle): + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + state['tip'] = True + if obstacle == 'foreign_desktop': windows[1]['desktop'] = 'Default' + if obstacle == 'unknown': windows.append(dict(windows[1], hwnd=300, title='Unknown action')) + if obstacle == 'document': windows[0]['documents'] = [300] + if obstacle == 'progress': windows[0]['children'] = [{'class': 'msctls_progress32'}] + if obstacle == 'write': row['runtime_phase'] = 'NATIVE_CALL' + if obstacle == 'identity': identity['created_handle'] = 'replacement' + if obstacle == 'scope': row['scope_confirmed'] = False + if obstacle == 'changed_prompt': + original = failed_session._startup_snapshot + from dataclasses import replace + monkeypatch.setattr(failed_session, '_startup_snapshot', + lambda h, p: replace(original(h, p), title='New question')) + if obstacle == 'disabled_tip': windows[1]['children'][0]['enabled'] = False + if obstacle == 'incomplete': + captured = sessions._WindowSnapshot({12}); captured[12] = windows + captured.incomplete[12] = 'unreadable' + monkeypatch.setattr(sessions, '_process_windows', lambda pids: captured) + assert sessions._request_close(row)['release_status'] in ('WAITING', 'IDENTITY_CHANGED') + assert not messages and records + + +def test_startup_late_tip_does_not_extend_original_close_budget(tmp_path, monkeypatch): + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + # Tip survives acknowledgement; no re-click and no second WM_CLOSE. + import win32gui, win32con + def record(hwnd, message, *_): messages.append((hwnd, message)) + monkeypatch.setattr(win32gui, 'PostMessage', record) + monkeypatch.setattr(sessions, '_post_window_message', lambda w,h,p,m: record(h,m)) + result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) + assert result['status'] == 'RETAINED' + assert messages == [(100, win32con.WM_CLOSE), (201, win32con.BM_CLICK)] + assert 1 <= state['ticks'] <= 1.2 + + +@pytest.mark.parametrize('obstacle', ['identity', 'desktop', 'document', 'progress', 'unknown']) +def test_late_tip_after_close_preserves_changed_or_busy_owner(tmp_path, monkeypatch, obstacle): + import win32con, win32gui + from cbb_refresh_verify import native_repair_ui + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + original = win32gui.PostMessage + if obstacle == 'desktop': + monkeypatch.setattr(native_repair_ui, '_current_desktop_name', + lambda: 'Default' if messages else job['desktop']) + def post(hwnd, message, *args): + original(hwnd, message, *args) + if message != win32con.WM_CLOSE: return + if obstacle == 'identity': identity['created_handle'] = 'replacement' + if obstacle == 'document': windows[0]['documents'] = [300] + if obstacle == 'progress': windows[0]['children'] = [{'class': 'msctls_progress32'}] + if obstacle == 'unknown': windows.append(dict(windows[1], hwnd=300, title='Unknown action')) + monkeypatch.setattr(win32gui, 'PostMessage', post) + result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) + assert result['status'] == 'RETAINED' and records + assert messages == [(100, win32con.WM_CLOSE)] + + +def test_transient_missing_wmi_pid_is_not_exit_of_held_startup_process(tmp_path, monkeypatch): + import win32gui + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: records.clear()) + result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) + assert result['status'] == 'RETAINED' + assert not result['release']['safe_to_continue'] + + +def test_release_rechecks_live_write_record_before_tip_action(tmp_path, monkeypatch): + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + state['tip'] = True + monkeypatch.setattr('cbb_refresh_verify.session_record.active_write_records', + lambda _: [{'phase': 'NATIVE_CALL'}]) + assert sessions._request_close(row)['release_status'] == 'WAITING' + assert not messages + + +def test_release_tip_ack_never_stacks_another_close_while_process_still_exits(tmp_path, monkeypatch): + import win32con + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + state['tip'] = True + def dismiss(window, hwnd, pid, message): + messages.append((hwnd, message)) + state['tip'] = False + monkeypatch.setattr(sessions, '_post_window_message', dismiss) + result = sessions._request_close(row) + assert result['release_status'] == 'WAITING' and records + assert messages == [(201, win32con.BM_CLICK)] + assert 3 <= state['ticks'] < 3.2 + + +@pytest.mark.parametrize('entry', ['startup', 'release']) +@pytest.mark.parametrize('obstacle', ['', 'foreign_owner', 'other_desktop', 'document', + 'progress', 'changed_owner', 'enabled_owner', 'wrong_title']) +def test_late_tip_direct_hidden_empty_owner_matches_native_capture(tmp_path, monkeypatch, entry, obstacle): + import win32con, win32gui, win32process + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + frame, tip = deepcopy(windows) + monkeypatch.setattr(sessions, '_process_windows', lambda pids: { + 12: [deepcopy(tip)] if state['tip'] else [dict(frame, enabled=True)]}) + monkeypatch.setattr(sessions, '_desktop_windows', lambda desktop: + [200] if obstacle == 'other_desktop' else [100, 200]) + monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: hwnd != 100 if state['tip'] else True) + monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd: + hwnd != 100 or not state['tip'] or obstacle == 'enabled_owner') + monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: + 'Loaded.pcb - Expedition PCB' if state['tip'] and obstacle == 'wrong_title' + else 'Expedition PCB') + monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: + ('msctls_progress32' if obstacle == 'progress' else 'MDIClient') if hwnd == 300 + else 'Afx:main') + monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg: + fn(300, arg) if state['tip'] and obstacle in ('document', 'progress') else None) + monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: + (1, 99 if hwnd == 100 and state['tip'] and obstacle == 'foreign_owner' else 12)) + reads = [] + def owner(hwnd, kind): + if hwnd == 300 and kind == win32con.GW_CHILD: return 301 + if hwnd == 200 and kind == win32con.GW_OWNER: + reads.append(hwnd) + return 999 if obstacle == 'changed_owner' and len(reads) > 1 else 100 + return 0 + monkeypatch.setattr(win32gui, 'GetWindow', owner) + if entry == 'release': + state['tip'] = True + result = sessions._request_close(row) + status = result['release_status'] + else: + result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) + status = result['status'] + expected = [(100, win32con.WM_CLOSE)] if entry == 'startup' else [] + if obstacle: + assert status in ('WAITING', 'RETAINED') and records + else: + expected.append((201, win32con.BM_CLICK)) + assert status in ('CLOSED', 'RELEASED') and not records + assert messages == expected + + +@pytest.mark.parametrize('entry', ['startup_deadline', 'release_stop']) +def test_tip_action_rechecks_budget_or_stop_after_slow_fresh_snapshot(tmp_path, monkeypatch, entry): + from threading import Event + import win32con + job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch) + stop = Event() + original = sessions._process_windows + reads = [] + def snapshot(pids): + value = original(pids) + if state['tip']: + reads.append(1) + if len(reads) >= 2: + state['ticks'] += 2 + stop.set() + return value + monkeypatch.setattr(sessions, '_process_windows', snapshot) + if entry == 'startup_deadline': + result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) + assert result['status'] == 'RETAINED' + assert messages == [(100, win32con.WM_CLOSE)] + else: + state['tip'] = True + assert sessions._request_close(row, stop=stop)['release_status'] in ('WAITING', 'CANCELLED') + assert not messages + assert records diff --git a/tests/test_library_reader.py b/tests/test_library_reader.py index fcaadb7..926f95f 100644 --- a/tests/test_library_reader.py +++ b/tests/test_library_reader.py @@ -35,7 +35,7 @@ def test_reader_accepts_com_collections_exposing_callable_count(): def test_reader_fast_scans_reusable_blocks_without_com(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') (tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir(parents=True) (tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir() from cbb_refresh_verify.library_reader import read_library_fast @@ -45,7 +45,7 @@ def test_reader_fast_scans_reusable_blocks_without_com(tmp_path): def test_reader_fast_applies_status_reader(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') (tmp_path / 'ReusableBlocksLP' / 'READY_CBB').mkdir(parents=True) from cbb_refresh_verify.library_reader import read_library_fast result = read_library_fast(lmc, status_reader=lambda name: 'READY' if name == 'READY_CBB' else 'PENDING') @@ -53,7 +53,7 @@ def test_reader_fast_applies_status_reader(tmp_path): def test_reader_fast_bulk_status_reader_is_called_once(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') (tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True) (tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir() calls = [] @@ -68,7 +68,7 @@ def test_reader_fast_bulk_status_reader_is_called_once(tmp_path): def test_reader_fast_preserves_unavailable_bridge_status(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') (tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True) from cbb_refresh_verify.library_reader import read_library_fast result = read_library_fast(lmc, status_reader=lambda path, names: {'A_CBB': 'UNAVAILABLE'}) @@ -77,7 +77,7 @@ def test_reader_fast_preserves_unavailable_bridge_status(tmp_path): def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') (tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True) from cbb_refresh_verify.library_reader import read_library_fast result = read_library_fast(lmc, status_reader=lambda path, names: (_ for _ in ()).throw(RuntimeError('bridge down'))) @@ -86,7 +86,7 @@ def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path): def test_filesystem_status_uses_complete_fresh_cert_artifacts(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') root = tmp_path / 'ReusableBlocksLP' ready = root / 'READY_CBB' / 'Work' pending = root / 'PENDING_CBB' / 'Work' @@ -325,7 +325,7 @@ def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path): def test_status_scan_without_native_observation_does_not_guess_status(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') root = lmc.parent / 'ReusableBlocksLP' ready = root / 'READY_CBB' / 'Work' (ready / 'PCB' / 'Layout').mkdir(parents=True) @@ -353,7 +353,7 @@ def test_status_scan_without_native_observation_does_not_guess_status(tmp_path): def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work' (work / 'PCB' / 'Layout').mkdir(parents=True) (work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8') @@ -375,7 +375,7 @@ def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path): def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch): """Legacy evidence scanning must not resolve a mapped drive back to UNC.""" lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work' (work / 'PCB' / 'Layout').mkdir(parents=True) (work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8') @@ -393,7 +393,7 @@ def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch) def test_missing_work_project_is_a_pending_calibration_anchor(tmp_path): lmc = tmp_path / 'center.lmc' - lmc.touch() + lmc.write_bytes(b'fixture metadata; native format is not checked') (tmp_path / 'ReusableBlocksLP' / 'IMPORTED_CBB').mkdir(parents=True) from cbb_refresh_verify.library_reader import filesystem_evidence_map evidence = filesystem_evidence_map(lmc, ('IMPORTED_CBB',))['IMPORTED_CBB'] diff --git a/tests/test_live_observer_queue.py b/tests/test_live_observer_queue.py new file mode 100644 index 0000000..eb0ef55 --- /dev/null +++ b/tests/test_live_observer_queue.py @@ -0,0 +1,90 @@ +from concurrent.futures import ThreadPoolExecutor +from threading import Event +from types import SimpleNamespace + +import pytest + +from cbb_refresh_verify import session_record as sessions +from cbb_refresh_verify.operation_queue import BatchTaskContext,NativeQueue + + +def observed(tmp_path,monkeypatch,*,status='ACTIVE',initializing=False,registered=True,alive=True,worker_alive=False): + library=tmp_path/'lib.lmc';key='record' + states={key:dict(status=status,observer_initializing=initializing,owned_worker_alive=worker_alive)} + monkeypatch.setattr(sessions,'_retained_libraries',{key:{sessions._library_key(library)}}) + monkeypatch.setattr(sessions,'_retained_results',states) + monkeypatch.setattr(sessions,'_observers',{key:(SimpleNamespace(is_alive=lambda:alive),None)} if registered else {}) + return library,states[key] + + +@pytest.mark.parametrize('initializing',[False,True]) +def test_same_library_waits_for_actual_observer_and_other_library_can_run(tmp_path,monkeypatch,initializing): + library,state=observed(tmp_path,monkeypatch,status='UNCONFIRMED' if initializing else 'ACTIVE',initializing=initializing) + queue=NativeQueue();waiting=Event();entered=Event();stop=Event() + # Queue predicates may not perform filesystem/process probes. + monkeypatch.setattr(sessions,'query_process_snapshot',lambda *a,**kw:pytest.fail('queue probed native clients'),raising=False) + context=BatchTaskContext(str(library),native_policy='external') + with ThreadPoolExecutor(2) as pool: + future=pool.submit(queue.run,lambda:entered.set() or 'resumed',context=context,stop=stop,waiting=waiting.set) + try: + assert waiting.wait(.5) and not entered.is_set() + other=pool.submit(queue.run,lambda:'unrelated',context=BatchTaskContext(str(tmp_path/'other.lmc'))) + assert other.result(1)=='unrelated' + state.update(status='RELEASED',observer_initializing=False) + assert future.result(2)=='resumed' + finally: + stop.set();queue.wake() + + +@pytest.mark.parametrize('case',['orphaned','dead_thread','unconfirmed','released']) +def test_stale_or_nonlive_cache_does_not_prevent_fresh_scoped_admission(tmp_path,monkeypatch,case): + library,state=observed(tmp_path,monkeypatch,status='RELEASED' if case=='released' else 'UNCONFIRMED', + registered=case!='orphaned',alive=case!='dead_thread') + assert not sessions.library_available(library) # Historical cache is deliberately stale. + assert NativeQueue().run(lambda:'fresh admission',context=BatchTaskContext(str(library)))=='fresh admission' + + +def test_live_owned_worker_still_blocks_when_its_journal_cannot_be_read(tmp_path,monkeypatch): + library,state=observed(tmp_path,monkeypatch,status='UNCONFIRMED',worker_alive=True) + queue=NativeQueue();waiting=Event();stop=Event();entered=Event() + with ThreadPoolExecutor(1) as pool: + future=pool.submit(queue.run,lambda:entered.set(),context=BatchTaskContext(str(library)), + stop=stop,waiting=waiting.set) + try: + assert waiting.wait(.5) and not entered.is_set() + state['owned_worker_alive']=False + future.result(2) + finally: + stop.set();queue.wake() + + +def test_actual_observer_initialization_closes_queue_race_then_unconfirmed_cache_releases_it(tmp_path,monkeypatch): + library=tmp_path/'lib.lmc';path=tmp_path/'session.json' + sessions.write_session_record(path,dict(operation_id='initializing',library=str(library))) + entered,finish,waiting,stop=Event(),Event(),Event(),Event() + def first_scan(*args,**kwargs): + entered.set();assert finish.wait(3) + return dict(status='UNCONFIRMED',operation_id='initializing',library=str(library), + detail='No live client; fresh admission must recheck resource proof') + monkeypatch.setattr(sessions,'_reconcile',first_scan) + queue=NativeQueue();thread=None + try: + sessions.handoff_session(path,evidence_root=tmp_path,observe_only=True,stop=stop) + assert entered.wait(2) + thread=sessions._observers[str(path.absolute()).casefold()][0] + assert not sessions.library_available(library,live_only=True) + with ThreadPoolExecutor(1) as pool: + future=pool.submit(queue.run,lambda:'fresh scoped admission',context=BatchTaskContext(str(library)), + waiting=waiting.set,stop=stop) + try: + assert waiting.wait(1) and not future.done() + finish.set() + assert future.result(2)=='fresh scoped admission' + finally: + stop.set();queue.wake() + thread.join(2) + assert not sessions.library_available(library) # Unproved historical state remains visible. + assert sessions.library_available(library,live_only=True) + finally: + finish.set();stop.set() + if thread:thread.join(2) diff --git a/tests/test_maintenance_ui.py b/tests/test_maintenance_ui.py index af262a6..a1d13cf 100644 --- a/tests/test_maintenance_ui.py +++ b/tests/test_maintenance_ui.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt import json from pathlib import Path @@ -16,9 +17,9 @@ def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypa window.search_edit.setText('Beta') window.verify_all(); qtbot.waitUntil(lambda: not window.busy) assert calls and calls[-1].maintenance is False - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.No) window.repair_icdb_all(); assert len(calls) == 1 - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) window.repair_icdb_all(); qtbot.waitUntil(lambda: not window._icdb_active()) assert len(calls) == 2 and calls[-1].maintenance is True @@ -56,7 +57,7 @@ def test_old_checkpoint_does_not_force_maintenance_or_disable_verify(qtbot, tmp_ window.select_visible_button.click() assert window.icdb_repair_button.isEnabled() assert window.batch_button.isEnabled() and window.selected_batch_button.isEnabled() - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) window.verify_selected(); qtbot.waitUntil(lambda: not window.busy) assert len(calls) == 1 and calls[0].maintenance is False assert window.selected_batch_button.isEnabled() @@ -102,7 +103,7 @@ def test_open_check_preserves_verify_state_without_starting_an_extra_catalog_rea blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary. return VerifyResult('CHECKED') monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None) - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data', status_refresher=lambda *a: pytest.fail('An open check must not start a second native status read')) qtbot.addWidget(window) diff --git a/tests/test_management.py b/tests/test_management.py index b7cddd5..c0a893a 100644 --- a/tests/test_management.py +++ b/tests/test_management.py @@ -215,7 +215,7 @@ def test_cancel_and_restart_never_replay(setup): from cbb_refresh_verify.management import run_management_batch, unfinished_operations request, adapter, _ = setup stop = Event(); stop.set() - assert run_management_batch([request], stop=stop, adapter=adapter) == [] + assert [r.status for r in run_management_batch([request], stop=stop, adapter=adapter)] == ['SKIPPED'] checkpoint = request.evidence_dir/'interrupted/checkpoint.json' checkpoint.parent.mkdir(parents=True) checkpoint.write_text('{"stage":"native_remove", "status":"RUNNING"}', encoding='utf-8') diff --git a/tests/test_management_deleted_receiver.py b/tests/test_management_deleted_receiver.py new file mode 100644 index 0000000..d6328ce --- /dev/null +++ b/tests/test_management_deleted_receiver.py @@ -0,0 +1,32 @@ +"""Queued worker completion must not touch a destroyed management dialog.""" +import pytest +from PySide6.QtWidgets import QMessageBox +from shiboken6 import delete, isValid + + +@pytest.mark.parametrize('failed', [False, True]) +def test_queued_management_completion_ignores_deleted_receiver(qtbot, tmp_path, monkeypatch, failed): + from cbb_refresh_verify.management import ManagementRequest + from cbb_refresh_verify.ui import timed_prompt + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + + def run(*args, **kwargs): + if failed: + raise ValueError('simulated native-boundary failure') + return [] + monkeypatch.setattr(timed_prompt, 'question', lambda *args, **kwargs: QMessageBox.Yes) + dialog = ManagementDialog([ManagementRequest('remove', tmp_path/'library.lmc', 'Block', + evidence_dir=tmp_path/'evidence')], runner=run) + completed = [] + dialog.completed.connect(completed.append) + try: + dialog.execute_button.click() + worker = dialog.worker # Retain the real sender while its queued signals are delivered. + assert dialog.pool.waitForDone(3000) + delete(dialog) + assert not isValid(dialog) + qtbot.wait(30) + assert not completed + finally: + if isValid(dialog): + delete(dialog) diff --git a/tests/test_management_native_transaction.py b/tests/test_management_native_transaction.py index f3dac02..2e80dbe 100644 --- a/tests/test_management_native_transaction.py +++ b/tests/test_management_native_transaction.py @@ -18,7 +18,7 @@ def transaction(tmp_path, monkeypatch): library = root/'native-add/fixture/mentor_lib.lmc' library.parent.mkdir(parents=True); library.write_bytes(b'fixture library') (root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8') - source = project(tmp_path/'source') + source = project(tmp_path/'source', 'Block') for path in (source, source.parent/'PCB/pcb.prj'): with path.open('a') as stream: stream.write(f'KEY CentralLibrary "{library}"\n') state = {'entries': [], 'calls': [], 'corrupt': False, 'fail_add': False} @@ -80,7 +80,7 @@ def test_owned_fixture_engine_add_conflict_update_remove_and_identity(transactio root, request, state = transaction original = request.source.read_bytes() assert execute(root, request).status == 'UPLOADED' - registered = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj' + registered = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj' assert project_library(registered) == request.library.resolve() calls = len(state['calls']) assert execute(root, request).status == 'UPLOAD_FAILED' diff --git a/tests/test_management_probe_guards.py b/tests/test_management_probe_guards.py index f5a6a35..340e914 100644 --- a/tests/test_management_probe_guards.py +++ b/tests/test_management_probe_guards.py @@ -147,7 +147,8 @@ def test_mapping_context_is_serialized_and_restored_before_catalog(tmp_path, mon order.append(('mapping', drive, remote))) monkeypatch.setattr(native, '_catalog_native', lambda job, root: (order.append(('catalog', job['library'])) or {'success': True, 'safe_to_continue': True})) - assert native.management_worker_main(tmp_path/'catalog/request.json') == 0 + assert captured[0]['worker_role'] == 'catalog_readonly' + assert native.catalog_worker_main(tmp_path/'catalog/request.json') == 0 assert order == [('mapping', 'S:', r'\\server\share'), ('catalog', str(library))] diff --git a/tests/test_management_retry_blockers.py b/tests/test_management_retry_blockers.py index d18f6d9..c78799b 100644 --- a/tests/test_management_retry_blockers.py +++ b/tests/test_management_retry_blockers.py @@ -542,7 +542,7 @@ def test_add_source_missing_central_library_fails_before_capture_without_retaini monkeypatch.setattr(adapter, 'catalog', lambda library, evidence: Catalog(library, 1, ())) monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity.capture_identity', lambda *_a, **_kw: pytest.fail('incomplete source reached native capture')) - result = execute(replace(request, operation='add', name='New', source=source, auto_verify=False), adapter) + result = execute(replace(request, operation='add', name=source.stem, source=source, auto_verify=False), adapter) assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue assert 'CentralLibrary' in result.detail assert not blocker_path(request.library).exists() diff --git a/tests/test_management_stop_after_current.py b/tests/test_management_stop_after_current.py new file mode 100644 index 0000000..b255841 --- /dev/null +++ b/tests/test_management_stop_after_current.py @@ -0,0 +1,168 @@ +"""Real Qt/management/admission boundaries, with only native work simulated.""" +from dataclasses import asdict, replace +import json +from pathlib import Path +from threading import Event + +import pytest +from PySide6.QtWidgets import QMessageBox + +from test_management import setup, project + + +@pytest.mark.parametrize('boundary,action,readback', [ + (boundary, action, 'success') for boundary in ('remove', 'add', 'after-add') for action in ('button', 'close') +] + [('after-add', 'button', 'failed'), ('after-add', 'button', 'unknown_release')]) +def test_soft_stop_finishes_current_transaction_and_skips_next(setup, qtbot, monkeypatch, boundary, action, readback): + from cbb_refresh_verify import backup_recovery + from cbb_refresh_verify.management import CatalogEntry + from cbb_refresh_verify.native_management import NativeManagementAdapter + from cbb_refresh_verify.operation_queue import NativeQueue + from cbb_refresh_verify.ui import timed_prompt + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + import win32con, win32event + + req, adapter, source = setup + other = project(source.parent.parent/'other-source', 'Other') + project(req.library.parent/'ReusableBlocksLP/Other/Work', 'Other') + adapter.records.append(CatalogEntry('Other', 'Logical-Physical')) + entered, release = Event(), Event() + admitted, results = [], [] + monkeypatch.setattr(backup_recovery, '_idle_check', lambda *a, **kw: None) + # Native work is simulated here; machine WMI latency is not the stop/readback boundary. + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: []) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **kw: QMessageBox.Yes) + + class Worker: + def __init__(self, command, desktop): + self.job = json.loads(Path(command[-1]).read_text()) + self.folder = Path(command[-1]).parent + self._start_event = win32event.CreateEvent(None, True, False, None) + self.closed = False + def bind_cancellation(self, path): pass + def bind_session(self, job): + self._start_binding = (job['session_record_path'], job['operation_id'], job['start_gate']) + def poll(self): + if win32event.WaitForSingleObject(self._start_event, 0) != win32con.WAIT_OBJECT_0: + return None + if self.folder.name == boundary: + entered.set() + assert release.wait(8) + assert not Path(self.job['cancel_signal']).exists() + if not (self.folder/'result.json').exists(): + admitted.append(self.folder.name) + failed = self.folder.name == 'after-add' and readback != 'success' + (self.folder/'result.json').write_text(json.dumps(dict(success=not failed, + safe_to_continue=not (failed and readback == 'unknown_release'), detail='readback failure' if failed else '', + library=str(req.library), flow=1, entries=[asdict(r) for r in adapter.records]))) + return 0 + def close(self): + if not self.closed: self._start_event.Close(); self.closed = True + + catalog = NativeManagementAdapter(mentor_home=req.library.parent, worker_factory=Worker) + adapter.bind_stop = catalog.bind_stop + adapter.catalog = catalog.catalog + for name in ('remove', 'add'): + original = getattr(adapter, name) + def call(*args, original=original, name=name): + result = original(*args) + if name == boundary: + entered.set() + assert release.wait(8) + return result + setattr(adapter, name, call) + requests = [replace(req, operation='update', source=source, auto_verify=False), + replace(req, operation='update', name='Other', source=other, auto_verify=False)] + dialog = ManagementDialog(requests, adapter=adapter) + dialog.native_queue = NativeQueue() + dialog.completed.connect(results.extend) + qtbot.addWidget(dialog); dialog.show(); dialog.execute_button.click() + try: + qtbot.waitUntil(entered.is_set, timeout=10000) + if action == 'button': dialog.stop_button.click() + else: dialog.close() + assert not dialog.context.stop.is_set(), 'Stop-after-current must not hard-cancel the admitted transaction' + finally: + release.set() + qtbot.waitUntil(lambda: not dialog.busy, timeout=10000) + assert [r.status for r in results] == ['UPLOADED' if readback == 'success' else 'RECOVERY_REQUIRED', 'SKIPPED'] + record = json.loads(results[0].evidence_path.read_text(encoding='utf-8')) + assert record['safe_to_continue'] is (readback != 'unknown_release') + assert admitted == ['before', 'after-remove', 'after-add'] + assert [r.name for r in adapter.records] == ['Other', 'Block'] + assert len(adapter.calls) == 2 + assert dialog.isVisible() + + +def test_soft_stop_before_first_item_never_opens_catalog(setup): + from cbb_refresh_verify.management import run_management_batch + from cbb_refresh_verify.operation_queue import BatchTaskContext + req, adapter, _ = setup + context = BatchTaskContext(str(req.library)) + context.stop_after_current.set() + adapter.catalog = lambda *args: pytest.fail('Stopped batch must not open native catalog') + results = context.run(lambda: run_management_batch([req], adapter=adapter, idle_check=lambda *a: None)) + assert [r.status for r in results] == ['SKIPPED'] + assert not context.stop.is_set() + + +def test_soft_stop_at_terminal_result_skips_next_item(setup): + from cbb_refresh_verify.management import run_management_batch + from cbb_refresh_verify.operation_queue import BatchTaskContext + req, adapter, _ = setup + context = BatchTaskContext(str(req.library)) + def progress(event): + if event['stage'] == 'REMOVED': context.stop_after_current.set() + results = context.run(lambda: run_management_batch([req, replace(req, name='Other')], + adapter=adapter, idle_check=lambda *a: None, progress=progress)) + assert [r.status for r in results] == ['REMOVED', 'SKIPPED'] + assert adapter.calls == ['remove'] and not context.stop.is_set() + + +def test_soft_stop_cancels_only_its_queued_batch(tmp_path): + from threading import Thread + from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, QueueCancelled + queue = NativeQueue(); waiting = Event(); outcomes = [] + stopped = BatchTaskContext(str(tmp_path/'stopped.lmc')) + independent = BatchTaskContext(str(tmp_path/'independent.lmc')) + def queued(): + try: queue.run(lambda: outcomes.append('unexpected'), context=stopped, + ready=lambda: False, waiting=waiting.set) + except QueueCancelled: outcomes.append('cancelled') + thread = Thread(target=queued); thread.start() + try: + assert waiting.wait(3) + stopped.stop_after_current.set(); queue.wake(); thread.join(3) + assert not thread.is_alive() + queue.run(lambda: outcomes.append('independent'), context=independent) + assert outcomes == ['cancelled', 'independent'] + assert not stopped.stop.is_set() and not independent.stop_after_current.is_set() + finally: + stopped.cancel(); queue.wake(); thread.join(3) + + +@pytest.mark.parametrize('shutdown', [False, True]) +def test_soft_stop_never_weakens_hard_worker_admission(tmp_path, shutdown): + from types import SimpleNamespace + from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff, commit_worker_start + import win32con, win32event + context = BatchTaskContext(str(tmp_path/'lib.lmc'), native_policy='external') + event = win32event.CreateEvent(None, True, False, None) + job = dict(session_record_path=str(tmp_path/'session.json'), operation_id='exact', + start_gate=str(tmp_path/'start.signal'), cancel_signal=str(tmp_path/'cancel.signal')) + worker = SimpleNamespace(_start_event=event, + _start_binding=(job['session_record_path'], job['operation_id'], job['start_gate'])) + checked = Event() + def action(): + context.stop_after_current.set() + if shutdown: context.shutdown() + else: context.cancel() + with pytest.raises(QueueCancelled): commit_worker_start(worker, job) + checked.set() + try: + try: context.run(action) + except TaskHandoff: pass + assert checked.wait(3) + assert win32event.WaitForSingleObject(event, 0) == win32con.WAIT_TIMEOUT + assert not Path(job['start_gate']).exists() and Path(job['cancel_signal']).exists() + finally: event.Close() diff --git a/tests/test_management_ui.py b/tests/test_management_ui.py index 6f85ac6..b33e5b6 100644 --- a/tests/test_management_ui.py +++ b/tests/test_management_ui.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt from dataclasses import replace from pathlib import Path from types import SimpleNamespace @@ -39,10 +40,10 @@ def test_management_dialog_preview_confirmation_and_result_status(qtbot, tmp_pat False, 'complete', 'REMOVED', True, 'removed', tmp_path/'checkpoint.json')] dialog = ManagementDialog(requests, runner=runner) qtbot.addWidget(dialog) - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (confirmations.append(a[2]) or QMessageBox.No)) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: (confirmations.append(a[2]) or QMessageBox.No)) dialog.execute_button.click() assert not calls and 'Block' in confirmations[0] and '手动备份' in confirmations[0] - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) dialog.execute_button.click() qtbot.waitUntil(lambda: not dialog.busy) assert len(calls) == 1 and '已移除' in dialog.status_label.text() diff --git a/tests/test_manifest_process_exit.py b/tests/test_manifest_process_exit.py new file mode 100644 index 0000000..0ffb3cc --- /dev/null +++ b/tests/test_manifest_process_exit.py @@ -0,0 +1,35 @@ +import os +from pathlib import Path +import subprocess +import sys +import time + +import pytest + + +@pytest.mark.parametrize('mode',['hash','copy','validate']) +def test_actual_app_exits_without_releasing_stalled_manifest_boundary(tmp_path,mode): + script=Path(__file__).parent/'support/manifest_process_exit.py' + env=dict(os.environ,QT_QPA_PLATFORM='offscreen') + child=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path),mode], + env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + exited=False + try: + deadline=time.monotonic()+8 + while not (tmp_path/'main-returning').exists() and child.poll() is None and time.monotonic()2:stop.set() + result=session_record.observe_retained_session(tmp_path/'session.json',evidence_root=tmp_path,stop=stop,progress=progress) + assert result['status']=='RELEASED' + assert messages==([(31,245)] if closed else [(31,245),(100,16)]) + assert (tmp_path/'result.json').read_bytes()==original + claim=json.loads((tmp_path/'session.json').read_text())['retained_startup_cleanup'] + assert claim['operation_id']==job['operation_id'] and claim['pcb_pid']==12 + + +@pytest.mark.parametrize('obstacle',['live_worker','other_write','save','foreign_identity','missing_cancel']) +def test_automatic_observer_does_not_consume_intent_or_act_without_positive_proof(tmp_path,monkeypatch,obstacle): + job,row,records,messages,state=fixture(tmp_path,monkeypatch,obstacle=obstacle) + residual_sessions.resume_cancelled_startup(tmp_path/'session.json') + assert not messages and records + assert 'retained_startup_cleanup' not in json.loads((tmp_path/'session.json').read_text()) + + +def test_timed_out_retained_phase_is_not_restarted_by_observer_or_explicit_release(tmp_path,monkeypatch): + job,row,records,messages,state=fixture(tmp_path,monkeypatch) + read=residual_sessions._legacy_diagnostic_windows + def progress(bound): + values=read(bound) + if state['declined']:values[0]['children'].append(dict(hwnd=123,**{'class':'msctls_progress32'},visible=True)) + return values + monkeypatch.setattr(residual_sessions,'_legacy_diagnostic_windows',progress) + residual_sessions.resume_cancelled_startup(tmp_path/'session.json') + first=state['ticks'] + assert 30<=first<30.2 and messages==[(31,245)] + residual_sessions.resume_cancelled_startup(tmp_path/'session.json') + assert residual_sessions._request_close(row)['release_status']=='WAITING' + assert state['ticks']==first and messages==[(31,245)] and records + + +def test_claim_is_persisted_before_any_native_action_and_failure_prevents_action(tmp_path,monkeypatch): + job,row,records,messages,state=fixture(tmp_path,monkeypatch) + def denied(*a,**kw):raise OSError('journal unavailable') + monkeypatch.setattr(session_record,'write_session_record',denied) + residual_sessions.resume_cancelled_startup(tmp_path/'session.json') + assert not messages and records + + +def test_retained_phase_never_repeats_worker_no_on_still_visible_prompt(tmp_path,monkeypatch): + job,row,records,messages,state=fixture(tmp_path,monkeypatch) + with (tmp_path/'events.jsonl').open('a') as stream: + stream.write(json.dumps(dict(stage='startup_prompt_no',pcb_pid=12,hwnd=31,control_id=7))+'\n') + residual_sessions.resume_cancelled_startup(tmp_path/'session.json') + assert not messages and records and 30<=state['ticks']<30.2 + + +def test_explicit_ordinary_release_promotes_cold_observer_before_native_action(tmp_path,monkeypatch): + job,row,records,messages,state=fixture(tmp_path,monkeypatch) + assert residual_sessions._request_close(row)['release_status']=='RELEASED' + assert state['observer_requests'] + path,actions,options=state['observer_requests'][0] + assert path==tmp_path/'session.json' and actions==[] and options['observe_only'] is False + + +@pytest.mark.parametrize('obstacle',['unknown','hidden_document','revoked']) +def test_late_observer_preserves_unknown_or_changed_loaded_state_before_claim(tmp_path,monkeypatch,obstacle): + job,row,records,messages,state=fixture(tmp_path,monkeypatch) + read=residual_sessions._legacy_diagnostic_windows + def windows(bound): + values=read(bound) + if obstacle=='unknown':values.append(dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown',children=[])) + if obstacle=='hidden_document':values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False)) + if obstacle=='revoked': + with (tmp_path/'events.jsonl').open('a') as stream:stream.write('{"stage":"startup_write_admitted"}\n') + return values + monkeypatch.setattr(residual_sessions,'_legacy_diagnostic_windows',windows) + residual_sessions.resume_cancelled_startup(tmp_path/'session.json') + assert not messages and records + assert 'retained_startup_cleanup' not in json.loads((tmp_path/'session.json').read_text()) + + +def test_duplicate_observer_explicit_release_and_process_restart_share_persisted_claim(tmp_path): + """Real process/mutex/file race; only native evidence and action boundary are stubs.""" + import os,subprocess,sys,time + path=tmp_path/'session.json' + session_record.write_session_record(path,dict(operation_id='one',block='B',library=str(tmp_path/'lib.lmc'))) + (tmp_path/'request.json').write_text(json.dumps(dict(diagnostic_only=False))) + script=tmp_path/'race.py' + script.write_text(''' +import json,sys,time +from pathlib import Path +from contextlib import nullcontext +import win32api +from cbb_refresh_verify import session_record as s,residual_sessions as r,diagnostic_open as d,failed_session as f +root=Path(sys.argv[1]);mode=sys.argv[2];tag=sys.argv[3];path=root/'session.json' +job=dict(diagnostic_only=False,desktop='CbbVerify_test',pcb=str(root/'B.pcb')) +row=dict(pid=1,name='ExpeditionPCB.exe',created_handle='bound',image='ExpeditionPCB.exe',owner_sid='owner',session_id=1) +proof=dict(job=job,record_path=str(path),operation_id='one',closed_frame=None) +r._process_handle=lambda *a,**k:nullcontext(win32api.GetCurrentProcess()) +r._handle_identity=lambda h:dict(created_handle='bound',image='ExpeditionPCB.exe') +r._force_ownership=lambda *a:dict(force_user_confirmed=True,owner_sid='owner',session_id=1) +r._process_windows=lambda *a:{} +r._cancelled_diagnostic_record=lambda *a:proof +r._legacy_diagnostic_windows=lambda *a:[dict(hwnd=100,pid=1)] +d._target_frame=lambda *a,**k:dict(hwnd=100,pid=1) +d._pending_prompt=lambda *a,**k:False +f.cancelled_prewrite_startup=lambda *a:{} +r.inspect_residual_sessions=lambda *a,**k:dict(sessions=[row]) +s._session=lambda *a:(s.read_session_record(path,evidence_root=root),{},[dict(role='native',pid=1,image='ExpeditionPCB.exe')]) +def close(*a,**k): + assert 'retained_startup_cleanup' in json.loads(path.read_text()) + (root/('action-'+tag)).write_text('one native phase') + until=time.monotonic()+8 + while not (root/'release').exists() and time.monotonic()=4:stop.set() + if state['ticks']<4 or obstacle=='progress': + value[0]['children'].append(dict(hwnd=123,**{'class':'msctls_progress32'},text='',visible=True)) + if obstacle=='unknown': + value.append(dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown action',children=[])) + return value + monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows) + result=sessions._request_close(row,stop=stop) + assert state['observer_requests'] and state['observer_requests'][0][1]==[] + assert state['observer_requests'][0][2].get('observe_only',False) is False + if not obstacle: + assert result['release_status']=='RELEASED' and not records + assert messages==[(31,245),(100,16)] and 4<=state['ticks']<5 + else: + assert result['release_status'] in ('WAITING','CANCELLED') and records + assert messages==[(31,245)] + assert state['ticks']<5 if obstacle=='stop' else 30<=state['ticks']<30.2 + + +def test_known_no_then_changing_ready_snapshot_revalidates_within_same_intent(tmp_path,monkeypatch): + job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch) + original=sessions._legacy_diagnostic_windows;reads=[] + def windows(bound): + value=original(bound) + if state['declined']: + reads.append(1) + if len(reads)==2:value[0]['children'].append(dict(hwnd=124,**{'class':'Afx:tool'},text='settling',parent=100)) + return value + monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows) + assert sessions._request_close(row)['release_status']=='RELEASED' + assert messages==[(31,245),(100,16)] and not records + + +def test_proved_native_cleanup_uses_its_budget_instead_of_metadata_inactivity(tmp_path,monkeypatch): + from threading import Event,Timer + from cbb_refresh_verify.operation_queue import BatchTaskContext + job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch) + ready,done=Event(),Event();original=sessions._legacy_diagnostic_windows + def windows(bound): + if state['declined']:assert ready.wait(1) + return original(bound) + monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows) + timer=Timer(.25,ready.set);timer.start() + context=BatchTaskContext(str(row['library'])) + def cleanup(): + try:return sessions._request_close(row) + finally:done.set() + try: + result=context.run(cleanup,timeout_seconds=.08) + assert result['release_status']=='RELEASED' and messages==[(31,245),(100,16)] + finally: + ready.set();timer.join(1);assert done.wait(2) + + +def test_registered_cleanup_preserves_frame_with_an_additional_mdi_document(tmp_path,monkeypatch): + job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch) + original=sessions._legacy_diagnostic_windows + def windows(bound): + value=original(bound) + value[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101)) + return value + monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows) + assert sessions._request_close(row)['release_status']=='WAITING' + assert records and not messages + + +@pytest.mark.parametrize('hidden_sibling',[None,False,True]) +def test_real_legacy_adapter_keeps_hidden_documents_before_any_native_action(tmp_path,monkeypatch,hidden_sibling): + import win32con,win32gui,win32process + snapshot,adapter=sessions._process_windows,sessions._legacy_diagnostic_windows + job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch) + monkeypatch.setattr(sessions,'_process_windows',snapshot) + monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',adapter) + monkeypatch.setattr(sessions,'_process_threads',lambda pids:{12:[1]}) + monkeypatch.setattr(sessions,'_thread_desktop_name',lambda tid:job['desktop']) + monkeypatch.setattr(sessions,'_desktop_windows',lambda desktop:[100,200] if not state['declined'] else [100]) + classes={100:'Afx:main',101:'MDIClient',102:'Afx:document',103:'Afx:document', + 200:'#32770',30:'Static',31:'Button',32:'Button'} + texts={100:'Expedition PCB - Reusable Block - [IP101GR]',101:'',102:'IP101GR',103:'Other', + 200:'Expedition PCB',30:'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?',31:'&No',32:'&Yes'} + parents={101:100,102:101,103:101,30:200,31:200,32:200} + monkeypatch.setattr(win32process,'GetWindowThreadProcessId',lambda h:(1,12)) + monkeypatch.setattr(win32gui,'GetClassName',lambda h:classes[h]) + monkeypatch.setattr(win32gui,'GetWindowText',lambda h:texts[h]) + monkeypatch.setattr(win32gui,'GetParent',lambda h:parents.get(h,0)) + monkeypatch.setattr(win32gui,'GetDlgCtrlID',lambda h:{30:6172,31:7,32:6}.get(h,0)) + monkeypatch.setattr(win32gui,'GetWindowRect',lambda h:(0,0,300,200)) + monkeypatch.setattr(win32gui,'IsWindowVisible',lambda h:not (h==103 and hidden_sibling)) + monkeypatch.setattr(win32gui,'IsWindowEnabled',lambda h:h!=100 or state['declined']) + monkeypatch.setattr(win32gui,'GetWindow',lambda h,k:102 if h==101 and k==win32con.GW_CHILD else 100 if h==200 and k==win32con.GW_OWNER else 0) + monkeypatch.setattr(win32gui,'EnumChildWindows',lambda h,fn,arg:[fn(c,arg) for c in ([101,102]+([103] if hidden_sibling is not None else []) if h==100 else [30,31,32])]) + result=sessions._request_close(row) + if hidden_sibling is None: + assert result['release_status']=='RELEASED',result + assert not records and messages==[(31,245),(100,16)] + else: + assert result['release_status']=='WAITING',result + assert records and not messages + + +@pytest.mark.parametrize('closed',[False,True]) +@pytest.mark.parametrize('delayed_tip',[False,True]) +def test_legacy_tip_continues_to_loaded_cleanup_only_without_prior_close(tmp_path,monkeypatch,closed,delayed_tip): + import win32con,win32gui + from copy import deepcopy + job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch,closed=closed) + state['tip']=True + tip_windows=[dict(hwnd=100,**{'class':'Afx:main'},title='Expedition PCB',enabled=False, + desktop=job['desktop'],children=[],documents=[]), + dict(hwnd=200,**{'class':'#32770'},title='Tip of the Day',enabled=True, + desktop=job['desktop'],documents=[],children=[dict(hwnd=201,**{'class':'Button'},id=1,text='OK',enabled=True)])] + def windows(pids): + state['ticks']+=.02 + if delayed_tip and state.get('tip_posted') and state['ticks']>=.3: + state['tip']=False + if closed:records.clear() + return {12:deepcopy(tip_windows) if state['tip'] else []} + monkeypatch.setattr(sessions,'_process_windows',windows) + monkeypatch.setattr(win32gui,'GetWindow',lambda h,k:100 if h==200 and k==win32con.GW_OWNER else 0) + original=win32gui.PostMessage + def post(hwnd,message,*args): + original(hwnd,message,*args) + if hwnd==201: + if delayed_tip:state.update(tip=True,tip_posted=True) + elif closed:records.clear() + monkeypatch.setattr(win32gui,'PostMessage',post) + if delayed_tip and closed: + original_wait=__import__('win32event').WaitForSingleObject + def wait(handle,ms): + value=original_wait(handle,ms) + if state.get('tip_posted') and state['ticks']>=.3:records.clear() + return value + monkeypatch.setattr(__import__('win32event'),'WaitForSingleObject',wait) + assert sessions._request_close(row)['release_status']=='RELEASED' + assert messages==([(201,245)] if closed else [(201,245),(31,245),(100,16)]) + assert not records and state['ticks']<30 diff --git a/tests/test_reimport_recovery.py b/tests/test_reimport_recovery.py index f292cd4..80ede7c 100644 --- a/tests/test_reimport_recovery.py +++ b/tests/test_reimport_recovery.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt from dataclasses import replace from pathlib import Path from threading import Event @@ -62,7 +63,7 @@ def test_declining_reimport_confirmation_does_not_check_release_or_write(qtbot, dialog.add_sources([source]) monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('unconfirmed release')) confirmations = [] - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **kw: confirmations.append(a[2]) or QMessageBox.No) dialog.execute_button.click() assert not dialog.busy and not dialog.executed @@ -179,7 +180,7 @@ def test_recovery_uses_background_release_then_existing_management(qtbot, tmp_pa return [ManagementResult('update', req.library, req.name, req.partition, req.source, True, 'complete', 'UPLOADED_VERIFIED', True)] monkeypatch.setattr(management, 'run_management_batch', run) - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **kw: QMessageBox.Yes) dialog = ManagementDialog([req], recovery_from={'Block': 'old.json'}) qtbot.addWidget(dialog) ticks = [] diff --git a/tests/test_release_progress.py b/tests/test_release_progress.py new file mode 100644 index 0000000..714bdbc --- /dev/null +++ b/tests/test_release_progress.py @@ -0,0 +1,111 @@ +"""Completed release work renews inactivity; a late proof cannot release a lease.""" +from contextlib import contextmanager +import json +from pathlib import Path +from threading import Event +import time +from types import SimpleNamespace + +import pytest + +from test_issue15_resource_release import library_file, cleanup +from cbb_refresh_verify import library_lock, operation_queue, owner_probe, file_probe, residual_sessions + + +@pytest.fixture +def release_work(tmp_path, monkeypatch): + library = library_file(tmp_path) + with library_lock.LibraryLock(library, safe_to_release=lambda: False) as lease: + pass + offset = [0] + clock = time.monotonic + monkeypatch.setattr(operation_queue, 'time', SimpleNamespace(monotonic=lambda: clock()+offset[0])) + steps = [] + state = {'delay': lambda name: None} + def complete(name): + steps.append(name) + state['delay'](name) + monkeypatch.setattr(owner_probe, 'query_owners', lambda *_: (complete('owners') or [])) + monkeypatch.setattr(residual_sessions, 'query_process_snapshot', lambda: (complete('snapshot') or [])) + monkeypatch.setattr(residual_sessions, '_process_windows', lambda *_: {}) + hold = file_probe.hold_release_files + @contextmanager + def files(*args, **kwargs): + with hold(*args, **kwargs) as proof: + complete('files') + yield proof + monkeypatch.setattr(file_probe, 'hold_release_files', files) + write_text, write_bytes = Path.write_text, Path.write_bytes + def text(path, content, *args, **kwargs): + result = write_text(path, content, *args, **kwargs) + if path.name == 'release.json' and json.loads(content)['status'] == 'RELEASE_PENDING': + complete('pending_record') + return result + def data(path, content, *args, **kwargs): + result = write_bytes(path, content, *args, **kwargs) + if path.name.startswith('blocker-before-'): complete('archive') + return result + monkeypatch.setattr(Path, 'write_text', text) + monkeypatch.setattr(Path, 'write_bytes', data) + yield library, lease, offset, state, steps + cleanup(lease) + + +@pytest.mark.parametrize('ui', [False, True]) +def test_aggregate_completed_release_checks_keep_final_proof_visible(release_work, tmp_path, monkeypatch, qtbot, ui): + library, lease, offset, state, steps = release_work + def advancing(name): + offset[0] += 6 if name in ('pending_record', 'archive') else 4 + time.sleep(.06) # The real context waiter observes each completed boundary. + state['delay'] = advancing + if ui: + from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog + monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: {'library':str(library),'sessions':[]}) + dialog = ResidualReleaseDialog(library, tmp_path/'evidence') + qtbot.addWidget(dialog); dialog.show() + qtbot.waitUntil(lambda: not dialog.busy) + proofs = []; dialog.released.connect(proofs.append) + dialog.confirm_button.click() + qtbot.waitUntil(lambda: not dialog.busy, timeout=5000) + assert len(proofs) == 1, dialog.message.text() + assert '已释放 0 个会话' in dialog.message.text() + proof = proofs[0] + else: + context = operation_queue.BatchTaskContext(str(library)) + try: + proof = context.run(lambda: library_lock.release_retained_library(library, tmp_path/'evidence'), + timeout_seconds=10) + finally: context.close(timeout_seconds=3) + assert proof['status'] == 'RELEASE_CONFIRMED' + assert proof['exclusive_files'] == [str(library)] + assert offset[0] >= 24 and steps.count('owners') == 2 + assert not library_lock.has_retained_library(library) + assert not library_lock.blocker_path(library).exists() + + +@pytest.mark.parametrize('step', ['owners', 'files', 'pending_record', 'archive']) +@pytest.mark.parametrize('cancel', [False, True]) +def test_stalled_or_cancelled_completed_step_cannot_commit_release(release_work, tmp_path, step, cancel): + library, lease, offset, state, steps = release_work + marker = library_lock.blocker_path(library); original = marker.read_bytes() + context = operation_queue.BatchTaskContext(str(library)); done = Event() + delayed = [] + def delayed_step(name): + if name == step and not delayed: + delayed.append(name) + if cancel: context.cancel() + offset[0] += 11 + time.sleep(.08) + state['delay'] = delayed_step + def release(): + try: return library_lock.release_retained_library(library, tmp_path/'evidence', stop=context.stop) + finally: done.set() + try: + with pytest.raises(operation_queue.QueueCancelled): context.run(release, timeout_seconds=10) + assert done.wait(3), 'Observe completion before closing the context; close must not mask late release' + assert delayed == [step] + assert marker.read_bytes() == original + assert library_lock.has_retained_library(library) + for path in (tmp_path/'evidence').rglob('release.json'): + assert json.loads(path.read_text())['status'] != 'RELEASE_CONFIRMED' + finally: context.close(timeout_seconds=3) diff --git a/tests/test_residual_inspection_metadata.py b/tests/test_residual_inspection_metadata.py new file mode 100644 index 0000000..9e3b8b8 --- /dev/null +++ b/tests/test_residual_inspection_metadata.py @@ -0,0 +1,30 @@ +from threading import Event + +import pytest + +from cbb_refresh_verify.operation_queue import BatchTaskContext,TaskHandoff,hold_native_handoff +from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog + + +def test_pure_residual_inspection_remains_available_during_native_finalizer(qtbot,tmp_path,monkeypatch): + library=tmp_path/'lib.lmc';library.touch() + context=BatchTaskContext(str(library),native_policy='external') + entered,finish=Event(),Event();reads=[] + def finalize(): + try:hold_native_handoff(None,tmp_path/'session.json') + except TaskHandoff:entered.set();assert finish.wait(5) + monkeypatch.setattr('cbb_refresh_verify.library_lock.inspect_residual_sessions',lambda path: + reads.append(path) or dict(library=str(library),sessions=[],previous_records=[])) + monkeypatch.setattr('cbb_refresh_verify.session_record.discover_sessions',lambda *a,**kw:[]) + monkeypatch.setattr('cbb_refresh_verify.session_record.retained_session_states',lambda *a:[]) + dialog=None + try: + with pytest.raises(TaskHandoff):context.run(finalize) + assert entered.is_set() + dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog) + qtbot.waitUntil(lambda:not dialog.busy,timeout=3000) + assert reads==[library] and dialog.plan is not None,dialog.message.text() + assert dialog.library==library and dialog.confirm_button.isEnabled() + finally: + finish.set();context.close(timeout_seconds=2) + if dialog is not None:dialog.close() diff --git a/tests/test_residual_release_dialog.py b/tests/test_residual_release_dialog.py index 9960e86..685630c 100644 --- a/tests/test_residual_release_dialog.py +++ b/tests/test_residual_release_dialog.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt from pathlib import Path from PySide6.QtCore import Qt @@ -93,10 +94,10 @@ def test_force_close_is_explicit_and_cancel_does_not_release(qtbot, tmp_path, mo dialog = ResidualReleaseDialog(tmp_path/'lib.lmc', tmp_path/'evidence') qtbot.addWidget(dialog) qtbot.waitUntil(lambda: not dialog.busy) - monkeypatch.setattr(QMessageBox, 'warning', lambda *a: QMessageBox.Cancel) + monkeypatch.setattr(timed_prompt, 'warning', lambda *a: QMessageBox.Cancel) dialog.force_button.click() assert not calls - monkeypatch.setattr(QMessageBox, 'warning', lambda *a: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'warning', lambda *a: QMessageBox.Yes) dialog.force_button.click() qtbot.waitUntil(lambda: not dialog.busy) assert calls == [True] @@ -115,7 +116,7 @@ def test_force_confirmation_excludes_shared_servers(qtbot, tmp_path, monkeypatch qtbot.addWidget(dialog) qtbot.waitUntil(lambda: not dialog.busy) messages = [] - monkeypatch.setattr(QMessageBox, 'warning', lambda parent, title, text, *args: + monkeypatch.setattr(timed_prompt, 'warning', lambda parent, title, text, *args: messages.append(text) or QMessageBox.Cancel) dialog.force_button.click() assert len(messages) == 1 @@ -153,6 +154,7 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo action = window._resume_batch_action assert action.isEnabled() calls = [] + original_remaining = (window._batch_requests[1],) monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw))) action.click() - assert calls == [(['Gamma'], {'maintenance': False})] + assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})] diff --git a/tests/test_review326_queue_guidance.py b/tests/test_review326_queue_guidance.py index 94c6616..2174c40 100644 --- a/tests/test_review326_queue_guidance.py +++ b/tests/test_review326_queue_guidance.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt from pathlib import Path from threading import Event @@ -27,6 +28,8 @@ def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot, window.show() library = window.mentor_lmc_path retain(monkeypatch, library) + from test_review381_queue_release import hold_native_queue + queue_release, queue_worker = hold_native_queue(window) finished = Event() window._start(lambda: VerifyResult('PASS'), lambda _: finished.set()) qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text()) @@ -36,6 +39,7 @@ def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot, window.queue_release_button.click() assert opened == [{'queued': True}] sessions._retained_libraries.clear() + queue_release.set(); queue_worker.join(2) window.native_queue.wake() qtbot.waitUntil(finished.is_set) qtbot.waitUntil(lambda: not window.busy) @@ -69,7 +73,9 @@ def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, t retain(monkeypatch, library) monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda _: dict(library=str(library), sessions=[])) + entered, allow_release = Event(), Event() def backend_release(*a, **kw): + entered.set(); assert allow_release.wait(5) sessions._retained_libraries.clear() return dict(status='RELEASE_CONFIRMED', sessions=[], proof=dict(status='RELEASE_CONFIRMED', library=str(library), evidence_path='controlled-proof.json')) @@ -81,15 +87,20 @@ def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, t def action(): assert cleaned.is_set(), 'new native operation began before old mapping release completed' finished.set() - window._start(action, lambda _: None) - qtbot.waitUntil(lambda: window._queue_wait_library is not None) + window._queue_wait_library = str(library) window.check_library_release(queued=True) qtbot.waitUntil(lambda: not window.release_dialog.busy) window.release_dialog.confirm_button.click() - qtbot.waitUntil(finished.is_set) - qtbot.waitUntil(lambda: not window.release_dialog.busy) - qtbot.waitUntil(lambda: not window.busy) - window.release_dialog.close() + qtbot.waitUntil(entered.is_set) + try: + window._start(action, lambda _: None) + allow_release.set() + qtbot.waitUntil(finished.is_set) + qtbot.waitUntil(lambda: not window.release_dialog.busy) + qtbot.waitUntil(lambda: not window.busy) + window.release_dialog.close() + finally: + allow_release.set() def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot, tmp_path, monkeypatch): @@ -109,7 +120,6 @@ def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot, qtbot.waitUntil(lambda: '已排队' in window.status_label.text()) assert window._queue_wait_library is None sessions._retained_libraries['controlled-session'] = {sessions._library_key(library)} - release.set(); first.join(3) qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text()) assert not window.queue_release_button.isHidden() finally: @@ -125,12 +135,14 @@ def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_pa from PySide6.QtWidgets import QMessageBox library = tmp_path/'lib.lmc' retain(monkeypatch, library) - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **kw: QMessageBox.Yes) dialog = ManagementDialog([ManagementRequest('remove', library, 'A')], runner=lambda *a, **kw: []) dialog.native_queue = NativeQueue() qtbot.addWidget(dialog); dialog.show() targets = [] dialog.release_requested.connect(targets.append) + from test_review381_queue_release import hold_native_queue + queue_release, queue_worker = hold_native_queue(dialog) dialog.execute_button.click() qtbot.waitUntil(lambda: 'BlockedCBB' in dialog.status_label.text()) assert dialog.release_wait_button.isVisible() @@ -138,6 +150,7 @@ def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_pa assert targets == [library] dialog.stop.set() qtbot.waitUntil(lambda: not dialog.busy) + queue_release.set(); queue_worker.join(2) def test_close_waits_for_independent_release_worker(qtbot, tmp_path, monkeypatch): diff --git a/tests/test_review381_queue_release.py b/tests/test_review381_queue_release.py index 673a1ac..c2714e7 100644 --- a/tests/test_review381_queue_release.py +++ b/tests/test_review381_queue_release.py @@ -1,5 +1,5 @@ """Stale and repeated user actions around native queue admission.""" -from threading import Event +from threading import Event, Thread from types import SimpleNamespace from pathlib import Path @@ -12,6 +12,18 @@ from test_review326_queue_guidance import retain from test_ui_filters import load_window + +def hold_native_queue(window): + """A live owner, rather than old retention metadata, keeps admission queued.""" + entered, release = Event(), Event() + def action(): + entered.set() + assert release.wait(10) + worker = Thread(target=lambda:window.native_queue.run(action)) + worker.start() + assert entered.wait(2) + return release, worker + def test_verify_admission_hides_release_entry_before_action_finishes(qtbot, tmp_path, monkeypatch): window = load_window(qtbot, tmp_path, monkeypatch) window.show() @@ -81,6 +93,7 @@ def test_old_waiting_event_is_rechecked_against_current_release_state(qtbot, tmp def test_other_library_icdb_start_preserves_the_foreground_wait(qtbot, tmp_path, monkeypatch): window = load_window(qtbot, tmp_path, monkeypatch) window.show() + queue_release, queue_worker = hold_native_queue(window) retain(monkeypatch, window.mentor_lmc_path) window._start(lambda: None, lambda _: None) try: @@ -90,6 +103,7 @@ def test_other_library_icdb_start_preserves_the_foreground_wait(qtbot, tmp_path, assert window.queue_release_button.isVisible() assert window._queue_wait_library == 'test.lmc' finally: + queue_release.set(); queue_worker.join(2) sessions._retained_libraries.clear() window.native_queue.wake() qtbot.waitUntil(lambda: not window.busy) @@ -130,6 +144,7 @@ def test_repeated_click_and_close_reuse_one_panel_without_unlocking_the_task(qtb from cbb_refresh_verify import library_lock window = load_window(qtbot, tmp_path, monkeypatch) window.show() + queue_release, queue_worker = hold_native_queue(window) retain(monkeypatch, window.mentor_lmc_path) monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda library: dict(library=str(library), sessions=[])) @@ -150,6 +165,7 @@ def test_repeated_click_and_close_reuse_one_panel_without_unlocking_the_task(qtb reopened.close() assert window.busy finally: + queue_release.set(); queue_worker.join(2) sessions._retained_libraries.clear() window.native_queue.wake() qtbot.waitUntil(lambda: not window.busy) @@ -159,6 +175,7 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt calls = [] window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda request: calls.append(request.block_name)) window.show() + queue_release, queue_worker = hold_native_queue(window) retain(monkeypatch, window.mentor_lmc_path) window.search_edit.setText('Beta') window.verify_all() @@ -167,15 +184,16 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt for _ in range(5): qtbot.mouseClick(window.batch_button, Qt.LeftButton) window.verify_all() - assert len(window.native_queue.pending) == 1 + assert len(window.native_queue.pending) == 2 qtbot.mouseClick(window.stop_button, Qt.LeftButton) qtbot.waitUntil(lambda: not window.busy) for _ in range(5): window.check_library_release(queued=True) assert calls == [] - assert not window.native_queue.pending + assert len(window.native_queue.pending) == 1 assert getattr(window, 'release_dialog', None) is None finally: + queue_release.set(); queue_worker.join(2) window.stop.set() sessions._retained_libraries.clear() window.native_queue.wake() @@ -186,11 +204,14 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt def test_foreground_completion_and_background_cancel_keep_only_live_waits(qtbot, tmp_path, monkeypatch, foreground_finishes_first): window = load_window(qtbot, tmp_path, monkeypatch, - verifier=lambda _: pytest.fail('A retained library must not start a native check')) + verifier=lambda _: pytest.fail('An intentionally paused check must not execute')) window.show() + queue_release, queue_worker = hold_native_queue(window) retain(monkeypatch, window.mentor_lmc_path) window._run(['Beta'], maintenance=True) + window.icdb_task.pause() qtbot.waitUntil(lambda: window.queue_release_button.isVisible()) + queue_release.set(); queue_worker.join(2) window.mentor_lmc_path = Path('other.lmc') window.lmc_edit.setText('other.lmc') started, finish = Event(), Event() @@ -215,6 +236,7 @@ def test_foreground_completion_and_background_cancel_keep_only_live_waits(qtbot, if not foreground_finishes_first: assert window.busy finally: + queue_release.set(); queue_worker.join(2) finish.set() window.icdb_task.cancel() sessions._retained_libraries.clear() diff --git a/tests/test_review391.py b/tests/test_review391.py index b47ef37..35b83bd 100644 --- a/tests/test_review391.py +++ b/tests/test_review391.py @@ -49,7 +49,8 @@ def test_batch_result_is_visible_before_queued_refresh_and_survives_user_actions other_started.set();other_release.wait(5) thread=Thread(target=lambda:window.native_queue.run(other));thread.start() try: - qtbot.waitUntil(lambda:len(window.native_queue.pending)==1) + # The queue retains both the active ticket and its waiting successor. + qtbot.waitUntil(lambda:len(window.native_queue.pending)==2) release.set();qtbot.waitUntil(other_started.is_set) qtbot.waitUntil(lambda:getattr(window,'summary',None) is not None,timeout=1500) assert window.summary.isVisible() and window.busy diff --git a/tests/test_review414_write_admission.py b/tests/test_review414_write_admission.py index 190ba4f..a6a3947 100644 --- a/tests/test_review414_write_admission.py +++ b/tests/test_review414_write_admission.py @@ -94,7 +94,7 @@ def test_user_can_close_unknown_client_before_confirming(tmp_path,monkeypatch): _idle_check(*paths,confirmation=WriteAdmission(prompt=prompt),evidence=tmp_path/'evidence',block='Block') -@pytest.mark.parametrize('first,expected',[('skip',['SKIPPED','UPLOADED']),('cancel',['CANCELLED'])]) +@pytest.mark.parametrize('first,expected',[('skip',['SKIPPED','UPLOADED']),('cancel',['CANCELLED','SKIPPED'])]) def test_batch_continues_only_after_skip_or_confirmed_release(tmp_path,monkeypatch,first,expected): from dataclasses import replace from test_management import FileAdapter,project @@ -117,7 +117,7 @@ def test_write_confirmation_dialog_defaults_cancel_and_cannot_overwrite_choice(q from cbb_refresh_verify.ui.write_owner_dialog import WriteOwnerDialog choice=WriteOwnerChoice('Block','target.lmc',[dict(pid=12,name='viewdraw.exe',image='viewdraw.exe')]) dialog=WriteOwnerDialog(choice);qtbot.addWidget(dialog) - assert dialog.defaultButton() is dialog.cancel_button + assert dialog.defaultButton() is dialog.skip_button dialog.skip_button.click();dialog.reject() assert choice.decision=='skip' @@ -149,7 +149,7 @@ def test_cancel_batch_also_stops_default_api_without_a_caller_event(tmp_path,mon request=ManagementRequest('add',library,'One',source=source,auto_verify=False,evidence_dir=tmp_path/'evidence') adapter=FileAdapter() results=run_management_batch([request,replace(request,name='Two')],adapter=adapter,version_prompt=prompt) - assert [r.status for r in results]==['CANCELLED'] + assert [r.status for r in results]==['CANCELLED','SKIPPED'] assert len(choices)==1 and not adapter.calls diff --git a/tests/test_review430.py b/tests/test_review430.py index 60ec62a..c9d382a 100644 --- a/tests/test_review430.py +++ b/tests/test_review430.py @@ -109,7 +109,12 @@ def test_real_file_error_preserves_failed_item_and_allows_an_independent_item(tr return assets(source, expected_library) monkeypatch.setattr(identity, 'asset_identity', read_assets) adapter = _OwnedFixtureManagementAdapter(root, 'owned') - results = run_management_batch([request, replace(request, name='Other')], adapter=adapter, + from test_management import project + other_source = project(request.source.parent.parent/'other-source', name='Other') + for path in (other_source, other_source.parent/'PCB/pcb.prj'): + with path.open('a') as stream: + stream.write(f'KEY CentralLibrary "{request.library}"\n') + results = run_management_batch([request, replace(request, name='Other', source=other_source)], adapter=adapter, idle_check=lambda *_: None) assert [r.status for r in results] == ['RECOVERY_REQUIRED', 'UPLOADED'] assert all(r.safe_to_continue for r in results) diff --git a/tests/test_review_release_followup.py b/tests/test_review_release_followup.py index 4298ae2..1422980 100644 --- a/tests/test_review_release_followup.py +++ b/tests/test_review_release_followup.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt import json from contextlib import nullcontext from pathlib import Path @@ -180,9 +181,9 @@ def test_ui_native_cancel_is_explicit_and_details_are_readable(qtbot, tmp_path, assert 'Backing up project' in dialog.native_details.detailedText() assert 'CbbRepair_A' in dialog.native_details.detailedText() dialog.native_details.close() - monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.No) + monkeypatch.setattr(timed_prompt,'question',lambda *a:QMessageBox.No) dialog.cancel_native_button.click();assert calls==[] - monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.Yes) + monkeypatch.setattr(timed_prompt,'question',lambda *a:QMessageBox.Yes) dialog.cancel_native_button.click();qtbot.waitUntil(lambda:not dialog.busy) assert calls==[process] @@ -245,7 +246,7 @@ def test_native_cancel_completion_propagates_actual_release_to_parent(qtbot,tmp_ proof={'status':'RELEASE_CONFIRMED','library':str(library)} monkeypatch.setattr(residual_sessions,'request_native_cancel',lambda *a,**kw: {'status':'RELEASE_CONFIRMED','sessions':[{**process,'release_status':'RELEASED'}],'proof':proof}) - monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.Yes) + monkeypatch.setattr(timed_prompt,'question',lambda *a:QMessageBox.Yes) dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog) released=[];dialog.released.connect(released.append) qtbot.waitUntil(lambda:not dialog.busy) diff --git a/tests/test_ui.py b/tests/test_ui.py index 305c47c..18e4333 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -1,3 +1,4 @@ +from cbb_refresh_verify.ui import timed_prompt import os import pytest from pathlib import Path @@ -26,7 +27,7 @@ def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks' @pytest.fixture(autouse=True) def isolate_authoritative_native_refresh(monkeypatch): from PySide6.QtWidgets import QMessageBox - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) # Production refresh crosses the native Mentor boundary; these are UI tests. monkeypatch.setattr('cbb_refresh_verify.ui.main_window.authoritative_status_map', lambda names, *_: {name: 'READY' for name in names}) @@ -42,10 +43,10 @@ def test_global_icdb_action_confirms_and_excludes_ready_rows(qtbot, tmp_path, mo qtbot.addWidget(window) window.lmc_edit.setText('lib.lmc'); window.load_library() qtbot.waitUntil(lambda: not window.busy) - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.No) window.icdb_repair_button.click() assert calls == [] - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) window.icdb_repair_button.click() qtbot.waitUntil(lambda: not window._icdb_active()) assert calls == ['PENDING'] @@ -70,7 +71,7 @@ def test_global_icdb_failure_preserves_untargeted_ready_and_stops_queue(qtbot, t qtbot.addWidget(window) window.lmc_edit.setText('lib.lmc'); window.load_library() qtbot.waitUntil(lambda: not window.busy) - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) window.icdb_repair_button.click() qtbot.waitUntil(lambda: not window._icdb_active()) assert calls == ['B'] @@ -84,7 +85,7 @@ def test_global_icdb_progress_and_check_summary(qtbot, tmp_path, monkeypatch): def confirm(*args, **kwargs): confirmations.append(args[2]) return QMessageBox.Yes - monkeypatch.setattr(QMessageBox, 'question', confirm) + monkeypatch.setattr(timed_prompt, 'question', confirm) window = MainWindow(reader=fake_reader, data_root=tmp_path, verifier=lambda _: VerifyResult('FAIL', safe_to_continue=False, recovery_attempts=( {'status': 'RESTORED_REVIEW_REQUIRED', 'detail': 'restored old backup'},))) @@ -125,7 +126,8 @@ def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot): assert hasattr(window, 'libspec_edit') and hasattr(window, 'dms_edit') window.lmc_edit.setText('different.lmc') assert not window.batch_button.isEnabled() - assert window.cbb_table.rowCount() == 0 + assert window.cbb_table.rowCount() == 1 + assert '失效' in window.library_notice.text() def test_ui_removes_current_cbb_controls_and_hides_advanced_settings(qtbot): diff --git a/tests/test_ui_filters.py b/tests/test_ui_filters.py index b8d8ff2..ea36589 100644 --- a/tests/test_ui_filters.py +++ b/tests/test_ui_filters.py @@ -1,4 +1,5 @@ """Local catalog scope and authoritative status refresh regression tests.""" +from cbb_refresh_verify.ui import timed_prompt import json import time from threading import Event @@ -24,7 +25,7 @@ MIXED = ( def load_window(qtbot, tmp_path, monkeypatch, records=MIXED, **kwargs): - monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes) import cbb_refresh_verify.ui.main_window as ui monkeypatch.setattr(ui, 'preflight_skip_reason', lambda _, name: 'missing project' if name == 'Missing' else None) @@ -102,7 +103,7 @@ def test_maintenance_confirmation_progress_and_report_use_visible_checked_subset status_refresher=refresh) window.search_edit.setText('analog') window.cbb_table.item(3, 0).setCheckState(Qt.Checked) - monkeypatch.setattr(QMessageBox, 'question', lambda *args, **_: ( + monkeypatch.setattr(timed_prompt, 'question', lambda *args, **_: ( confirmations.append(args[2]) or QMessageBox.Yes)) window.repair_icdb_all() qtbot.waitUntil(lambda: not window._icdb_active()) @@ -126,7 +127,7 @@ def test_maintenance_defaults_to_visible_eligible_and_ready_only_checks_do_not_f window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')), status_refresher=lambda targets, _: {name: 'PENDING' for name in targets}) - monkeypatch.setattr(QMessageBox, 'question', lambda *_, **__: QMessageBox.Yes) + monkeypatch.setattr(timed_prompt, 'question', lambda *_, **__: QMessageBox.Yes) window.cbb_table.item(0, 0).setCheckState(Qt.Checked) window.repair_icdb_all() assert not window.busy and calls == [] diff --git a/tests/test_unattended_prompts.py b/tests/test_unattended_prompts.py new file mode 100644 index 0000000..beb609a --- /dev/null +++ b/tests/test_unattended_prompts.py @@ -0,0 +1,168 @@ +import pytest +from PySide6.QtCore import QTimer +from PySide6.QtWidgets import QMessageBox + + +def restore_choice(*, manual=True): + from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice + return RestoreChoice('Block', 'library.lmc', [ + dict(kind='last_user_saved', date='2026/9/24 23:06', enabled=manual), + dict(kind='autosave', date='2026/9/24 23:06', enabled=True)]) + + +@pytest.mark.parametrize('kind,decision', [('open', 'skip'), ('owner', 'skip'), + ('version', 'last_user_saved')]) +def test_native_choice_finishes_in_three_seconds_without_an_operator(qtbot, kind, decision): + from cbb_refresh_verify.pcb_open_consent import OpenChoice + from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog + from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog + from cbb_refresh_verify.ui.write_owner_dialog import WriteOwnerDialog + from cbb_refresh_verify.write_admission import WriteOwnerChoice + if kind == 'open': + choice = OpenChoice('Block', 'library.lmc') + dialog = PcbOpenDialog(choice) + elif kind == 'owner': + choice = WriteOwnerChoice('Block', 'library.lmc', [ + dict(pid=12, name='viewdraw.exe', image='viewdraw.exe')]) + dialog = WriteOwnerDialog(choice) + else: + choice = restore_choice() + dialog = PcbRestoreDialog(choice) + qtbot.addWidget(dialog) + dialog.show() + qtbot.wait(3200) + assert choice.decision == decision + assert choice.decision_origin == 'timeout_default' + assert not dialog.isVisible() + + +def test_manual_selection_cancels_the_pending_default(qtbot, monkeypatch): + from cbb_refresh_verify.ui import timed_prompt + from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog + monkeypatch.setattr(timed_prompt, 'DEFAULT_TIMEOUT_MS', 100) + choice = restore_choice() + dialog = PcbRestoreDialog(choice) + qtbot.addWidget(dialog) + dialog.show() + dialog.auto_button.click() + qtbot.wait(200) + assert choice.decision == 'autosave' + assert choice.decision_origin == 'user' + + +def test_unavailable_preferred_version_never_clicks_disabled_or_other_version(qtbot, monkeypatch): + from cbb_refresh_verify.ui import timed_prompt + from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog + monkeypatch.setattr(timed_prompt, 'DEFAULT_TIMEOUT_MS', 100) + choice = restore_choice(manual=False) + dialog = PcbRestoreDialog(choice) + qtbot.addWidget(dialog) + dialog.show() + qtbot.waitUntil(lambda: choice.decision is not None) + assert choice.decision == 'cancel' + assert choice.decision_origin == 'timeout_default' + + +@pytest.mark.parametrize('default', [QMessageBox.Yes, QMessageBox.Cancel]) +def test_question_runs_its_explicit_default_without_mouse_input(qtbot, monkeypatch, default): + from cbb_refresh_verify.ui import timed_prompt + monkeypatch.setattr(timed_prompt, 'DEFAULT_TIMEOUT_MS', 100) + result = timed_prompt.question(None, 'Timed fixture', 'Choose', + QMessageBox.Yes | QMessageBox.Cancel, default) + assert result == default + + +def test_manual_question_answer_wins_before_timeout(qtbot, monkeypatch): + from cbb_refresh_verify.ui import timed_prompt + monkeypatch.setattr(timed_prompt, 'DEFAULT_TIMEOUT_MS', 200) + def answer(): + from PySide6.QtWidgets import QApplication + for box in QApplication.topLevelWidgets(): + if isinstance(box, QMessageBox) and box.windowTitle() == 'Manual fixture': + box.button(QMessageBox.No).click() + QTimer.singleShot(50, answer) + assert timed_prompt.question(None, 'Manual fixture', 'Choose', + QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.No + qtbot.wait(250) + + +def test_hidden_or_closed_notifications_never_execute_later(qtbot, monkeypatch): + from cbb_refresh_verify.ui import timed_prompt + monkeypatch.setattr(timed_prompt, 'DEFAULT_TIMEOUT_MS', 100) + box = QMessageBox() + qtbot.addWidget(box) + box.setStandardButtons(QMessageBox.Close) + clicks = [] + box.buttonClicked.connect(lambda _: clicks.append(True)) + timed_prompt.arm_default(box, box.button(QMessageBox.Close)) + box.show() + box.hide() + qtbot.wait(200) + assert not clicks + box.show() + qtbot.waitUntil(lambda: bool(clicks)) + qtbot.wait(200) + assert clicks == [True] + + +def test_timeout_skip_does_not_grant_unknown_clients_or_stop_the_batch(tmp_path, monkeypatch): + from threading import Event + from cbb_refresh_verify.write_admission import WriteAdmission, WriteAdmissionDeclined + monkeypatch.setattr('cbb_refresh_verify.write_admission.process_identity', lambda pid: dict( + pid=pid, created_handle='one', image='viewdraw.exe', owner_sid='user', session_id=1)) + owners = [dict(pid=12, name='viewdraw.exe', executable='viewdraw.exe')] + stop = Event() + admission = WriteAdmission(stop=stop, prompt=lambda c: c.choose('skip', origin='timeout_default')) + with pytest.raises(WriteAdmissionDeclined, match='超时默认'): + admission.confirm(tmp_path/'library.lmc', owners, evidence=tmp_path/'evidence', block='Block') + assert not stop.is_set() + assert not admission.confirmed(tmp_path/'library.lmc', owners) + + +def test_recorded_pcb_open_choice_distinguishes_timeout_from_user(tmp_path, monkeypatch): + from contextlib import nullcontext + from types import SimpleNamespace + import json + from test_post_repair_consent import snapshot + from cbb_refresh_verify import pcb_open_consent as consent + monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'owned'}) + monkeypatch.setattr(consent, 'resource_guard', lambda *_: nullcontext()) + controller = consent.OpenController(dict(root=str(tmp_path), block_name='Block', + lmc_file='library.lmc', project='Block.prj', pcb='Block.pcb', desktop='CbbVerify_test')) + shown = [] + options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, + perform=lambda *_: SimpleNamespace(error_code='', accepted_controls=(7,), detail='', channel='win32_button_click')) + controller.handle(snapshot(), (snapshot(),), **options) + shown[0].choose('skip', origin='timeout_default') + result = controller.handle(snapshot(), (snapshot(),), **options) + assert result.error_code == 'PCB_OPEN_SKIPPED' + record = json.loads((tmp_path/'pcb-open-user-choice.json').read_text('utf-8')) + assert record['decision_origin'] == 'timeout_default' + + +@pytest.mark.parametrize('decision', ['last_user_saved', 'cancel']) +def test_native_version_action_retains_automatic_choice_origin(tmp_path, monkeypatch, decision): + import json + from types import SimpleNamespace + from test_pcb_version_choice import captured + from cbb_refresh_verify.pcb_restore_prompt import RestoreController + monkeypatch.setattr('cbb_refresh_verify.pcb_open_consent.validate_owner', lambda *_: {'target': 'owned'}) + controller = RestoreController(dict(root=str(tmp_path), block_name='Block', lmc_file='library.lmc', + project='Block.prj', pcb='Block.pcb', desktop='CbbVerify_test'), user_open=True) + value = captured() + shown, actions = [], [] + def perform(snapshot, action, phase): + actions.append(action) + return SimpleNamespace(error_code='', accepted_controls=(6213,), detail='', channel='win32_button_click') + options = dict(target_pid=value.pid, launcher_pid=10, worker_pid=5, companion_pids=(), + show=shown.append, perform=perform) + controller.handle(value, (value,), **options) + shown[0].choose(decision, origin='timeout_default') + result = controller.handle(value, (value,), **options) + record = json.loads((tmp_path/'pcb-version-user-choice.json').read_text('utf-8')) + assert record['choice'] == decision and record['decision_origin'] == 'timeout_default' + if decision == 'cancel': + assert not actions and result.error_code == 'PCB_VERSION_CHOICE_REQUIRED' + else: + assert actions[0]['decision_origin'] == 'timeout_default' + assert actions[0]['target']['control_id'] == 6213 diff --git a/tests/test_verify_worker_stability.py b/tests/test_verify_worker_stability.py index 5de7dde..91a74ed 100644 --- a/tests/test_verify_worker_stability.py +++ b/tests/test_verify_worker_stability.py @@ -11,7 +11,7 @@ def exercise_worker(tmp_path, monkeypatch, *, integration_error=None): work = tmp_path/'ReusableBlocksLP/CBB/Work' pcb = work/'PCB/CBB.pcb' pcb.parent.mkdir(parents=True) - pcb.touch() + pcb.write_text('KEY ProjectFile "../CBB.prj"\n') project = work/'CBB.prj' project.touch() evidence = tmp_path/'evidence' diff --git a/tests/test_worker_entry_failure.py b/tests/test_worker_entry_failure.py new file mode 100644 index 0000000..351fba9 --- /dev/null +++ b/tests/test_worker_entry_failure.py @@ -0,0 +1,91 @@ +"""Hidden native workers must publish errors instead of a frozen bootloader popup.""" +import json +from contextlib import contextmanager + +import pytest + + +@pytest.fixture(autouse=True) +def fresh_worker_registry(monkeypatch): + from cbb_refresh_verify import desktop_worker + # Each hidden entry runs in a new process, without earlier tests' fake clients. + monkeypatch.setattr(desktop_worker, '_automation_clients', []) + + +@pytest.mark.parametrize('mode,result_file', [ + ('verify', 'outcome.json'), ('management', 'result.json'), + ('management_catalog', 'result.json'), ('repair', 'repair-result.json')]) +@pytest.mark.parametrize('reason', ['cancelled', 'busy', 'invalid_session', 'mismatched_session', 'invalid_json']) +def test_hidden_worker_admission_refusal_exits_with_unconfirmed_receipt(tmp_path, monkeypatch, mode, result_file, reason): + from cbb_refresh_verify import application, desktop_worker + request = tmp_path/'request.json' + job = {'root': str(tmp_path), 'block_name': 'Fixture', 'operation': 'catalog'} + if mode == 'management_catalog': + mode = 'management' + job['worker_role'] = 'catalog_readonly' + if reason == 'cancelled': + cancel = tmp_path/'cancel.signal'; cancel.touch() + job['cancel_signal'] = str(cancel) + elif reason == 'invalid_session': + job['session_record_path'] = str(tmp_path/'missing-session.json') + elif reason == 'mismatched_session': + import os + from types import SimpleNamespace + from cbb_refresh_verify.session_record import register_worker_session + job.update(session_record_path=str(tmp_path/'session.json'), operation_id='admission', + library=str(tmp_path/'library.lmc'), block='Fixture') + register_worker_session(SimpleNamespace(pid=os.getpid()), job) + job['library'] = str(tmp_path/'different-library.lmc') + elif reason == 'busy': + @contextmanager + def occupied(**kwargs): + raise RuntimeError('NATIVE_WRITER_ACTIVE: independent writer') + yield + monkeypatch.setattr(desktop_worker, 'worker_native_channel', occupied) + request.write_text('{' if reason == 'invalid_json' else json.dumps(job), encoding='utf-8') + assert application.main(['--'+mode+'-worker', str(request)]) != 0 + result = json.loads(request.with_name(result_file).read_text('utf-8')) + assert result['safe_to_continue'] is False + failure = json.loads(request.with_name('worker-failure.json').read_text('utf-8')) + assert failure['stage'] == 'admission' and failure['worker_entered'] is False + assert failure['native_started'] is False + assert 'Traceback' in request.with_name('worker.log').read_text('utf-8') + assert not (tmp_path/'save.log').exists() + + +def test_entered_worker_failure_preserves_existing_save_facts_and_stays_unconfirmed(tmp_path, monkeypatch): + from cbb_refresh_verify import application, mentor_adapter + request = tmp_path/'request.json'; request.write_text(json.dumps({'root': str(tmp_path)})) + facts = {'save_state': 'COMMITTED', 'close_state': 'UNKNOWN', 'helper_state': 'RUNNING'} + state = tmp_path/'worker-state.json' + def entered(path): + state.write_text(json.dumps({'write_outcome': facts})) + (tmp_path/'outcome.json').write_text(json.dumps({'status': 'FAIL', 'safe_to_continue': False, + 'write_outcome': facts, 'stderr': 'save returned; close still pending'})) + raise RuntimeError('post-entry transport failed') + monkeypatch.setattr(mentor_adapter, 'worker_main', entered) + assert application.main(['--verify-worker', str(request)]) != 0 + result = json.loads((tmp_path/'outcome.json').read_text()) + assert result['write_outcome'] == facts and result['safe_to_continue'] is False + assert json.loads(state.read_text()) == {'write_outcome': facts} + failure = json.loads((tmp_path/'worker-failure.json').read_text()) + assert failure['stage'] == 'worker' and failure['worker_entered'] is True + assert failure['native_started'] is None + + +def test_native_backup_bootstrap_error_also_exits_without_claiming_release(tmp_path): + from cbb_refresh_verify.application import main + request = tmp_path/'request.json'; request.write_text('{') + assert main(['--native-backup-worker', str(request)]) != 0 + assert json.loads((tmp_path/'result.json').read_text())['safe_to_continue'] is False + + +def test_receipt_io_failure_still_cannot_escape_to_frozen_bootloader(tmp_path, monkeypatch): + from pathlib import Path + from cbb_refresh_verify.application import main + request = tmp_path/'request.json'; request.write_text('{') + def denied(*args, **kwargs): + raise PermissionError('receipt disk unavailable') + monkeypatch.setattr(Path, 'write_text', denied) + assert main(['--verify-worker', str(request)]) == 1 + assert 'JSONDecodeError' in (tmp_path/'worker.log').read_text() diff --git a/tests/test_worktree_imports.py b/tests/test_worktree_imports.py new file mode 100644 index 0000000..115fded --- /dev/null +++ b/tests/test_worktree_imports.py @@ -0,0 +1,14 @@ +"""A spawned Python must test the same worktree as its pytest parent.""" +import json +from pathlib import Path +import subprocess +import sys + + +def test_spawned_python_imports_active_worktree_from_another_directory(tmp_path): + import cbb_refresh_verify + child = subprocess.run( + [sys.executable, '-c', 'import json,cbb_refresh_verify; ' + 'print(json.dumps(cbb_refresh_verify.__file__))'], + cwd=tmp_path, capture_output=True, text=True, check=True, timeout=10) + assert Path(json.loads(child.stdout)).resolve() == Path(cbb_refresh_verify.__file__).resolve()