From 6d45ea1fa043a29b8f8bf4ed887f0d813b4f68ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Wed, 25 Nov 2026 10:58:53 +0800 Subject: [PATCH] fix: resume frozen task queue after verified resource release --- .../2026-11-25-issue33-task-queue-resume.md | 21 + .../2026-11-25-issue33-d8/baseline-100.json | 80 +++ .../2026-11-25-issue33-d8/candidate-100.json | 542 ++++++++++++++++++ .../candidate-8-restart.json | 55 ++ src/dx_productivity/dsh/execution_runs.py | 11 +- src/dx_productivity/dsh/run_journal.py | 29 +- .../trial_task_center/project_isolation.py | 14 +- .../trial_task_center/task_queue.py | 132 ++++- .../trial_task_center/ui/main_window.py | 35 +- tests/dsh/test_run_journal.py | 24 + tests/v1_1/test_resource_queue_resume.py | 86 +++ tools/verify_issue33_queue.py | 244 ++++++++ 12 files changed, 1259 insertions(+), 14 deletions(-) create mode 100644 docs/testing/2026-11-25-issue33-task-queue-resume.md create mode 100644 docs/testing/evidence/2026-11-25-issue33-d8/baseline-100.json create mode 100644 docs/testing/evidence/2026-11-25-issue33-d8/candidate-100.json create mode 100644 docs/testing/evidence/2026-11-25-issue33-d8/candidate-8-restart.json create mode 100644 tests/v1_1/test_resource_queue_resume.py create mode 100644 tools/verify_issue33_queue.py diff --git a/docs/testing/2026-11-25-issue33-task-queue-resume.md b/docs/testing/2026-11-25-issue33-task-queue-resume.md new file mode 100644 index 0000000..e84f173 --- /dev/null +++ b/docs/testing/2026-11-25-issue33-task-queue-resume.md @@ -0,0 +1,21 @@ +# Issue #33 D8 · 原批次资源恢复验证 + +现场 100 工程按同一个任务队列执行。第 10 项已经隔离,第 11 项留下业务阻断回执,原队列仍有 89 项待派发。后台资源复核完成后,应用界面更新了资源状态,队列执行入口未再次读取原检查点。现场归档队列编号为 `55e1032ac965453b8adf307da1400511`。 + +候选在延续执行前核对监督进程与结束回执、原始请求摘要、队列编号、有序任务范围和计划哈希。现有写入资源和监督进程须通过释放核验。新暂停记录保存每个工程的写入源,恢复时重新读取工程声明,源不明确或变更时保留暂停。已经出具结果待核验回执的工程与共享其写入源的后续工程继续隔离。队列租约内消费原暂停记录并保存隔离状态,防止重复接续。同一用户授权运行可在资源释放后继续,用户主动暂停仍走原确认流程。 + +| Windows 场景 | 验证结果 | +| --- | --- | +| D7 基线,100 工程 | Windows 写进程退出后,首次返回 9 项完成、2 项阻断、89 项待执行。 [基线记录](evidence/2026-11-25-issue33-d8/baseline-100.json) | +| D8 候选,100 工程 | 写进程存活时,89 项仍待执行。退出后原队列自动继续,最终 97 项完成、3 项阻断。第 10、11 项各保留一条待核验回执,第 12 项共享数据库且零次替换派发。成功项各保存一次。 [候选记录](evidence/2026-11-25-issue33-d8/candidate-100.json) | +| D8 候选,8 工程 | 人工在第 3 项保存后暂停,保留 5 项待执行。启动不同 PID 的 Python 进程,以同一队列及冻结计划恢复到 8 项完成。每个作业 ID 仅派发一次。 [重启记录](evidence/2026-11-25-issue33-d8/candidate-8-restart.json) | + +夹具使用生产任务服务、队列、SQLite、监督协议和 Windows 进程退出检查。CAD 替换与保存结果使用故障注入回执。验收覆盖调度和恢复路径,真实 Mentor 批量替换另有实机环境依赖。 + +```powershell +$env:PYTHONPATH = (Resolve-Path src).Path +py -3.12 tools/verify_issue33_queue.py --projects 100 --output <新候选目录> +py -3.12 tools/verify_issue33_queue.py --projects 8 --output <新暂停目录> +``` + +将 `PYTHONPATH` 指向 D7 基线源码,并在 100 项命令追加 `--expect-baseline`,即可复跑基线。输出目录首次运行时应当不存在。 diff --git a/docs/testing/evidence/2026-11-25-issue33-d8/baseline-100.json b/docs/testing/evidence/2026-11-25-issue33-d8/baseline-100.json new file mode 100644 index 0000000..e561723 --- /dev/null +++ b/docs/testing/evidence/2026-11-25-issue33-d8/baseline-100.json @@ -0,0 +1,80 @@ +{ + "projects": 100, + "first_return": { + "completed": 9, + "blocked": 2, + "pending": 89 + }, + "before_release": { + "completed": 9, + "blocked": 2, + "pending": 89 + }, + "queue_id": "d935388f7bab4bf98c882280ec6c76a3", + "writer_pid": 56064, + "writer_gone": true, + "calls": [ + { + "project": 1, + "job_id": "c959a1eba7fb46f9b22d95f9afdff465_0", + "result": "saved_ok" + }, + { + "project": 2, + "job_id": "ab1fb1a7058a4b41b5886c3c01008aa7_0", + "result": "saved_ok" + }, + { + "project": 3, + "job_id": "490c1abb2a9441d8b5a8d70cbe5c0aa8_0", + "result": "saved_ok" + }, + { + "project": 4, + "job_id": "56b8dfaacb514a94ab506c632b37b647_0", + "result": "saved_ok" + }, + { + "project": 5, + "job_id": "d0d223381b9e4a01ababa484fcc07e82_0", + "result": "saved_ok" + }, + { + "project": 6, + "job_id": "abe6fa9a9919494ba433983cd125d1ac_0", + "result": "saved_ok" + }, + { + "project": 7, + "job_id": "2f103677ed4347938888e03b9b26b87f_0", + "result": "saved_ok" + }, + { + "project": 8, + "job_id": "5d4eeaed50bd46e89fd6830b51e8c3fb_0", + "result": "saved_ok" + }, + { + "project": 9, + "job_id": "ff4f78bf6e834c758fcb0fe9382a28fe_0", + "result": "saved_ok" + }, + { + "project": 10, + "job_id": "31ad660420e74b8499bd54abfbe250f5_0", + "result": "batch_saved_unverified" + }, + { + "project": 11, + "job_id": "321e40d86fe147bb977ba9865c1d24b9_0", + "result": "batch_saved_unverified" + } + ], + "supervisor_calls": [ + { + "batch_id": "d31e906c280e4849a22a3176ced4bee0", + "queue_id": null, + "resource_batch_id": null + } + ] +} \ No newline at end of file diff --git a/docs/testing/evidence/2026-11-25-issue33-d8/candidate-100.json b/docs/testing/evidence/2026-11-25-issue33-d8/candidate-100.json new file mode 100644 index 0000000..6965ac9 --- /dev/null +++ b/docs/testing/evidence/2026-11-25-issue33-d8/candidate-100.json @@ -0,0 +1,542 @@ +{ + "projects": 100, + "first_return": { + "completed": 97, + "blocked": 3 + }, + "before_release": { + "completed": 9, + "blocked": 2, + "pending": 89 + }, + "final": { + "completed": 97, + "blocked": 3 + }, + "supervisor_calls": [ + { + "batch_id": "15fcc3425d5f4a9ea172b7725023dd91", + "queue_id": null, + "resource_batch_id": null + }, + { + "batch_id": "78718bb8a02147358b441c540c902899", + "queue_id": "af07e3269bcd4a08afbf064af9126123", + "resource_batch_id": "15fcc3425d5f4a9ea172b7725023dd91" + }, + { + "batch_id": "862fad3b3d754c4a944135ff8256b1d8", + "queue_id": "af07e3269bcd4a08afbf064af9126123", + "resource_batch_id": null + }, + { + "batch_id": "69c5a03140bc4c5ca7d9bb52f6ff528f", + "queue_id": "af07e3269bcd4a08afbf064af9126123", + "resource_batch_id": null + } + ], + "queue_id": "af07e3269bcd4a08afbf064af9126123", + "shared_source_blocked": 12, + "writer_pid": 25028, + "release_checks": [ + 10, + 11 + ], + "calls": [ + { + "project": 1, + "job_id": "388bad5bafc54ae3b766a574f07feb44_0", + "result": "saved_ok" + }, + { + "project": 2, + "job_id": "78c6aa3632484ef795705071c4f6871e_0", + "result": "saved_ok" + }, + { + "project": 3, + "job_id": "b1e96b8625df4e8cb50f44c2faed14be_0", + "result": "saved_ok" + }, + { + "project": 4, + "job_id": "1c1419a896374821ac7c51a3117b75e1_0", + "result": "saved_ok" + }, + { + "project": 5, + "job_id": "df4e71b52bf842f093029d4dad56f797_0", + "result": "saved_ok" + }, + { + "project": 6, + "job_id": "1fcb7b6d75f44cdcbaed93accaa1c07d_0", + "result": "saved_ok" + }, + { + "project": 7, + "job_id": "6eeb02803cde4b2483ee776c9afeba1c_0", + "result": "saved_ok" + }, + { + "project": 8, + "job_id": "84c54eeb256d404582eda32019de17d8_0", + "result": "saved_ok" + }, + { + "project": 9, + "job_id": "05cf0fb9ad8b4c7d90d039d466de25a7_0", + "result": "saved_ok" + }, + { + "project": 10, + "job_id": "7c2ea733df924c1a9e04750f22134738_0", + "result": "batch_saved_unverified" + }, + { + "project": 11, + "job_id": "807cafae32bc495a894f5b35a6d1cb5e_0", + "result": "batch_saved_unverified" + }, + { + "project": 13, + "job_id": "304752f4d4c64e1bbabcbf55bff365fb_0", + "result": "saved_ok" + }, + { + "project": 14, + "job_id": "2040d066abc4482da2323b1b313e6e0e_0", + "result": "saved_ok" + }, + { + "project": 15, + "job_id": "908898c13c47472bb6f115f4910cccf4_0", + "result": "saved_ok" + }, + { + "project": 16, + "job_id": "3abda0f30178471c9af61afd5738b530_0", + "result": "saved_ok" + }, + { + "project": 17, + "job_id": "6c7365afea284aa3854b66af096bd098_0", + "result": "saved_ok" + }, + { + "project": 18, + "job_id": "f210b5d510344eb08f8d93ce05d001fe_0", + "result": "saved_ok" + }, + { + "project": 19, + "job_id": "eaaa69c064f0433fbab3874e0b331090_0", + "result": "saved_ok" + }, + { + "project": 20, + "job_id": "edc20d8c922f4bbaad379a3ce0db6891_0", + "result": "saved_ok" + }, + { + "project": 21, + "job_id": "f5cdef2f94b54d7da8c9c9c730557b8e_0", + "result": "saved_ok" + }, + { + "project": 22, + "job_id": "1dfc6665bfcf455e9246e212f92c689c_0", + "result": "saved_ok" + }, + { + "project": 23, + "job_id": "75385b75cf9140629f9aa1022bb2c53c_0", + "result": "saved_ok" + }, + { + "project": 24, + "job_id": "809cef1ba35b44d9be4ffd1dbd1ab000_0", + "result": "saved_ok" + }, + { + "project": 25, + "job_id": "367c3ffd715c4ef586f2e8824bbef491_0", + "result": "saved_ok" + }, + { + "project": 26, + "job_id": "bf5f3bdd3fb14fcc9740436fa464be37_0", + "result": "saved_ok" + }, + { + "project": 27, + "job_id": "a60a8566d058464495773969e6a99017_0", + "result": "saved_ok" + }, + { + "project": 28, + "job_id": "0c4c8103d7104788a5da9f017c0f1ace_0", + "result": "saved_ok" + }, + { + "project": 29, + "job_id": "eaa9e2e922e44c39a012af2519d951cf_0", + "result": "saved_ok" + }, + { + "project": 30, + "job_id": "e84022b8f6f949ddaee69e8067b9a795_0", + "result": "saved_ok" + }, + { + "project": 31, + "job_id": "8ab8ba8bad0e4b859e4720d0af2d56d8_0", + "result": "saved_ok" + }, + { + "project": 32, + "job_id": "0e7d3863480e4382b6b07ededa94f012_0", + "result": "saved_ok" + }, + { + "project": 33, + "job_id": "fbe7d3bf153644859f9b6a785fc98d64_0", + "result": "saved_ok" + }, + { + "project": 34, + "job_id": "6e1e4e3e44ad4aeeb51896837e6b84fb_0", + "result": "saved_ok" + }, + { + "project": 35, + "job_id": "efe7a9fb23944560bdac2212b2154cbe_0", + "result": "saved_ok" + }, + { + "project": 36, + "job_id": "50ef7be31e7740bbbf337e570690de86_0", + "result": "saved_ok" + }, + { + "project": 37, + "job_id": "8696162e1e7b4169b562f5454f8ddfb0_0", + "result": "saved_ok" + }, + { + "project": 38, + "job_id": "657ca58af33a4b7db33b19007e1ce071_0", + "result": "saved_ok" + }, + { + "project": 39, + "job_id": "a18f78199fd74601a007e8eb9ee15433_0", + "result": "saved_ok" + }, + { + "project": 40, + "job_id": "badd43d9a5624a689cc693bb7ea31652_0", + "result": "saved_ok" + }, + { + "project": 41, + "job_id": "bab81db14eb54782b869252fac15e570_0", + "result": "saved_ok" + }, + { + "project": 42, + "job_id": "92617c885ead4d838432c68e2255f7d0_0", + "result": "saved_ok" + }, + { + "project": 43, + "job_id": "216b4cda3f4148e7bc9d75ee5be8b6cb_0", + "result": "saved_ok" + }, + { + "project": 44, + "job_id": "3d57183d53304ce69933c982311b0f35_0", + "result": "saved_ok" + }, + { + "project": 45, + "job_id": "528549b58fd64769bc5016d3a4357aab_0", + "result": "saved_ok" + }, + { + "project": 46, + "job_id": "f8d51cf682604a08bd046123ab6a509a_0", + "result": "saved_ok" + }, + { + "project": 47, + "job_id": "c73cc80bbc35445b8e4ffbb26a884bb0_0", + "result": "saved_ok" + }, + { + "project": 48, + "job_id": "40a362b535034d15b4c89c4bc9af0c91_0", + "result": "saved_ok" + }, + { + "project": 49, + "job_id": "4df4aafeb2c841b494b9949c8ca230d2_0", + "result": "saved_ok" + }, + { + "project": 50, + "job_id": "7064b1e06df642c9a6c2fca037287ec4_0", + "result": "saved_ok" + }, + { + "project": 51, + "job_id": "f6caf03914f74a26b769873941506bd1_0", + "result": "saved_ok" + }, + { + "project": 52, + "job_id": "a2dea8f52ac04ed6ac1a2a28d9f8ef63_0", + "result": "saved_ok" + }, + { + "project": 53, + "job_id": "42e312a4cf6d453a88ee9b2163b191b5_0", + "result": "saved_ok" + }, + { + "project": 54, + "job_id": "45dbef10be42411c9a2a0248946d9037_0", + "result": "saved_ok" + }, + { + "project": 55, + "job_id": "2d6bfff0905149659324f152a5a37053_0", + "result": "saved_ok" + }, + { + "project": 56, + "job_id": "687a85f8e4684ebb99ae3371f08da745_0", + "result": "saved_ok" + }, + { + "project": 57, + "job_id": "f03c1b7e292d458fa1cf34fa32fcc6dc_0", + "result": "saved_ok" + }, + { + "project": 58, + "job_id": "2ddfbc06b4864f6cb76f7253fa35fab5_0", + "result": "saved_ok" + }, + { + "project": 59, + "job_id": "14e6219fdebe4b54bbd95cd95d82fe27_0", + "result": "saved_ok" + }, + { + "project": 60, + "job_id": "328b84460d394545a8b3a1701bb4668e_0", + "result": "saved_ok" + }, + { + "project": 61, + "job_id": "932ee1968d8548cb9b20d2205cbda07f_0", + "result": "saved_ok" + }, + { + "project": 62, + "job_id": "d61878a4fb6b42f69bc29d5a9039151f_0", + "result": "saved_ok" + }, + { + "project": 63, + "job_id": "df606318c32a445f83fe0aaafa47dd8b_0", + "result": "saved_ok" + }, + { + "project": 64, + "job_id": "810306d724314216b533239129fa5f00_0", + "result": "saved_ok" + }, + { + "project": 65, + "job_id": "95d51023c87b4fa6be5ed8c36b884b02_0", + "result": "saved_ok" + }, + { + "project": 66, + "job_id": "490361523d184a738048546ad39c5051_0", + "result": "saved_ok" + }, + { + "project": 67, + "job_id": "d51096842332404b97c5bd9b320e2b72_0", + "result": "saved_ok" + }, + { + "project": 68, + "job_id": "07beb872e39e4ed99bd63520b0b6f9e9_0", + "result": "saved_ok" + }, + { + "project": 69, + "job_id": "7fd5188c1c1d4eb3874c45629db474b2_0", + "result": "saved_ok" + }, + { + "project": 70, + "job_id": "b1690759022045288b9e3cec1089284f_0", + "result": "saved_ok" + }, + { + "project": 71, + "job_id": "f7e247a2619642f2a1f881891e8eeb57_0", + "result": "saved_ok" + }, + { + "project": 72, + "job_id": "aea8b540c89842d6869bc34564aa8a8f_0", + "result": "saved_ok" + }, + { + "project": 73, + "job_id": "1deab0ea04ee4ee2be2bf8a5564fcf7c_0", + "result": "saved_ok" + }, + { + "project": 74, + "job_id": "8808d235aba149bd8651675f2b10ceed_0", + "result": "saved_ok" + }, + { + "project": 75, + "job_id": "30505f56d58848be97ce2af31bf8590d_0", + "result": "saved_ok" + }, + { + "project": 76, + "job_id": "1aceadb5a89d4d068f318f8eeed650e4_0", + "result": "saved_ok" + }, + { + "project": 77, + "job_id": "b75a90feeb3f4737a3bbc31c55aa418c_0", + "result": "saved_ok" + }, + { + "project": 78, + "job_id": "21fe6401ceb34a80865a0d548ef707e5_0", + "result": "saved_ok" + }, + { + "project": 79, + "job_id": "4ca98380c3494062bbca254f3efb91e6_0", + "result": "saved_ok" + }, + { + "project": 80, + "job_id": "2eee50b616934bf9849d116fe4e313f4_0", + "result": "saved_ok" + }, + { + "project": 81, + "job_id": "32cf6eb628bd4039a6d591682c96c661_0", + "result": "saved_ok" + }, + { + "project": 82, + "job_id": "966a29d95f7040ceb044d818e0abcde0_0", + "result": "saved_ok" + }, + { + "project": 83, + "job_id": "8aa901efbd6149bc9744714992fd6021_0", + "result": "saved_ok" + }, + { + "project": 84, + "job_id": "9e6b5ecf9b714354b191e92add01d6c3_0", + "result": "saved_ok" + }, + { + "project": 85, + "job_id": "08bd3aac43aa4b7ea9dd980540951c8f_0", + "result": "saved_ok" + }, + { + "project": 86, + "job_id": "b70f927d89354785939daa703ae65dc3_0", + "result": "saved_ok" + }, + { + "project": 87, + "job_id": "e1f98f7188b6446c8218d83a2041d906_0", + "result": "saved_ok" + }, + { + "project": 88, + "job_id": "9c75b996f185424d9507fd00f2262fae_0", + "result": "saved_ok" + }, + { + "project": 89, + "job_id": "2671fb1be481453cbd382973d8d3807c_0", + "result": "saved_ok" + }, + { + "project": 90, + "job_id": "20044c501cf84140bc54114f903d40fd_0", + "result": "saved_ok" + }, + { + "project": 91, + "job_id": "a5eda4530b8940178dabf9f8e85b1a2a_0", + "result": "saved_ok" + }, + { + "project": 92, + "job_id": "fafda99d5f8344f18c574d4440c57518_0", + "result": "saved_ok" + }, + { + "project": 93, + "job_id": "b3247626d9e441208779273cd3e607bc_0", + "result": "saved_ok" + }, + { + "project": 94, + "job_id": "4dc0c755982f4fc1bd63803b83466aab_0", + "result": "saved_ok" + }, + { + "project": 95, + "job_id": "b41bcead3e0c45fe855f2fa08dfc668b_0", + "result": "saved_ok" + }, + { + "project": 96, + "job_id": "397b58aa73b042719410592f9b6ed4a1_0", + "result": "saved_ok" + }, + { + "project": 97, + "job_id": "012bde1609484512b83f23809f333c9d_0", + "result": "saved_ok" + }, + { + "project": 98, + "job_id": "00a4507a1c1f45f797e3f9e466c633b1_0", + "result": "saved_ok" + }, + { + "project": 99, + "job_id": "300db9dee9b947be85a596b9f538128e_0", + "result": "saved_ok" + }, + { + "project": 100, + "job_id": "c748b639f5034e8baaa0b2a6bed638ae_0", + "result": "saved_ok" + } + ] +} \ No newline at end of file diff --git a/docs/testing/evidence/2026-11-25-issue33-d8/candidate-8-restart.json b/docs/testing/evidence/2026-11-25-issue33-d8/candidate-8-restart.json new file mode 100644 index 0000000..3112601 --- /dev/null +++ b/docs/testing/evidence/2026-11-25-issue33-d8/candidate-8-restart.json @@ -0,0 +1,55 @@ +{ + "projects": 8, + "first_return": { + "completed": 3, + "pending": 5 + }, + "final": { + "completed": 8 + }, + "queue_id": "6bbbdf75c72e4a21844c51d1938ee725", + "calls": [ + { + "project": 1, + "job_id": "d4a210a4bea9478dbbe552f6fe87e125_0", + "result": "saved_ok" + }, + { + "project": 2, + "job_id": "b595108e12e24858ae8faa006b63c103_0", + "result": "saved_ok" + }, + { + "project": 3, + "job_id": "c74e034af94c4fdabaedee1b1d482771_0", + "result": "saved_ok" + }, + { + "project": 4, + "job_id": "1a7c1b81b15844f2bce705755164e2d9_0", + "result": "saved_ok" + }, + { + "project": 5, + "job_id": "267ea09123c44f20be66b0141f94177c_0", + "result": "saved_ok" + }, + { + "project": 6, + "job_id": "8d9f2932a57846da8d087d80ddaed2fb_0", + "result": "saved_ok" + }, + { + "project": 7, + "job_id": "a7e1d97f74d6495aa112831364ec47cc_0", + "result": "saved_ok" + }, + { + "project": 8, + "job_id": "6a77966ac69a47c1b8c984bcc655cd7e_0", + "result": "saved_ok" + } + ], + "paused_in_pid": 54160, + "resumed_in_pid": 60636 +} \ No newline at end of file diff --git a/src/dx_productivity/dsh/execution_runs.py b/src/dx_productivity/dsh/execution_runs.py index 67f816f..f64ca54 100644 --- a/src/dx_productivity/dsh/execution_runs.py +++ b/src/dx_productivity/dsh/execution_runs.py @@ -87,10 +87,12 @@ def _execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, res else: journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None) initialized = True + resource_batch_id = inspected.get('resource_batch_id') if resume else None result = execute_task_queue(service, tuple(task_ids), stop_event=stop, expected_plan_hashes=report['plan_hashes'], queue_id=run_id if resume and resume['queue_available'] else None, - checkpoint_id=None if resume and resume['queue_available'] else run_id) + checkpoint_id=None if resume and resume['queue_available'] else run_id, + **({'resource_batch_id': resource_batch_id} if resource_batch_id else {})) except Exception as error: failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}), 'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id, @@ -118,6 +120,13 @@ def _finish_execution_run(service, root, task_ids, stop, run_id, result, *, base 'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()), 'entries': entries, 'tasks': [], 'reporting_errors': [], 'message': '请按每项实际计数判断;未命中不表示已替换保存。'} + batch_id = getattr(service, '_last_supervisor_batch_id', None) + if result.paused and not stop.is_set() and batch_id: + from ..trial_task_center.task_queue import resource_pause_admitted + run = journal.get(run_id) + if (run and resource_pause_admitted(root, batch_id, tuple(task_ids), run['plan_hashes'], + result, require_released=False)): + receipt['resource_batch_id'] = batch_id if result.netlist_verification: receipt['netlist_verification'] = result.netlist_verification # Persist the executor's known outcome before optional readback/enrichment. diff --git a/src/dx_productivity/dsh/run_journal.py b/src/dx_productivity/dsh/run_journal.py index 193573a..4a6cd14 100644 --- a/src/dx_productivity/dsh/run_journal.py +++ b/src/dx_productivity/dsh/run_journal.py @@ -332,6 +332,31 @@ class RunJournal: released_primary = {key for key, entry in (queue['entries'].items() if workspace and queue else ()) if entry['released'] and entry['state'] in {'completed', 'failed', 'skipped', 'blocked'}} isolated = {key for key in released_primary if queue['entries'][key]['state'] == 'blocked'} + resource_batch_id = None + if queue and not workspace: + isolated.update(key for key in queue.get('isolated_tasks', {}) + if key in queue['entries'] and queue['entries'][key]['state'] == 'blocked') + receipt = row.get('result') or {} + if (receipt.get('paused') is True and receipt.get('user_pause_requested') is False + and any(entry['state'] == 'blocked' and key not in isolated + for key, entry in queue['entries'].items())): + from ..trial_task_center.task_queue import resource_pause_admitted + pause = queue.get('resource_pause') or {} + known_batch = receipt.get('resource_batch_id') or pause.get('batch_id') + candidates = (known_batch,) if known_batch else ( + path.parent.name for path in (self.data_root / 'batch-resources').glob('*/result.json')) + matches = [] + for batch_id in candidates: + paused = resource_pause_admitted(self.data_root, batch_id, + tuple(row['task_ids']), row['plan_hashes']) + if paused and paused.queue_id == run_id: + matches.append((batch_id, paused)) + if len(matches) > 1: + break + if len(matches) == 1: + resource_batch_id, paused = matches[0] + isolated.add(paused.current_task_id) + released_primary.update(isolated) safe_continuations = set() for task_id in row["task_ids"]: item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0} @@ -380,7 +405,8 @@ class RunJournal: counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"]) remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}] if queue and not workspace and queue.get('phase') in {'primary', 'problems'}: - remaining = [key for key in row['task_ids'] if key in remaining or key in released_primary] + remaining = [key for key in row['task_ids'] if key not in isolated and + (key in remaining or key in released_primary)] if workspace and queue: primary_exhausted = all(entry['state'] in {'completed', 'failed', 'skipped', 'blocked'} for entry in queue['entries'].values()) remaining = [key for key in row['task_ids'] if key not in isolated and ( @@ -407,6 +433,7 @@ class RunJournal: blockers.append("resources_pending") blockers = list(dict.fromkeys(blockers)) value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters, + 'resource_batch_id': resource_batch_id, 'isolated_task_ids': [key for key in row['task_ids'] if key in isolated], 'released_primary_task_ids': [key for key in row['task_ids'] if key in released_primary], 'safe_continuation_task_ids': [key for key in row['task_ids'] if key in safe_continuations], diff --git a/src/dx_productivity/trial_task_center/project_isolation.py b/src/dx_productivity/trial_task_center/project_isolation.py index e915849..e0298e1 100644 --- a/src/dx_productivity/trial_task_center/project_isolation.py +++ b/src/dx_productivity/trial_task_center/project_isolation.py @@ -6,20 +6,28 @@ import re from .path_access import canonical_path, internal_path -def write_sources(project): +def write_sources(project, *, strict=False): project = canonical_path(project) sources = {str(project).casefold()} try: from .native_inventory_protocol import read_native_text text = read_native_text(internal_path(project)) - match = re.search(r'^\s*KEY\s+iCDBDir\s+"([^"\r\n]+)"', text, re.MULTILINE | re.IGNORECASE) + if strict: + definitions = re.findall(r'^[ \t]*KEY[ \t]+iCDBDir\b([^\r\n]*)', text, + re.MULTILINE | re.IGNORECASE) + match = re.fullmatch(r'[ \t]+"([^"\r\n]+)"[ \t]*', definitions[0]) if len(definitions) == 1 else None + if not match: + raise ValueError('The iCDBDir write source must be declared once') + else: + match = re.search(r'^\s*KEY\s+iCDBDir\s+"([^"\r\n]+)"', text, re.MULTILINE | re.IGNORECASE) if match: directory = Path(match[1]) if not directory.is_absolute(): directory = project.parent / directory sources.add(str(canonical_path(directory / 'icdb.dat')).casefold()) except (OSError, UnicodeError, ValueError): - pass + if strict: + raise return sources diff --git a/src/dx_productivity/trial_task_center/task_queue.py b/src/dx_productivity/trial_task_center/task_queue.py index c596f10..9453ede 100644 --- a/src/dx_productivity/trial_task_center/task_queue.py +++ b/src/dx_productivity/trial_task_center/task_queue.py @@ -183,9 +183,76 @@ def reconcile_interrupted_queue(root, journal): _save(path, state) +def resource_pause_admitted(root, batch_id, task_ids, plan_hashes, result=None, *, require_released=True): + """Bind a completed supervisor's resource pause to the frozen queue.""" + from .batch_resources import _process_gone, blocking_resources + from .batch_supervisor import pending_supervisors + from .path_access import canonical_path, internal_path + from .supervisor_protocol import MessageGate, decode, valid_journal + + def token(value): + return isinstance(value, str) and len(value) == 32 and all(c in '0123456789abcdef' for c in value) + + if not token(batch_id) or not plan_hashes: + return False + root = canonical_path(root) + directory = internal_path(root / 'batch-resources' / batch_id) + try: + journal = json.loads((directory / 'supervisor.json').read_bytes()) + if (not valid_journal(journal, batch_id) or journal['state'] not in {'blocked', 'finished'} + or journal['operation'] != 'execute_task_queue' or journal['task_ids'] != list(task_ids) + or not journal['process'] or 'stop_requested_at' in journal + or journal.get('stop_mode') in {'safe', 'forced'} or (directory / 'cancel.json').exists()): + return False + raw_request = (directory / 'request.json').read_bytes() + request = json.loads(raw_request) + arguments = decode(request['arguments']) + if (hashlib.sha256(raw_request).hexdigest() != journal['request_sha256'] + or request['batch_id'] != batch_id or request['attempt_id'] != journal['attempt_id'] + or request['operation'] != journal['operation'] or canonical_path(request['root']) != root + or list(arguments['task_ids']) != list(task_ids) or arguments['expected_plan_hashes'] != plan_hashes): + return False + message = json.loads((directory / 'result.json').read_bytes()) + if not MessageGate(batch_id, journal['attempt_id']).accept(message) or message['type'] != 'result': + return False + payload = message['payload'] + recorded = decode(payload['result']) + if (payload['business_succeeded'] is not True or not isinstance(recorded, TaskQueueResult) + or result is not None and recorded != result or not recorded.paused + or not token(recorded.queue_id) or recorded.current_task_id not in task_ids + or (arguments['queue_id'] or arguments['checkpoint_id']) != recorded.queue_id): + return False + result = recorded + checkpoint = internal_path(root / 'task-queues' / (result.queue_id + '.json')) + state = json.loads(checkpoint.read_bytes()) + current = result.current_task_id + if (state['version'] != 1 or state['task_ids'] != list(task_ids) or state['plan_hashes'] != plan_hashes + or state['phase'] != 'primary' or set(state['entries']) != set(task_ids) + or list(entry.task_id for entry in result.entries) != list(task_ids) + or any(state['entries'][entry.task_id]['state'] != entry.state for entry in result.entries) + or state['entries'][current]['state'] != 'blocked' + or any(entry.state in {'paused', 'running'} for entry in result.entries) + or not any(state['entries'][item]['state'] == 'pending' for item in task_ids[task_ids.index(current) + 1:])): + return False + if batch_id in state.get('consumed_resource_pauses', {}): + return False + warning = payload.get('resource_warning') or {} + pause = state.get('resource_pause') or {} + intended = ((pause.get('task_id'), pause.get('batch_id')) == (current, batch_id) + and isinstance(pause.get('sources'), dict) + and set(pause['sources']) == set(task_ids) + or not pause and warning.get('state') == 'isolated' and warning.get('owned_writers_exited') is True) + if intended and (not require_released or (journal['state'] == 'finished' + and _process_gone(journal['process']) and not blocking_resources(root) and not pending_supervisors(root))): + return result + return False + except (OSError, ValueError, TypeError, KeyError, AttributeError): + return False + + def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None, - defer_problem_pass=False) -> TaskQueueResult: + defer_problem_pass=False, resource_batch_id=None) -> TaskQueueResult: """Execute the frozen order; uncertain state stops before the next project.""" if runtime is None and getattr(service, '_supervised', False): # Existing per-project checkpoints keep their original resume owner. @@ -196,9 +263,30 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, return execute_workspace_projects(service, task_ids, queue_id=queue_id, stop_event=stop_event, expected_plan_hashes=expected_plan_hashes, checkpoint_id=checkpoint_id, defer_problem_pass=defer_problem_pass) - return service._supervise('execute_task_queue', {'task_ids': tuple(task_ids), + arguments = {'task_ids': tuple(task_ids), 'queue_id': queue_id, 'expected_plan_hashes': expected_plan_hashes, - 'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass}, stop_event=stop_event) + 'checkpoint_id': checkpoint_id, 'defer_problem_pass': defer_problem_pass} + if resource_batch_id: + arguments['resource_batch_id'] = resource_batch_id + recovered = set() + while True: + try: + result = service._supervise('execute_task_queue', arguments, stop_event=stop_event) + except TaskCenterError as error: + result = getattr(error, 'completed_result', None) + batch_id = getattr(service, '_last_supervisor_batch_id', None) + if (error.code not in {'batch_resources_pending', 'application_shutdown_failed'} + or stop_event.is_set() or not isinstance(result, TaskQueueResult) + or not resource_pause_admitted(service._logging.root, batch_id, tuple(task_ids), + expected_plan_hashes, result, require_released=False)): + raise + if (not result.paused or stop_event.is_set() or result.current_task_id in recovered + or not resource_pause_admitted(service._logging.root, + batch_id := getattr(service, '_last_supervisor_batch_id', None), tuple(task_ids), + expected_plan_hashes, result)): + return result + recovered.add(result.current_task_id) + arguments = dict(arguments, queue_id=result.queue_id, checkpoint_id=None, resource_batch_id=batch_id) if runtime is None: from .batch_runtime import BatchCadRuntime with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime: @@ -213,7 +301,7 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, root = service._logging.root with _queue_lease(root): children = {task_id: service.for_project_task(task_id) for task_id in ids} - project_paths = [] + project_paths, projects_by_task = [], {} sources = {} for task_id, child in children.items(): task = child.get_task(task_id) @@ -221,9 +309,14 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, if not getattr(task, 'primary_project_id', None) or len(projects) != 1: raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。') project_paths.append(str(projects[0].path.resolve(strict=False)).casefold()) + projects_by_task[task_id] = projects[0].path sources[task_id] = write_sources(projects[0].path) if len(set(project_paths)) != len(ids): raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。') + try: + frozen_sources = {item: sorted(write_sources(projects_by_task[item], strict=True)) for item in ids} + except (OSError, UnicodeError, ValueError): + frozen_sources = None runtime.bind_logs(service._logging, ids) hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()} if expected_plan_hashes is not None and hashes != expected_plan_hashes: @@ -260,6 +353,29 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, isolated_tasks = state.setdefault('isolated_tasks', {}) isolated_sources = state.setdefault('isolated_sources', {}) dependency_tasks = state.setdefault('dependency_tasks', {}) + if resource_batch_id: + evidence = resource_pause_admitted(root, resource_batch_id, ids, hashes) + if not evidence or evidence.queue_id != queue_id: + raise TaskCenterError('task_queue_state', '原队列的资源释放或阻断回执无法核验。') + item = evidence.current_task_id + if not children[item].has_interrupted_quick_run(item): + raise TaskCenterError('task_queue_state', '阻断工程缺少原待核验证据。') + pause = state.get('resource_pause') + if pause: + known_sources = pause['sources'] + else: + before = (state.get('netlist_verification', {}).get(item, {}).get('before') or {}) + known = [str(Path(name).resolve()).casefold() for name in before.get('source_hashes', {}) + if Path(name).suffix.casefold() == '.prj' or Path(name).name.casefold() == 'icdb.dat'] + known_sources = {item: sorted(known)} + if not frozen_sources or any(frozen_sources.get(task) != values for task, values in known_sources.items()): + raise TaskCenterError('task_queue_state', '工程写入源已变化或无法核验,须重新确认。') + sources = {task: set(values) for task, values in frozen_sources.items()} + isolated_tasks[item] = state['entries'][item]['message'] + isolated_sources.update((source, item) for source in sources[item]) + state.setdefault('consumed_resource_pauses', {})[resource_batch_id] = item + state.pop('resource_pause', None) + _save(path, state) from .netlist_verification import NetlistVerification checks = NetlistVerification(root, token, stop_event) try: @@ -289,7 +405,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, continue if state['entries'][task_id]['state'] in _TERMINAL: if state['entries'][task_id]['state'] == 'completed': - checks.before_task(children[task_id], task_id, existing_only=True) + if not resource_batch_id or task_id not in state.get('netlist_verification', {}): + checks.before_task(children[task_id], task_id, existing_only=True) continue if stop_event.is_set(): paused = True @@ -409,6 +526,11 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event, execution_summary={key: getattr(progress, key, None) for key in ('saved_items', 'failed_items', 'no_match_items')}) if paused: + if (entry['state'] == 'blocked' and not stop_event.is_set() + and frozen_sources and hasattr(runtime, 'session_id')): + state['resource_pause'] = {'task_id': task_id, 'batch_id': runtime.session_id, + 'sources': frozen_sources} + _save(path, state) break if (not paused and stop_event.is_set() and state.get('phase') != 'finished' and any(entry['state'] == 'failed' for entry in state['entries'].values())): diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index 97523e9..7377457 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -122,6 +122,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._batch_stop = None self._active_quick_run_task_id = None self._project_queues = {} + self._resource_queue_resume = None self._execution_after_save = None self._generation = 0 self._message = '' @@ -214,6 +215,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._dsh_stall_timer.start() self._resource_status.changed.connect(self._update_gates) self._resource_status.changed.connect(self._observe_dsh_resource_blockers) + self._resource_status.changed.connect(self._resume_resource_queue) self._resource_status.refresh() self._refresh_task_list() self._update_gates() @@ -869,7 +871,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._bind_dsh_context() self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id) - def _execute_project_tasks(self): + def _execute_project_tasks(self, *, resource_resume=False): if not self.task_list.queue_button.isEnabled(): return owner_task_id = self._context.task.task_id @@ -885,7 +887,10 @@ class TrialTaskCenterWindow(MaterialMainWindow): try: if token: from ...dsh.run_journal import resume_preflight - report = resume_preflight(self.service, self._dsh_operations.runs.inspect(self.service, token)) + inspected = self._dsh_operations.runs.inspect(self.service, token) + if resource_resume and not inspected.get('resource_batch_id'): + return + report = resume_preflight(self.service, inspected) else: report = lifecycle.preflight(self.service, list(ids), allow_completed=True) except Exception as error: @@ -895,7 +900,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): return self._dsh_confirmation_impact = report.get('impact', {}) enabled = report.get('impact', {}).get('enabled_scope', 0) - if not self._quick_run_confirmer('batch', len(ids), enabled): + if not resource_resume and not self._quick_run_confirmer('batch', len(ids), enabled): return if not self._confirmed_execution_allowed(owner_task_id, ids, self.task_list.queue_button): return @@ -941,9 +946,30 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._show_receipt_verification(receipt) self._dsh_last_execution = receipt self._bind_dsh_context() + if (result.paused and receipt.get('resource_batch_id') and not stop.is_set() + and not self._close_pending and not self._closed): + self._resource_queue_resume = (group, result.queue_id, ids) else: done(value) - self._run_async(execute, completed, self.task_list.queue_button) + self._run_async(execute, completed, self.task_list.queue_button, on_finished=self._check_resource_queue) + + def _check_resource_queue(self): + if self._resource_queue_resume and self._resource_status.blocked and not self._workers: + self._cleanup_batch_resources(automatic=True) + else: + self._resume_resource_queue() + + def _resume_resource_queue(self): + pending = self._resource_queue_resume + if (not pending or self._closed or self._close_pending or self._workers or self._loading + or self._resource_status.busy or not self._resource_status.known or self._resource_status.blocked): + return + group, token, ids = pending + if (self._context is None or self._context.task.group_id != group + or self._project_queues.get(group) != (token, ids) or self.plan_panel.has_unsaved_plan(ids)): + return + self._resource_queue_resume = None + self._execute_project_tasks(resource_resume=True) def _begin_run(self, task_id): from uuid import uuid4 @@ -1056,6 +1082,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): nonlocal cleanup_finished cleanup_finished = True start_force_if_ready() + self._resume_resource_queue() def forced(remaining): from ..batch_resources import resource_blockers self._resource_status.refresh() diff --git a/tests/dsh/test_run_journal.py b/tests/dsh/test_run_journal.py index 10138d6..f22c45c 100644 --- a/tests/dsh/test_run_journal.py +++ b/tests/dsh/test_run_journal.py @@ -96,6 +96,30 @@ def test_inspect_accepts_frozen_workspace_checkpoint(project_service): assert result['remaining_task_ids'] == ids +def test_inspect_restores_a_legacy_resource_pause_only_from_its_original_batch(project_service, monkeypatch): + from dx_productivity.trial_task_center import task_queue + service, _, data, ids, hashes = project_service + journal = RunJournal(data) + token, batch_id = 'a' * 32, 'b' * 32 + journal.begin(token, ids, hashes) + checkpoint(data, token, ids, hashes, {ids[0]: 'blocked'}) + path = data / 'task-queues' / (token + '.json') + state = json.loads(path.read_bytes()) + path.write_text(json.dumps(dict(state, phase='primary')), encoding='utf-8') + journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': False}) + archive = data / 'batch-resources' / batch_id / 'result.json' + archive.parent.mkdir(parents=True) + archive.touch() + monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda root, owner, tasks, plan: + TaskQueueResult(token, (), True, ids[0]) if owner == batch_id and tuple(ids) == tasks and hashes == plan else False) + result = journal.inspect(service, token) + assert result['resource_batch_id'] == batch_id + assert result['isolated_task_ids'] == ids[:1] + assert result['remaining_task_ids'] == ids[1:] + journal.finish(token, {'status': 'blocked', 'paused': True, 'user_pause_requested': True}) + assert journal.inspect(service, token)['resource_batch_id'] is None + + @pytest.mark.parametrize('interrupted', [False, True]) def test_shared_safe_primary_failure_can_hold_remaining_commands_on_resume(project_service, monkeypatch, interrupted): from dataclasses import replace diff --git a/tests/v1_1/test_resource_queue_resume.py b/tests/v1_1/test_resource_queue_resume.py new file mode 100644 index 0000000..feeaa9a --- /dev/null +++ b/tests/v1_1/test_resource_queue_resume.py @@ -0,0 +1,86 @@ +import hashlib +import json +from threading import Event +from types import SimpleNamespace + +import pytest + +from dx_productivity.trial_task_center import task_queue +from dx_productivity.trial_task_center.supervisor_protocol import encode +from dx_productivity.trial_task_center.task_queue import TaskQueueEntry, TaskQueueResult + + +@pytest.mark.parametrize('release', [True, False]) +@pytest.mark.parametrize('user_pause', [False, True]) +def test_normal_supervised_queue_reuses_original_queue_after_resource_pause(tmp_path, monkeypatch, release, user_pause): + ids = ('A', 'B', 'C') + token = 'a' * 32 + hashes = dict.fromkeys(ids, 'f' * 64) + result = TaskQueueResult(token, (TaskQueueEntry('A', 'completed'), TaskQueueEntry('B', 'blocked'), + TaskQueueEntry('C', 'pending')), True, 'B') + done = TaskQueueResult(token, (result.entries[0], result.entries[1], TaskQueueEntry('C', 'completed')), False) + calls = [] + service = SimpleNamespace(_supervised=True, _logging=SimpleNamespace(root=tmp_path)) + stop = Event() + + def supervise(operation, arguments, **kwargs): + calls.append(arguments) + if user_pause: + stop.set() + return result if len(calls) == 1 else done + + service._supervise = supervise + service._last_supervisor_batch_id = 'b' * 32 + service.pending_batch_resources = lambda: () + monkeypatch.setattr(task_queue, 'resource_pause_admitted', lambda *args: release, raising=False) + resumed = release and not user_pause + assert task_queue.execute_task_queue(service, ids, stop_event=stop, checkpoint_id=token, + expected_plan_hashes=hashes) == (done if resumed else result) + assert [call['checkpoint_id'] for call in calls] == ([token, None] if resumed else [token]) + if resumed: + assert calls[-1]['queue_id'] == token + assert calls[-1]['expected_plan_hashes'] == hashes + + +@pytest.mark.parametrize('reason', [None, 'unknown_writer', 'cancel', 'consumed', 'unknown_pause']) +def test_original_receipt_must_prove_resource_pause_and_cannot_be_consumed_again(tmp_path, monkeypatch, reason): + from dx_productivity.trial_task_center import batch_resources + + batch_id, attempt, queue = 'b' * 32, 'c' * 32, 'a' * 32 + ids, hashes = ('A', 'B'), {'A': '01', 'B': '02'} + entries = (TaskQueueEntry('A', 'blocked'), TaskQueueEntry('B', 'pending')) + result = TaskQueueResult(queue, entries, True, 'A') + folder = tmp_path / 'batch-resources' / batch_id + request = {'batch_id': batch_id, 'attempt_id': attempt, 'operation': 'execute_task_queue', 'root': str(tmp_path), + 'arguments': encode({'task_ids': ids, 'queue_id': None, 'checkpoint_id': queue, + 'expected_plan_hashes': hashes})} + batch_resources.write_record(folder / 'request.json', request) + digest = hashlib.sha256((folder / 'request.json').read_bytes()).hexdigest() + process = {'pid': 17, 'creation_time': 'worker'} + batch_resources.write_record(folder / 'supervisor.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt, + 'operation': 'execute_task_queue', 'task_ids': list(ids), 'parent_process': process, + 'process': process, 'state': 'finished', 'request_sha256': digest}) + payload = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)} + if reason != 'unknown_pause': + payload['resource_warning'] = {'state': 'isolated', 'owned_writers_exited': True} + batch_resources.write_record(folder / 'result.json', {'version': 1, 'batch_id': batch_id, 'attempt_id': attempt, + 'generation': 1, 'sequence': 1, 'type': 'result', 'payload': payload}) + state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes, 'phase': 'primary', + 'entries': {entry.task_id: {'state': entry.state, 'message': entry.message} for entry in entries}} + if reason == 'consumed': + state['consumed_resource_pauses'] = {batch_id: 'A'} + if reason == 'cancel': + (folder / 'cancel.json').write_text(json.dumps({'batch_id': batch_id})) + batch_resources.write_record(tmp_path / 'task-queues' / (queue + '.json'), state) + monkeypatch.setattr(batch_resources, '_process_gone', lambda _: reason != 'unknown_writer') + assert task_queue.resource_pause_admitted(tmp_path, batch_id, ids, hashes) == (False if reason else result) + + +@pytest.mark.parametrize('text', ['', 'KEY iCDBDir database', 'KEY iCDBDir "database"\nKEY iCDBDir "../other"']) +def test_ambiguous_or_missing_write_sources_cannot_be_used_to_resume(tmp_path, text): + from dx_productivity.trial_task_center.project_isolation import write_sources + + project = tmp_path / 'board.prj' + project.write_text(text) + with pytest.raises(ValueError, match='iCDBDir'): + write_sources(project, strict=True) diff --git a/tools/verify_issue33_queue.py b/tools/verify_issue33_queue.py new file mode 100644 index 0000000..58e6ace --- /dev/null +++ b/tools/verify_issue33_queue.py @@ -0,0 +1,244 @@ +"""Run issue #33 D8 through real service/SQLite queues with an injected CAD runner.""" +from argparse import ArgumentParser +from collections import Counter +import csv +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +from uuid import uuid4 + +from dx_productivity.trial_task_center import supervisor_protocol +from dx_productivity.trial_task_center.batch_resources import _process_gone, process_identity, write_record +from dx_productivity.trial_task_center.inventory import HEADER +from dx_productivity.trial_task_center.logging_setup import configure_logging +from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _decode_vbs_field +from dx_productivity.trial_task_center.service import TaskCenterService +from dx_productivity.trial_task_center.stop_control import StopControl +from dx_productivity.trial_task_center.store import TaskStore +from dx_productivity.trial_task_center.target_plan import TargetPlanRow +from dx_productivity.trial_task_center.task_queue import _plan_hash, execute_task_queue + + +class SimulatedRuntime: + cad = desktop = None + stop_event = None + + def __init__(self, root, release): + self.root = root + self.release = release + self.session_id = uuid4().hex + + def bind_logs(self, *_): + pass + + def release_failed_project(self, *args): + return self.release(*args) + + +def run(root, projects, *, expect_baseline, resume_short=False): + resource_failure = projects == 100 + data = root / 'data' + source = root / 'projects' + shared = source / 'shared-db' + prior, blocked, dependent = (10, 11, 12) if resource_failure else (0, 0, 0) + if not resume_short: + root.mkdir(parents=True) + shared.mkdir(parents=True) + (shared / 'icdb.dat').write_bytes(b'simulated shared design source') + for ordinal in range(1, projects + 1): + path = source / f'board-{ordinal:03}' / 'board.prj' + path.parent.mkdir() + databank = shared if ordinal in (blocked, dependent) else 'database' + path.write_text(f'KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "{databank}"\n', encoding='utf-8') + data.mkdir() + + stop = StopControl() + calls = [] + release_checks = [] + supervisor_calls = [] + pre_cleanup = None + live_writer = None + identity = None + + def worker(command, _timeout): + evidence = Path(command[3]) + command_path = evidence / 'current-command.tsv' + if not command_path.exists(): + command_path = evidence / 'command.tsv' + with command_path.open(encoding='utf-8-sig') as stream: + item = next(csv.DictReader(stream, delimiter='\t')) + path = Path(item['project_path']) + ordinal = int(path.parent.name.split('-')[-1]) + if (evidence / 'sheet-discovery.request').exists(): + (evidence / 'sheets.tsv').write_text(f'project_path\tschematic_name\tsheet_number\n{path}\tMAIN\t1\n') + (evidence / 'inventory.tsv').write_text(f'project_path\tschematic_name\tsheet_number\told_part\n{path}\tMAIN\t1\tOLD\n') + (evidence / 'components.tsv').write_text('\t'.join(HEADER) + f'\n{path}\tMAIN\t1\tuid\tR1\tOLD\t10K\n') + return subprocess.CompletedProcess(command, 0, '', '') + job = command[-1] + assert item['job_id'] == job + assert _decode_vbs_field(item['target_selectors']) == 'uid\x1fR1\x1f10K' + assert all(call['project'] != ordinal and call['job_id'] != job for call in calls) + state = 'batch_saved_unverified' if ordinal in (prior, blocked) else 'saved_ok' + calls.append({'project': ordinal, 'job_id': job, 'result': state}) + message = ('Native replacement and parameter readback passed on current sheet. Replacements: ' + 'R1 OLD -> NEW Display verified: attributes=2. Saved, reopened for readback, and closed.') + if state != 'saved_ok': + message = 'Injected lookup timeout after an earlier possible CAD write.' + with (evidence / 'status.tsv').open('a', encoding='utf-8') as stream: + stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n') + stream.write(f'{job}\t{state}\tbatch_closed\t{message}\n') + if not resource_failure and ordinal == 3: + stop.set() + return subprocess.CompletedProcess(command, 0, '', '') + + store = None + + def open_service(): + nonlocal store + store = TaskStore(data / 'task-center.db') + service = TaskCenterService(store, configure_logging(data), quick_run_preparer=QuickRunPreparer( + data, process_runner=worker, cscript_resolver=lambda: Path('simulated-cscript'), + sheet_discoverer=lambda _: (('MAIN', '1'),))) + service._supervised = True + + def supervise(operation, arguments, *, stop_event): + nonlocal pre_cleanup + assert operation == 'execute_task_queue' + runtime = SimulatedRuntime(data, release) + supervisor_calls.append(dict(batch_id=runtime.session_id, queue_id=arguments.get('queue_id'), + resource_batch_id=arguments.get('resource_batch_id'))) + result = execute_task_queue(service, stop_event=stop_event, runtime=runtime, **arguments) + if resource_failure and live_writer is not None and live_writer.poll() is None: + assert result.paused and result.current_task_id == ids[blocked - 1] + assert [entry['project'] for entry in calls] == list(range(1, blocked + 1)) + assert not _process_gone(identity) + pre_cleanup = Counter(row.state for row in result.entries) + batch_id = runtime.session_id + attempt_id = uuid4().hex + directory = data / 'batch-resources' / batch_id + common = dict(version=supervisor_protocol.VERSION, batch_id=batch_id, attempt_id=attempt_id) + write_record(directory / 'request.json', dict(common, operation=operation, + root=str(data), arguments=supervisor_protocol.encode(arguments))) + request_digest = hashlib.sha256((directory / 'request.json').read_bytes()).hexdigest() + write_record(directory / 'result.json', dict(common, sequence=1, generation=1, type='result', + payload=dict(business_succeeded=True, result=supervisor_protocol.encode(result)))) + journal = dict(common, operation=operation, task_ids=list(ids), state='finished', + process=identity, parent_process=identity, request_sha256=request_digest) + assert supervisor_protocol.valid_journal(journal, batch_id) + write_record(directory / 'supervisor.json', journal) + service._last_supervisor_batch_id = batch_id + from dx_productivity.trial_task_center import task_queue + admitted = getattr(task_queue, 'resource_pause_admitted', None) + if admitted is not None: + assert not admitted(data, batch_id, ids, hashes, result) + live_writer.terminate() + live_writer.wait(timeout=10) + assert _process_gone(identity) + return result + + def release(error, evidence): + nonlocal live_writer, identity + ordinal = calls[-1]['project'] + release_checks.append(ordinal) + if resource_failure and ordinal == blocked and live_writer is None: + live_writer = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(300)'], + creationflags=subprocess.CREATE_NO_WINDOW) + identity = process_identity(live_writer) + return live_writer is None or live_writer.poll() is not None + + service._supervise = supervise + return service + + service = open_service() + try: + if resume_short: + recorded = json.loads((root / 'pause.json').read_text(encoding='utf-8')) + ids = tuple(recorded['checkpoint']['task_ids']) + hashes = recorded['checkpoint']['plan_hashes'] + calls.extend(recorded['calls']) + result = execute_task_queue(service, ids, stop_event=stop, + queue_id=recorded['queue_id'], expected_plan_hashes=hashes) + assert result.queue_id == recorded['queue_id'] + final = json.loads((data / 'task-queues' / (result.queue_id + '.json')).read_text(encoding='utf-8')) + assert final['task_ids'] == list(ids) and final['plan_hashes'] == hashes + assert final['phase'] == 'finished' and not result.paused + assert Counter(row.state for row in result.entries) == {'completed': projects} + assert [call['project'] for call in calls] == list(range(1, projects + 1)) + assert recorded['paused_in_pid'] != os.getpid() + return dict(projects=projects, first_return=recorded['first_return'], + final={'completed': projects}, queue_id=result.queue_id, calls=calls, + paused_in_pid=recorded['paused_in_pid'], resumed_in_pid=os.getpid()) + tasks = service.create_project_tasks(source) + ids = tuple(task.task_id for task in tasks) + assert len(ids) == projects + assert [service.projects(task_id)[0].path.parent.name for task_id in ids] == [ + f'board-{number:03}' for number in range(1, projects + 1)] + service.add_rule(ids[0], 'OLD', 'NEW') + for task_id in ids: + targets = service.collect_target_inventory(task_id, runtime=SimulatedRuntime(data, lambda *_: True)) + service.replace_target_plan(task_id, [TargetPlanRow(targets[0].target, enabled=True, new_part_number='NEW')]) + hashes = {task_id: _plan_hash(service.for_project_task(task_id), task_id) for task_id in ids} + first = execute_task_queue(service, ids, stop_event=stop, expected_plan_hashes=hashes, + checkpoint_id=uuid4().hex) + path = data / 'task-queues' / (first.queue_id + '.json') + checkpoint = json.loads(path.read_text(encoding='utf-8')) + initial = Counter(row.state for row in first.entries) + print(f'{projects} projects first return {dict(initial)}', flush=True) + if resource_failure: + assert pre_cleanup == {'completed': 9, 'blocked': 2, 'pending': projects - 11} + if expect_baseline: + assert first.paused and initial == pre_cleanup + return dict(projects=projects, first_return=initial, before_release=pre_cleanup, + queue_id=first.queue_id, writer_pid=identity['pid'], + writer_gone=_process_gone(identity), calls=calls, supervisor_calls=supervisor_calls) + assert not first.paused and initial == {'completed': 97, 'blocked': 3} + assert len(supervisor_calls) == 2 + assert supervisor_calls[-1]['queue_id'] == first.queue_id + assert supervisor_calls[-1]['resource_batch_id'] == supervisor_calls[0]['batch_id'] + else: + assert first.paused and [entry['project'] for entry in calls] == [1, 2, 3] + write_record(root / 'pause.json', dict(queue_id=first.queue_id, checkpoint=checkpoint, + calls=calls, first_return=initial, paused_in_pid=os.getpid())) + store.close() + subprocess.run([sys.executable, __file__, '--projects', str(projects), '--output', str(root), + '--resume-short'], check=True, creationflags=subprocess.CREATE_NO_WINDOW) + return json.loads((root / 'report.json').read_text(encoding='utf-8')) + + store.close() + service = open_service() + stop = StopControl() + result = execute_task_queue(service, ids, stop_event=stop, queue_id=first.queue_id, expected_plan_hashes=hashes) + final = json.loads(path.read_text(encoding='utf-8')) + assert final['task_ids'] == checkpoint['task_ids'] + assert final['plan_hashes'] == checkpoint['plan_hashes'] + assert final['phase'] == 'finished' and not result.paused + if resource_failure: + assert final['dependency_tasks'] == {ids[dependent - 1]: ids[blocked - 1]} + assert [entry.state for entry in result.entries[prior - 1:dependent]] == ['blocked'] * 3 + assert [call['project'] for call in calls] == [ordinal for ordinal in range(1, projects + 1) if ordinal != dependent] + assert execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id) == result + return dict(projects=projects, first_return=initial, before_release=pre_cleanup, + final=Counter(row.state for row in result.entries), supervisor_calls=supervisor_calls, + queue_id=result.queue_id, shared_source_blocked=dependent or None, + writer_pid=(identity or {}).get('pid'), release_checks=release_checks, calls=calls) + finally: + if live_writer is not None and live_writer.poll() is None: + live_writer.terminate() + live_writer.wait(timeout=10) + store.close() + + +if __name__ == '__main__': + parser = ArgumentParser(description=__doc__) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--projects', type=int, choices=(8, 100), required=True) + parser.add_argument('--expect-baseline', action='store_true') + parser.add_argument('--resume-short', action='store_true', help='Internal pause handoff to a new Python process') + args = parser.parse_args() + result = run(args.output.resolve(), args.projects, expect_baseline=args.expect_baseline, + resume_short=args.resume_short) + (args.output / 'report.json').write_text(json.dumps(result, indent=2), encoding='utf-8') + print({key: result.get(key) for key in ('projects', 'first_return', 'final', 'queue_id')}, flush=True)