trueppm-api 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (799) hide show
  1. trueppm_api/__init__.py +27 -0
  2. trueppm_api/apps/access/__init__.py +0 -0
  3. trueppm_api/apps/access/apps.py +19 -0
  4. trueppm_api/apps/access/groups.py +518 -0
  5. trueppm_api/apps/access/management/__init__.py +0 -0
  6. trueppm_api/apps/access/management/commands/__init__.py +0 -0
  7. trueppm_api/apps/access/management/commands/create_admin.py +346 -0
  8. trueppm_api/apps/access/management/commands/migrate_locked.py +96 -0
  9. trueppm_api/apps/access/management/commands/revoke_api_tokens.py +483 -0
  10. trueppm_api/apps/access/migrations/0001_initial.py +61 -0
  11. trueppm_api/apps/access/migrations/0001_squashed_0012_programmembership_role_title.py +184 -0
  12. trueppm_api/apps/access/migrations/0002_alter_projectmembership_id.py +29 -0
  13. trueppm_api/apps/access/migrations/0003_projectmembership_soft_delete.py +24 -0
  14. trueppm_api/apps/access/migrations/0004_alter_projectmembership_role.py +34 -0
  15. trueppm_api/apps/access/migrations/0005_program_entity_and_membership.py +76 -0
  16. trueppm_api/apps/access/migrations/0006_role_ordinal_spacing.py +113 -0
  17. trueppm_api/apps/access/migrations/0007_projectmembership_joined_at_and_more.py +35 -0
  18. trueppm_api/apps/access/migrations/0008_projectmembership_source_group.py +25 -0
  19. trueppm_api/apps/access/migrations/0009_projectmembership_pm_proj_serverver_idx.py +20 -0
  20. trueppm_api/apps/access/migrations/0010_programmembership_joined_at_and_more.py +38 -0
  21. trueppm_api/apps/access/migrations/0011_alter_programmembership_unique_together_and_more.py +36 -0
  22. trueppm_api/apps/access/migrations/0012_programmembership_role_title.py +17 -0
  23. trueppm_api/apps/access/migrations/0013_squashed_0019_release_0_4.py +302 -0
  24. trueppm_api/apps/access/migrations/0013_userdefinedmentiongroup.py +82 -0
  25. trueppm_api/apps/access/migrations/0014_programmembership_progm_serverver_idx.py +19 -0
  26. trueppm_api/apps/access/migrations/0015_programuserdefinedmentiongroup.py +86 -0
  27. trueppm_api/apps/access/migrations/0016_externalstakeholder.py +67 -0
  28. trueppm_api/apps/access/migrations/0017_viewer_ordinal_one.py +143 -0
  29. trueppm_api/apps/access/migrations/0018_programmembership_sync_seq_and_more.py +52 -0
  30. trueppm_api/apps/access/migrations/0019_programmembership_reinstated_at_and_more.py +22 -0
  31. trueppm_api/apps/access/migrations/__init__.py +0 -0
  32. trueppm_api/apps/access/minter_role.py +38 -0
  33. trueppm_api/apps/access/models.py +588 -0
  34. trueppm_api/apps/access/permissions.py +3263 -0
  35. trueppm_api/apps/access/serializers.py +1007 -0
  36. trueppm_api/apps/access/services.py +878 -0
  37. trueppm_api/apps/access/signals.py +171 -0
  38. trueppm_api/apps/access/tasks.py +50 -0
  39. trueppm_api/apps/access/throttles.py +96 -0
  40. trueppm_api/apps/access/urls.py +191 -0
  41. trueppm_api/apps/access/views.py +1965 -0
  42. trueppm_api/apps/agents/__init__.py +6 -0
  43. trueppm_api/apps/agents/apps.py +11 -0
  44. trueppm_api/apps/agents/canonical.py +73 -0
  45. trueppm_api/apps/agents/deferred.py +108 -0
  46. trueppm_api/apps/agents/management/__init__.py +0 -0
  47. trueppm_api/apps/agents/management/commands/__init__.py +0 -0
  48. trueppm_api/apps/agents/management/commands/audit_prune.py +137 -0
  49. trueppm_api/apps/agents/management/commands/audit_verify.py +101 -0
  50. trueppm_api/apps/agents/middleware.py +44 -0
  51. trueppm_api/apps/agents/migrations/0001_initial.py +231 -0
  52. trueppm_api/apps/agents/migrations/0001_squashed_0003_release_0_4.py +344 -0
  53. trueppm_api/apps/agents/migrations/0002_agentactioncheckpoint.py +71 -0
  54. trueppm_api/apps/agents/migrations/0003_agentactionrefusaldetail.py +58 -0
  55. trueppm_api/apps/agents/migrations/__init__.py +0 -0
  56. trueppm_api/apps/agents/models.py +371 -0
  57. trueppm_api/apps/agents/refusal.py +103 -0
  58. trueppm_api/apps/agents/serializers.py +85 -0
  59. trueppm_api/apps/agents/services.py +397 -0
  60. trueppm_api/apps/agents/signals.py +30 -0
  61. trueppm_api/apps/agents/urls.py +15 -0
  62. trueppm_api/apps/agents/views.py +109 -0
  63. trueppm_api/apps/csvimport/__init__.py +12 -0
  64. trueppm_api/apps/csvimport/apps.py +11 -0
  65. trueppm_api/apps/csvimport/mapping.py +363 -0
  66. trueppm_api/apps/csvimport/migrations/0001_initial.py +74 -0
  67. trueppm_api/apps/csvimport/migrations/0001_squashed_0003_release_0_4.py +90 -0
  68. trueppm_api/apps/csvimport/migrations/0002_schedule_outline_batch_operations.py +37 -0
  69. trueppm_api/apps/csvimport/migrations/0003_csvimportrequest_date_order_and_more.py +26 -0
  70. trueppm_api/apps/csvimport/migrations/__init__.py +0 -0
  71. trueppm_api/apps/csvimport/models.py +111 -0
  72. trueppm_api/apps/csvimport/parser.py +1825 -0
  73. trueppm_api/apps/csvimport/services.py +48 -0
  74. trueppm_api/apps/csvimport/tasks.py +459 -0
  75. trueppm_api/apps/csvimport/template.py +37 -0
  76. trueppm_api/apps/csvimport/urls.py +50 -0
  77. trueppm_api/apps/csvimport/views.py +793 -0
  78. trueppm_api/apps/history/__init__.py +0 -0
  79. trueppm_api/apps/history/apps.py +12 -0
  80. trueppm_api/apps/history/changelog.py +359 -0
  81. trueppm_api/apps/history/diff_policy.py +178 -0
  82. trueppm_api/apps/history/serializers.py +104 -0
  83. trueppm_api/apps/history/signals.py +82 -0
  84. trueppm_api/apps/history/tasks.py +105 -0
  85. trueppm_api/apps/history/urls.py +38 -0
  86. trueppm_api/apps/history/views.py +443 -0
  87. trueppm_api/apps/idempotency/__init__.py +0 -0
  88. trueppm_api/apps/idempotency/apps.py +11 -0
  89. trueppm_api/apps/idempotency/migrations/0001_initial.py +71 -0
  90. trueppm_api/apps/idempotency/migrations/__init__.py +0 -0
  91. trueppm_api/apps/idempotency/mixins.py +226 -0
  92. trueppm_api/apps/idempotency/models.py +75 -0
  93. trueppm_api/apps/idempotency/tasks.py +61 -0
  94. trueppm_api/apps/integrations/__init__.py +13 -0
  95. trueppm_api/apps/integrations/apps.py +59 -0
  96. trueppm_api/apps/integrations/connections.py +806 -0
  97. trueppm_api/apps/integrations/encryption.py +92 -0
  98. trueppm_api/apps/integrations/external_sources.py +863 -0
  99. trueppm_api/apps/integrations/git_automation_services.py +231 -0
  100. trueppm_api/apps/integrations/git_webhook_auth.py +243 -0
  101. trueppm_api/apps/integrations/http.py +597 -0
  102. trueppm_api/apps/integrations/me_work.py +218 -0
  103. trueppm_api/apps/integrations/migrations/0001_initial.py +64 -0
  104. trueppm_api/apps/integrations/migrations/0001_squashed_0006_tasklink_description_tasklink_preview_type_and_more.py +187 -0
  105. trueppm_api/apps/integrations/migrations/0002_tasklink.py +67 -0
  106. trueppm_api/apps/integrations/migrations/0003_tasklink_tasklink_serverver_idx.py +17 -0
  107. trueppm_api/apps/integrations/migrations/0004_tasklink_custom_title_tasklink_labels.py +25 -0
  108. trueppm_api/apps/integrations/migrations/0005_boardautomation.py +56 -0
  109. trueppm_api/apps/integrations/migrations/0006_tasklink_description_tasklink_preview_type_and_more.py +40 -0
  110. trueppm_api/apps/integrations/migrations/0007_squashed_0014_release_0_4.py +225 -0
  111. trueppm_api/apps/integrations/migrations/0007_tasklink_created_at.py +23 -0
  112. trueppm_api/apps/integrations/migrations/0008_integrationcredential_config_externalworkitem.py +66 -0
  113. trueppm_api/apps/integrations/migrations/0009_externalsyncrequest_and_more.py +96 -0
  114. trueppm_api/apps/integrations/migrations/0010_externalworkitem_due_date.py +17 -0
  115. trueppm_api/apps/integrations/migrations/0011_tasklink_sync_seq_tasklink_tasklink_syncseq_idx.py +22 -0
  116. trueppm_api/apps/integrations/migrations/0012_boardautomation_last_delivery_at_and_more.py +42 -0
  117. trueppm_api/apps/integrations/migrations/0013_externalsyncrequest_attempt_count_and_more.py +26 -0
  118. trueppm_api/apps/integrations/migrations/0014_tasklink_created_by.py +27 -0
  119. trueppm_api/apps/integrations/migrations/__init__.py +0 -0
  120. trueppm_api/apps/integrations/models.py +635 -0
  121. trueppm_api/apps/integrations/notification_channels.py +57 -0
  122. trueppm_api/apps/integrations/opengraph.py +229 -0
  123. trueppm_api/apps/integrations/outgoing.py +201 -0
  124. trueppm_api/apps/integrations/providers.py +528 -0
  125. trueppm_api/apps/integrations/registry.py +345 -0
  126. trueppm_api/apps/integrations/serializers.py +453 -0
  127. trueppm_api/apps/integrations/services.py +171 -0
  128. trueppm_api/apps/integrations/tasks.py +734 -0
  129. trueppm_api/apps/integrations/throttles.py +165 -0
  130. trueppm_api/apps/integrations/urls.py +77 -0
  131. trueppm_api/apps/integrations/views.py +1158 -0
  132. trueppm_api/apps/jiraimport/__init__.py +8 -0
  133. trueppm_api/apps/jiraimport/apps.py +11 -0
  134. trueppm_api/apps/jiraimport/migrations/0001_initial.py +72 -0
  135. trueppm_api/apps/jiraimport/migrations/__init__.py +0 -0
  136. trueppm_api/apps/jiraimport/models.py +70 -0
  137. trueppm_api/apps/jiraimport/parser.py +350 -0
  138. trueppm_api/apps/jiraimport/services.py +46 -0
  139. trueppm_api/apps/jiraimport/tasks.py +280 -0
  140. trueppm_api/apps/jiraimport/urls.py +15 -0
  141. trueppm_api/apps/jiraimport/views.py +153 -0
  142. trueppm_api/apps/msproject/__init__.py +0 -0
  143. trueppm_api/apps/msproject/apps.py +11 -0
  144. trueppm_api/apps/msproject/dataclasses.py +153 -0
  145. trueppm_api/apps/msproject/exporter.py +551 -0
  146. trueppm_api/apps/msproject/extended_attributes.py +77 -0
  147. trueppm_api/apps/msproject/importer.py +1095 -0
  148. trueppm_api/apps/msproject/migrations/0001_import_request.py +77 -0
  149. trueppm_api/apps/msproject/migrations/0001_squashed_0002_importrequest_creates_project.py +80 -0
  150. trueppm_api/apps/msproject/migrations/0002_importrequest_creates_project.py +15 -0
  151. trueppm_api/apps/msproject/migrations/__init__.py +0 -0
  152. trueppm_api/apps/msproject/models.py +81 -0
  153. trueppm_api/apps/msproject/parser.py +1276 -0
  154. trueppm_api/apps/msproject/serializers.py +136 -0
  155. trueppm_api/apps/msproject/services.py +58 -0
  156. trueppm_api/apps/msproject/tasks.py +439 -0
  157. trueppm_api/apps/msproject/urls.py +39 -0
  158. trueppm_api/apps/msproject/views.py +531 -0
  159. trueppm_api/apps/notifications/__init__.py +7 -0
  160. trueppm_api/apps/notifications/apps.py +15 -0
  161. trueppm_api/apps/notifications/backfill.py +79 -0
  162. trueppm_api/apps/notifications/categories.py +112 -0
  163. trueppm_api/apps/notifications/delivery_limits.py +258 -0
  164. trueppm_api/apps/notifications/digests.py +462 -0
  165. trueppm_api/apps/notifications/email_backend.py +350 -0
  166. trueppm_api/apps/notifications/email_health.py +128 -0
  167. trueppm_api/apps/notifications/migrations/0001_initial.py +207 -0
  168. trueppm_api/apps/notifications/migrations/0001_squashed_0006_notification_task.py +299 -0
  169. trueppm_api/apps/notifications/migrations/0002_project_notification_preference.py +67 -0
  170. trueppm_api/apps/notifications/migrations/0003_projectnotificationpreference_paused.py +17 -0
  171. trueppm_api/apps/notifications/migrations/0004_clean_unknown_matrix_keys.py +30 -0
  172. trueppm_api/apps/notifications/migrations/0005_notification_body_notification_event_type_and_more.py +27 -0
  173. trueppm_api/apps/notifications/migrations/0006_notification_task.py +25 -0
  174. trueppm_api/apps/notifications/migrations/0007_squashed_0011_release_0_4.py +204 -0
  175. trueppm_api/apps/notifications/migrations/0007_workspaceemailsettings.py +80 -0
  176. trueppm_api/apps/notifications/migrations/0008_notification_snoozed_until.py +17 -0
  177. trueppm_api/apps/notifications/migrations/0009_usernotificationsettings.py +43 -0
  178. trueppm_api/apps/notifications/migrations/0010_projectnotificationpreference_schema_version.py +20 -0
  179. trueppm_api/apps/notifications/migrations/0011_usernotificationsettings_digest_hour_and_more.py +96 -0
  180. trueppm_api/apps/notifications/migrations/__init__.py +0 -0
  181. trueppm_api/apps/notifications/models.py +1148 -0
  182. trueppm_api/apps/notifications/receivers.py +155 -0
  183. trueppm_api/apps/notifications/schema_migrations.py +56 -0
  184. trueppm_api/apps/notifications/serializers.py +1094 -0
  185. trueppm_api/apps/notifications/services.py +1489 -0
  186. trueppm_api/apps/notifications/tasks.py +762 -0
  187. trueppm_api/apps/notifications/throttles.py +98 -0
  188. trueppm_api/apps/notifications/urls.py +97 -0
  189. trueppm_api/apps/notifications/views.py +919 -0
  190. trueppm_api/apps/observability/__init__.py +0 -0
  191. trueppm_api/apps/observability/apps.py +31 -0
  192. trueppm_api/apps/observability/logging.py +213 -0
  193. trueppm_api/apps/observability/migrations/0001_initial.py +35 -0
  194. trueppm_api/apps/observability/migrations/0001_squashed_0003_alter_purgerun_trigger.py +154 -0
  195. trueppm_api/apps/observability/migrations/0002_purgerun_retentionpolicy_retentionschedule.py +131 -0
  196. trueppm_api/apps/observability/migrations/0003_alter_purgerun_trigger.py +21 -0
  197. trueppm_api/apps/observability/migrations/0004_alter_retentionpolicy_key.py +28 -0
  198. trueppm_api/apps/observability/migrations/__init__.py +0 -0
  199. trueppm_api/apps/observability/models.py +141 -0
  200. trueppm_api/apps/observability/otel/__init__.py +45 -0
  201. trueppm_api/apps/observability/otel/attributes.py +247 -0
  202. trueppm_api/apps/observability/otel/export_health.py +533 -0
  203. trueppm_api/apps/observability/otel/instrumentation.py +351 -0
  204. trueppm_api/apps/observability/otel/metrics.py +566 -0
  205. trueppm_api/apps/observability/otel/provider.py +511 -0
  206. trueppm_api/apps/observability/otel/request_attributes.py +204 -0
  207. trueppm_api/apps/observability/purge_registry.py +124 -0
  208. trueppm_api/apps/observability/retention.py +139 -0
  209. trueppm_api/apps/observability/selectors.py +993 -0
  210. trueppm_api/apps/observability/serializers.py +142 -0
  211. trueppm_api/apps/observability/services.py +407 -0
  212. trueppm_api/apps/observability/tasks.py +266 -0
  213. trueppm_api/apps/observability/urls.py +27 -0
  214. trueppm_api/apps/observability/views.py +537 -0
  215. trueppm_api/apps/profiles/__init__.py +0 -0
  216. trueppm_api/apps/profiles/apps.py +15 -0
  217. trueppm_api/apps/profiles/constants.py +54 -0
  218. trueppm_api/apps/profiles/migrations/0001_initial.py +55 -0
  219. trueppm_api/apps/profiles/migrations/0001_squashed_0004_userprofile_role_context.py +125 -0
  220. trueppm_api/apps/profiles/migrations/0002_userprofile_hidden_views.py +17 -0
  221. trueppm_api/apps/profiles/migrations/0003_projectvisit.py +63 -0
  222. trueppm_api/apps/profiles/migrations/0004_userprofile_role_context.py +26 -0
  223. trueppm_api/apps/profiles/migrations/0005_squashed_0009_release_0_4.py +128 -0
  224. trueppm_api/apps/profiles/migrations/0005_userprofile_schedule_in_deliver.py +20 -0
  225. trueppm_api/apps/profiles/migrations/0006_userprofile_date_format_userprofile_timezone.py +36 -0
  226. trueppm_api/apps/profiles/migrations/0007_userpin.py +91 -0
  227. trueppm_api/apps/profiles/migrations/0008_remove_userprofile_schedule_in_deliver.py +71 -0
  228. trueppm_api/apps/profiles/migrations/0009_auth_user_email_upper_idx.py +81 -0
  229. trueppm_api/apps/profiles/migrations/__init__.py +0 -0
  230. trueppm_api/apps/profiles/models.py +276 -0
  231. trueppm_api/apps/profiles/serializers.py +199 -0
  232. trueppm_api/apps/profiles/services.py +541 -0
  233. trueppm_api/apps/profiles/views.py +124 -0
  234. trueppm_api/apps/projects/__init__.py +0 -0
  235. trueppm_api/apps/projects/actual_date_rules.py +163 -0
  236. trueppm_api/apps/projects/amend.py +133 -0
  237. trueppm_api/apps/projects/apps.py +38 -0
  238. trueppm_api/apps/projects/asset_feed.py +459 -0
  239. trueppm_api/apps/projects/asset_views.py +317 -0
  240. trueppm_api/apps/projects/attachment_policy.py +278 -0
  241. trueppm_api/apps/projects/authentication.py +458 -0
  242. trueppm_api/apps/projects/backfill.py +459 -0
  243. trueppm_api/apps/projects/backlog_services.py +324 -0
  244. trueppm_api/apps/projects/backlog_views.py +302 -0
  245. trueppm_api/apps/projects/batch_operation_views.py +264 -0
  246. trueppm_api/apps/projects/blocker_services.py +510 -0
  247. trueppm_api/apps/projects/board_activity.py +462 -0
  248. trueppm_api/apps/projects/board_activity_views.py +186 -0
  249. trueppm_api/apps/projects/board_lanes.py +134 -0
  250. trueppm_api/apps/projects/bulk_settings.py +194 -0
  251. trueppm_api/apps/projects/bundled_templates.py +215 -0
  252. trueppm_api/apps/projects/calendar_settings.py +180 -0
  253. trueppm_api/apps/projects/ceremony_views.py +244 -0
  254. trueppm_api/apps/projects/commit_moment.py +212 -0
  255. trueppm_api/apps/projects/config_notice.py +1330 -0
  256. trueppm_api/apps/projects/custom_field_values.py +266 -0
  257. trueppm_api/apps/projects/decisions_services.py +132 -0
  258. trueppm_api/apps/projects/decisions_views.py +97 -0
  259. trueppm_api/apps/projects/estimation_scale.py +126 -0
  260. trueppm_api/apps/projects/export_bundle.py +423 -0
  261. trueppm_api/apps/projects/fixtures/seeds/atlas-platform-launch.json +4278 -0
  262. trueppm_api/apps/projects/fixtures/seeds/aurora-mobile-app.json +2001 -0
  263. trueppm_api/apps/projects/fixtures/seeds/bayside-civic-center.json +1827 -0
  264. trueppm_api/apps/projects/fixtures/seeds/ga-launch.json +1909 -0
  265. trueppm_api/apps/projects/fixtures/seeds/helios-crm-replacement.json +1410 -0
  266. trueppm_api/apps/projects/guardrail_policy_source.py +269 -0
  267. trueppm_api/apps/projects/inbound_sync.py +555 -0
  268. trueppm_api/apps/projects/iteration_label.py +85 -0
  269. trueppm_api/apps/projects/key_views.py +468 -0
  270. trueppm_api/apps/projects/keys.py +205 -0
  271. trueppm_api/apps/projects/lifecycle.py +191 -0
  272. trueppm_api/apps/projects/management/__init__.py +0 -0
  273. trueppm_api/apps/projects/management/commands/__init__.py +0 -0
  274. trueppm_api/apps/projects/management/commands/backfill_in_progress_status.py +92 -0
  275. trueppm_api/apps/projects/management/commands/create_demo_share_link.py +368 -0
  276. trueppm_api/apps/projects/management/commands/export_program.py +50 -0
  277. trueppm_api/apps/projects/management/commands/import_seed.py +165 -0
  278. trueppm_api/apps/projects/management/commands/load_sample_project.py +514 -0
  279. trueppm_api/apps/projects/management/commands/seed_capacity.py +406 -0
  280. trueppm_api/apps/projects/management/commands/seed_integration_fixtures.py +192 -0
  281. trueppm_api/apps/projects/management/commands/shift_sample_dates.py +120 -0
  282. trueppm_api/apps/projects/mcp_settings.py +305 -0
  283. trueppm_api/apps/projects/methodology.py +178 -0
  284. trueppm_api/apps/projects/migration_helpers.py +75 -0
  285. trueppm_api/apps/projects/migrations/0001_initial.py +208 -0
  286. trueppm_api/apps/projects/migrations/0001_squashed_0094_project_decisions_policy.py +5659 -0
  287. trueppm_api/apps/projects/migrations/0002_alter_uuid_pk_serialize_false.py +57 -0
  288. trueppm_api/apps/projects/migrations/0003_rename_task_project_index.py +25 -0
  289. trueppm_api/apps/projects/migrations/0004_soft_delete_and_dependency_versioned.py +70 -0
  290. trueppm_api/apps/projects/migrations/0005_task_assignee.py +33 -0
  291. trueppm_api/apps/projects/migrations/0006_task_utilization_index.py +31 -0
  292. trueppm_api/apps/projects/migrations/0007_task_is_milestone.py +28 -0
  293. trueppm_api/apps/projects/migrations/0008_baseline.py +119 -0
  294. trueppm_api/apps/projects/migrations/0009_historicaldependency_historicalproject_and_more.py +210 -0
  295. trueppm_api/apps/projects/migrations/0010_risk.py +229 -0
  296. trueppm_api/apps/projects/migrations/0011_task_status.py +27 -0
  297. trueppm_api/apps/projects/migrations/0012_task_status.py +27 -0
  298. trueppm_api/apps/projects/migrations/0013_task_planned_start.py +24 -0
  299. trueppm_api/apps/projects/migrations/0014_short_hex_ids.py +74 -0
  300. trueppm_api/apps/projects/migrations/0015_backfill_short_ids.py +48 -0
  301. trueppm_api/apps/projects/migrations/0016_task_actual_dates.py +42 -0
  302. trueppm_api/apps/projects/migrations/0017_boardcolumnconfig.py +43 -0
  303. trueppm_api/apps/projects/migrations/0018_estimation_governance.py +62 -0
  304. trueppm_api/apps/projects/migrations/0019_backfill_wbs_paths.py +28 -0
  305. trueppm_api/apps/projects/migrations/0020_task_status_5col.py +65 -0
  306. trueppm_api/apps/projects/migrations/0021_boardsavedview.py +64 -0
  307. trueppm_api/apps/projects/migrations/0022_task_status_changed_at_priority_rank.py +35 -0
  308. trueppm_api/apps/projects/migrations/0023_risk_framework_fields.py +96 -0
  309. trueppm_api/apps/projects/migrations/0024_riskcomment.py +52 -0
  310. trueppm_api/apps/projects/migrations/0025_sprint.py +352 -0
  311. trueppm_api/apps/projects/migrations/0026_project_methodology.py +30 -0
  312. trueppm_api/apps/projects/migrations/0027_sprint_retro.py +89 -0
  313. trueppm_api/apps/projects/migrations/0028_normalize_notes_field.py +42 -0
  314. trueppm_api/apps/projects/migrations/0029_complete_implies_full_progress.py +38 -0
  315. trueppm_api/apps/projects/migrations/0030_review_implies_full_progress.py +37 -0
  316. trueppm_api/apps/projects/migrations/0031_task_remaining_points.py +22 -0
  317. trueppm_api/apps/projects/migrations/0032_task_is_subtask_and_sprint_scope_change.py +90 -0
  318. trueppm_api/apps/projects/migrations/0033_task_my_work_index.py +38 -0
  319. trueppm_api/apps/projects/migrations/0034_inbound_task_sync.py +313 -0
  320. trueppm_api/apps/projects/migrations/0035_retro_versioned_and_suggested_assignee.py +173 -0
  321. trueppm_api/apps/projects/migrations/0036_program_entity_and_membership.py +157 -0
  322. trueppm_api/apps/projects/migrations/0037_sprint_capacity_points.py +20 -0
  323. trueppm_api/apps/projects/migrations/0038_taskcomment_commentreaction_commentacknowledgement_and_more.py +233 -0
  324. trueppm_api/apps/projects/migrations/0039_apitoken_and_more.py +88 -0
  325. trueppm_api/apps/projects/migrations/0040_program_general_fields.py +119 -0
  326. trueppm_api/apps/projects/migrations/0041_ceremony_template_and_phase_gate_config.py +210 -0
  327. trueppm_api/apps/projects/migrations/0041_project_general_fields.py +106 -0
  328. trueppm_api/apps/projects/migrations/0042_merge_20260522_0410.py +12 -0
  329. trueppm_api/apps/projects/migrations/0042_program_rollup_config.py +95 -0
  330. trueppm_api/apps/projects/migrations/0042_workflow_color_and_custom_fields.py +94 -0
  331. trueppm_api/apps/projects/migrations/0043_merge_20260522_1118.py +10 -0
  332. trueppm_api/apps/projects/migrations/0044_merge_20260522_rollup.py +10 -0
  333. trueppm_api/apps/projects/migrations/0044_project_archive_program_close.py +119 -0
  334. trueppm_api/apps/projects/migrations/0045_program_risk_policy.py +78 -0
  335. trueppm_api/apps/projects/migrations/0046_merge_20260523_2248.py +12 -0
  336. trueppm_api/apps/projects/migrations/0047_apitokenauditentry_program_and_more.py +55 -0
  337. trueppm_api/apps/projects/migrations/0048_historicalprogram_color_program_color.py +32 -0
  338. trueppm_api/apps/projects/migrations/0049_backlog_item.py +112 -0
  339. trueppm_api/apps/projects/migrations/0050_backlog_item_trgm_search.py +26 -0
  340. trueppm_api/apps/projects/migrations/0051_alter_calendar_working_days_alter_dependency_lag_and_more.py +144 -0
  341. trueppm_api/apps/projects/migrations/0052_recurring_tasks.py +278 -0
  342. trueppm_api/apps/projects/migrations/0053_dependency_dep_pred_serverver_idx_and_more.py +56 -0
  343. trueppm_api/apps/projects/migrations/0054_sprintscopechange_goal_impact_and_more.py +117 -0
  344. trueppm_api/apps/projects/migrations/0055_historicaltask_sprint_pending_and_more.py +51 -0
  345. trueppm_api/apps/projects/migrations/0056_historicalproject_prioritization_model_and_more.py +276 -0
  346. trueppm_api/apps/projects/migrations/0057_historicalsprint_binding_committed_snapshot_and_more.py +58 -0
  347. trueppm_api/apps/projects/migrations/0058_historicaltask_delivery_mode_and_more.py +72 -0
  348. trueppm_api/apps/projects/migrations/0059_forecastsnapshot.py +80 -0
  349. trueppm_api/apps/projects/migrations/0060_historicalprojectsignalprivacypolicy_and_more.py +90 -0
  350. trueppm_api/apps/projects/migrations/0061_baselinetask_story_points.py +17 -0
  351. trueppm_api/apps/projects/migrations/0062_project_is_sample.py +22 -0
  352. trueppm_api/apps/projects/migrations/0063_historicalsprint_wip_limit_sprint_wip_limit.py +22 -0
  353. trueppm_api/apps/projects/migrations/0064_sprinttaskoutcome.py +97 -0
  354. trueppm_api/apps/projects/migrations/0065_historicalsprint_goal_outcome_sprint_goal_outcome.py +32 -0
  355. trueppm_api/apps/projects/migrations/0066_historicalproject_lead_project_lead.py +38 -0
  356. trueppm_api/apps/projects/migrations/0067_sprint_exclude_from_velocity.py +22 -0
  357. trueppm_api/apps/projects/migrations/0068_project_recalculated_at.py +23 -0
  358. trueppm_api/apps/projects/migrations/0069_iteration_label.py +22 -0
  359. trueppm_api/apps/projects/migrations/0070_historicalprogram_iteration_label_and_more.py +32 -0
  360. trueppm_api/apps/projects/migrations/0071_backfill_iteration_label_inherit.py +35 -0
  361. trueppm_api/apps/projects/migrations/0072_pulseresponse_retroboarditem.py +129 -0
  362. trueppm_api/apps/projects/migrations/0073_sprinttaskoutcome_demo_ready.py +17 -0
  363. trueppm_api/apps/projects/migrations/0074_historicaltask_blocked_reason_task_blocked_reason.py +30 -0
  364. trueppm_api/apps/projects/migrations/0075_risk_decimal_short_id.py +42 -0
  365. trueppm_api/apps/projects/migrations/0076_sprinttaskoutcome_review_polish.py +45 -0
  366. trueppm_api/apps/projects/migrations/0077_task_blocker_fields.py +111 -0
  367. trueppm_api/apps/projects/migrations/0078_alter_risktask_unique_together_and_more.py +22 -0
  368. trueppm_api/apps/projects/migrations/0079_historicalproject_status_date_project_status_date.py +22 -0
  369. trueppm_api/apps/projects/migrations/0080_alter_historicaltask_type_alter_task_type.py +46 -0
  370. trueppm_api/apps/projects/migrations/0081_historicalprogram_allow_guests_and_more.py +52 -0
  371. trueppm_api/apps/projects/migrations/0082_project_last_sync_version.py +90 -0
  372. trueppm_api/apps/projects/migrations/0083_historicalprogram_mc_history_attribution_audience_and_more.py +108 -0
  373. trueppm_api/apps/projects/migrations/0084_tasknote.py +71 -0
  374. trueppm_api/apps/projects/migrations/0085_sprint_ix_sprint_velocity.py +33 -0
  375. trueppm_api/apps/projects/migrations/0086_board_card_search_trgm.py +33 -0
  376. trueppm_api/apps/projects/migrations/0087_historicalprogram_task_duration_change_percent_policy_and_more.py +155 -0
  377. trueppm_api/apps/projects/migrations/0088_historicalprogram_allowed_attachment_types_and_more.py +61 -0
  378. trueppm_api/apps/projects/migrations/0089_signalceilingraiseproposal_signalceilingraisevote_and_more.py +157 -0
  379. trueppm_api/apps/projects/migrations/0090_historicaltask_proj_histdate_index.py +59 -0
  380. trueppm_api/apps/projects/migrations/0091_project_board_cadence.py +39 -0
  381. trueppm_api/apps/projects/migrations/0092_program_target_date.py +22 -0
  382. trueppm_api/apps/projects/migrations/0093_cross_project_dependency_consent.py +58 -0
  383. trueppm_api/apps/projects/migrations/0094_project_decisions_policy.py +90 -0
  384. trueppm_api/apps/projects/migrations/0095_poker_session_vote.py +127 -0
  385. trueppm_api/apps/projects/migrations/0095_squashed_0097_release_0_3.py +225 -0
  386. trueppm_api/apps/projects/migrations/0096_crossprojectslipconflict.py +91 -0
  387. trueppm_api/apps/projects/migrations/0097_backlogitem_backlogitem_tags_gin_and_more.py +32 -0
  388. trueppm_api/apps/projects/migrations/0098_historicalproject_show_baselines_and_more.py +52 -0
  389. trueppm_api/apps/projects/migrations/0099_apitoken_scopes.py +48 -0
  390. trueppm_api/apps/projects/migrations/0100_task_dep_serverver_idx_concurrent.py +75 -0
  391. trueppm_api/apps/projects/migrations/0101_dependency_deleted_at_task_deleted_at.py +22 -0
  392. trueppm_api/apps/projects/migrations/0102_project_deleted_at_project_proj_isdel_deletedat_idx.py +25 -0
  393. trueppm_api/apps/projects/migrations/0103_taskdurationchangeevent_task_dur_evt_sprint_idx.py +18 -0
  394. trueppm_api/apps/projects/migrations/0104_historicalproject_stale_task_threshold_days_and_more.py +32 -0
  395. trueppm_api/apps/projects/migrations/0104_trash_restore_1113.py +38 -0
  396. trueppm_api/apps/projects/migrations/0105_historical_changelog_indexes.py +76 -0
  397. trueppm_api/apps/projects/migrations/0106_boardsavedview_schema_version.py +20 -0
  398. trueppm_api/apps/projects/migrations/0106_squashed_0158_release_0_4.py +2357 -0
  399. trueppm_api/apps/projects/migrations/0107_task_activity_event.py +70 -0
  400. trueppm_api/apps/projects/migrations/0108_remove_apitoken_api_token_scope_xor_and_more.py +117 -0
  401. trueppm_api/apps/projects/migrations/0109_projectexportjob.py +82 -0
  402. trueppm_api/apps/projects/migrations/0110_sharelink.py +123 -0
  403. trueppm_api/apps/projects/migrations/0111_projectcalendarlayer.py +67 -0
  404. trueppm_api/apps/projects/migrations/0112_sharelink_expires_at_alter_sharelink_content_kind.py +31 -0
  405. trueppm_api/apps/projects/migrations/0113_alter_historicaltask_percent_complete_and_more.py +35 -0
  406. trueppm_api/apps/projects/migrations/0114_historicalproject_default_member_role_and_more.py +28 -0
  407. trueppm_api/apps/projects/migrations/0115_historicalproject_end_date_shift_threshold_days_and_more.py +22 -0
  408. trueppm_api/apps/projects/migrations/0116_alter_taskactivityevent_event_type.py +28 -0
  409. trueppm_api/apps/projects/migrations/0117_label_tasklabel_label_tasks_and_more.py +126 -0
  410. trueppm_api/apps/projects/migrations/0118_programexportjob.py +82 -0
  411. trueppm_api/apps/projects/migrations/0119_historicalprogram_calendar_program_calendar.py +36 -0
  412. trueppm_api/apps/projects/migrations/0120_alter_backlogitem_item_type.py +29 -0
  413. trueppm_api/apps/projects/migrations/0121_task_three_point_estimate_ordered.py +64 -0
  414. trueppm_api/apps/projects/migrations/0122_task_relation.py +173 -0
  415. trueppm_api/apps/projects/migrations/0123_remove_historicalproject_agile_features_and_more.py +20 -0
  416. trueppm_api/apps/projects/migrations/0124_dependency_is_driving.py +17 -0
  417. trueppm_api/apps/projects/migrations/0125_historicalprogram_estimation_scale_and_more.py +68 -0
  418. trueppm_api/apps/projects/migrations/0126_projectcustomfield_show_on_card_taskcustomfieldvalue.py +80 -0
  419. trueppm_api/apps/projects/migrations/0127_historicalprogram_mcp_enabled_and_more.py +32 -0
  420. trueppm_api/apps/projects/migrations/0128_acceptancecriterion_sync_seq_apitoken_sync_seq_and_more.py +192 -0
  421. trueppm_api/apps/projects/migrations/0129_sharelink_show_milestone_dates.py +20 -0
  422. trueppm_api/apps/projects/migrations/0130_programimportjob.py +85 -0
  423. trueppm_api/apps/projects/migrations/0131_historicalprogram_sprint_picker_ready_only_default_and_more.py +32 -0
  424. trueppm_api/apps/projects/migrations/0132_task_scheduled_start.py +17 -0
  425. trueppm_api/apps/projects/migrations/0133_project_status_date_floor_armed_at.py +17 -0
  426. trueppm_api/apps/projects/migrations/0134_task_edited_at_task_seeded_at_task_source_id_and_more.py +65 -0
  427. trueppm_api/apps/projects/migrations/0135_projecttemplate_templateapplication_and_more.py +175 -0
  428. trueppm_api/apps/projects/migrations/0136_schedule_outline_batch_operations.py +118 -0
  429. trueppm_api/apps/projects/migrations/0137_collapse_dual_scope_api_tokens.py +54 -0
  430. trueppm_api/apps/projects/migrations/0138_apitokenauditentry_api_token_audit_owner_idx.py +18 -0
  431. trueppm_api/apps/projects/migrations/0139_historicaltask_duration_unit_task_duration_unit.py +32 -0
  432. trueppm_api/apps/projects/migrations/0140_historicaltask_auto_container_and_more.py +113 -0
  433. trueppm_api/apps/projects/migrations/0141_historicalproject_draft_started_at_and_more.py +44 -0
  434. trueppm_api/apps/projects/migrations/0142_baseline_calendar_hours_per_day_and_more.py +31 -0
  435. trueppm_api/apps/projects/migrations/0143_sprintcloserequest_failure_reason_and_more.py +42 -0
  436. trueppm_api/apps/projects/migrations/0144_projecttemplate_source_project_and_more.py +35 -0
  437. trueppm_api/apps/projects/migrations/0145_seed_bundled_templates.py +65 -0
  438. trueppm_api/apps/projects/migrations/0146_historicaltask_board_lane_task_board_lane.py +32 -0
  439. trueppm_api/apps/projects/migrations/0147_structuraloperation.py +128 -0
  440. trueppm_api/apps/projects/migrations/0148_task_unique_task_wbs_path_per_project_live.py +76 -0
  441. trueppm_api/apps/projects/migrations/0149_drop_workshops_tables.py +42 -0
  442. trueppm_api/apps/projects/migrations/0150_clear_uncommitted_cpm_output.py +130 -0
  443. trueppm_api/apps/projects/migrations/0151_config_notice_request.py +70 -0
  444. trueppm_api/apps/projects/migrations/0152_aggregate_task_wbs_name_idx.py +20 -0
  445. trueppm_api/apps/projects/migrations/0153_program_sample_anchor_date.py +22 -0
  446. trueppm_api/apps/projects/migrations/0154_object_keys.py +184 -0
  447. trueppm_api/apps/projects/migrations/0155_task_milestone_at_day_end.py +20 -0
  448. trueppm_api/apps/projects/migrations/0156_program_import_job_replaced_project_ids.py +17 -0
  449. trueppm_api/apps/projects/migrations/0157_forecastsnapshot_cpm_finish_at_day_start.py +17 -0
  450. trueppm_api/apps/projects/migrations/0158_baselinetask_finish_at_day_start.py +17 -0
  451. trueppm_api/apps/projects/migrations/__init__.py +0 -0
  452. trueppm_api/apps/projects/models.py +9209 -0
  453. trueppm_api/apps/projects/poker_services.py +154 -0
  454. trueppm_api/apps/projects/poker_views.py +398 -0
  455. trueppm_api/apps/projects/product_backlog_services.py +450 -0
  456. trueppm_api/apps/projects/program_label_services.py +94 -0
  457. trueppm_api/apps/projects/program_label_views.py +189 -0
  458. trueppm_api/apps/projects/program_rollup.py +903 -0
  459. trueppm_api/apps/projects/program_schedule.py +767 -0
  460. trueppm_api/apps/projects/program_views.py +3445 -0
  461. trueppm_api/apps/projects/project_templates.py +422 -0
  462. trueppm_api/apps/projects/receivers.py +234 -0
  463. trueppm_api/apps/projects/refusal_codes.py +140 -0
  464. trueppm_api/apps/projects/reorder_services.py +145 -0
  465. trueppm_api/apps/projects/restructure_hooks.py +54 -0
  466. trueppm_api/apps/projects/retro_board_services.py +368 -0
  467. trueppm_api/apps/projects/retro_services.py +285 -0
  468. trueppm_api/apps/projects/risk_import.py +396 -0
  469. trueppm_api/apps/projects/row_identity.py +113 -0
  470. trueppm_api/apps/projects/schema_migrations.py +228 -0
  471. trueppm_api/apps/projects/schemas/seed_v1.json +492 -0
  472. trueppm_api/apps/projects/schemas/seed_v2.json +891 -0
  473. trueppm_api/apps/projects/seed/__init__.py +61 -0
  474. trueppm_api/apps/projects/seed/demo_landing_overlay.py +532 -0
  475. trueppm_api/apps/projects/seed/exporter.py +1717 -0
  476. trueppm_api/apps/projects/seed/forecast_backfill.py +247 -0
  477. trueppm_api/apps/projects/seed/importer.py +2764 -0
  478. trueppm_api/apps/projects/seed/reanchor.py +551 -0
  479. trueppm_api/apps/projects/seed/reldates.py +126 -0
  480. trueppm_api/apps/projects/seed/replace.py +128 -0
  481. trueppm_api/apps/projects/seed/replay.py +1695 -0
  482. trueppm_api/apps/projects/seed/replay_ctx.py +41 -0
  483. trueppm_api/apps/projects/seed/samples.py +427 -0
  484. trueppm_api/apps/projects/seed/validation.py +1169 -0
  485. trueppm_api/apps/projects/serializers.py +12904 -0
  486. trueppm_api/apps/projects/services.py +7525 -0
  487. trueppm_api/apps/projects/share_serializers.py +142 -0
  488. trueppm_api/apps/projects/share_services.py +373 -0
  489. trueppm_api/apps/projects/share_views.py +395 -0
  490. trueppm_api/apps/projects/sharing_settings.py +187 -0
  491. trueppm_api/apps/projects/signal_privacy_services.py +910 -0
  492. trueppm_api/apps/projects/signal_privacy_views.py +485 -0
  493. trueppm_api/apps/projects/signals.py +132 -0
  494. trueppm_api/apps/projects/slip_conflict.py +288 -0
  495. trueppm_api/apps/projects/sprint_cadence.py +453 -0
  496. trueppm_api/apps/projects/sprint_picker_settings.py +132 -0
  497. trueppm_api/apps/projects/standup.py +304 -0
  498. trueppm_api/apps/projects/standup_views.py +99 -0
  499. trueppm_api/apps/projects/structural_operation_services.py +727 -0
  500. trueppm_api/apps/projects/structural_operation_views.py +311 -0
  501. trueppm_api/apps/projects/surface_visibility.py +126 -0
  502. trueppm_api/apps/projects/task_batch_services.py +379 -0
  503. trueppm_api/apps/projects/task_bulk.py +1244 -0
  504. trueppm_api/apps/projects/task_classification.py +561 -0
  505. trueppm_api/apps/projects/task_classification_defaults.py +95 -0
  506. trueppm_api/apps/projects/task_duration_settings.py +142 -0
  507. trueppm_api/apps/projects/task_grouping.py +754 -0
  508. trueppm_api/apps/projects/tasks.py +1979 -0
  509. trueppm_api/apps/projects/template_divergence.py +168 -0
  510. trueppm_api/apps/projects/template_services.py +160 -0
  511. trueppm_api/apps/projects/template_tasks.py +261 -0
  512. trueppm_api/apps/projects/template_views.py +829 -0
  513. trueppm_api/apps/projects/throttles.py +311 -0
  514. trueppm_api/apps/projects/urls.py +1016 -0
  515. trueppm_api/apps/projects/utilization.py +909 -0
  516. trueppm_api/apps/projects/views.py +21225 -0
  517. trueppm_api/apps/projects/wbs_paths.py +119 -0
  518. trueppm_api/apps/resources/__init__.py +0 -0
  519. trueppm_api/apps/resources/apps.py +8 -0
  520. trueppm_api/apps/resources/capacity.py +121 -0
  521. trueppm_api/apps/resources/migrations/0001_initial.py +68 -0
  522. trueppm_api/apps/resources/migrations/0001_squashed_0013_alter_projectresource_unique_together_and_more.py +281 -0
  523. trueppm_api/apps/resources/migrations/0002_alter_uuid_pk_serialize_false.py +36 -0
  524. trueppm_api/apps/resources/migrations/0003_resource_soft_delete.py +30 -0
  525. trueppm_api/apps/resources/migrations/0004_add_taskresource_resource_index.py +25 -0
  526. trueppm_api/apps/resources/migrations/0005_resource_job_role.py +20 -0
  527. trueppm_api/apps/resources/migrations/0006_skill.py +34 -0
  528. trueppm_api/apps/resources/migrations/0007_resource_skill.py +63 -0
  529. trueppm_api/apps/resources/migrations/0008_project_resource.py +63 -0
  530. trueppm_api/apps/resources/migrations/0009_task_skill_requirement.py +60 -0
  531. trueppm_api/apps/resources/migrations/0010_alter_resourceskill_options_and_more.py +20 -0
  532. trueppm_api/apps/resources/migrations/0011_alter_projectresource_notes.py +17 -0
  533. trueppm_api/apps/resources/migrations/0012_add_resource_user_fk.py +26 -0
  534. trueppm_api/apps/resources/migrations/0013_alter_projectresource_unique_together_and_more.py +53 -0
  535. trueppm_api/apps/resources/migrations/0014_projectresource_sync_seq_resource_sync_seq_and_more.py +37 -0
  536. trueppm_api/apps/resources/migrations/0014_squashed_0015_release_0_4.py +47 -0
  537. trueppm_api/apps/resources/migrations/0015_projectresource_deactivated_with_resource.py +17 -0
  538. trueppm_api/apps/resources/migrations/__init__.py +0 -0
  539. trueppm_api/apps/resources/models.py +298 -0
  540. trueppm_api/apps/resources/serializers.py +426 -0
  541. trueppm_api/apps/resources/services.py +465 -0
  542. trueppm_api/apps/resources/urls.py +28 -0
  543. trueppm_api/apps/resources/views.py +1752 -0
  544. trueppm_api/apps/scheduling/__init__.py +0 -0
  545. trueppm_api/apps/scheduling/apps.py +153 -0
  546. trueppm_api/apps/scheduling/calendars.py +144 -0
  547. trueppm_api/apps/scheduling/deadletter.py +91 -0
  548. trueppm_api/apps/scheduling/finish_reading.py +198 -0
  549. trueppm_api/apps/scheduling/forecast_history_settings.py +215 -0
  550. trueppm_api/apps/scheduling/forecast_staleness.py +313 -0
  551. trueppm_api/apps/scheduling/graph_guard.py +263 -0
  552. trueppm_api/apps/scheduling/management/__init__.py +0 -0
  553. trueppm_api/apps/scheduling/management/commands/__init__.py +0 -0
  554. trueppm_api/apps/scheduling/management/commands/prune_forecast_snapshots.py +53 -0
  555. trueppm_api/apps/scheduling/mc_admission.py +181 -0
  556. trueppm_api/apps/scheduling/migrations/0001_failed_task.py +62 -0
  557. trueppm_api/apps/scheduling/migrations/0001_squashed_0007_projectforecastsnapshot.py +309 -0
  558. trueppm_api/apps/scheduling/migrations/0002_schedulerequest.py +78 -0
  559. trueppm_api/apps/scheduling/migrations/0003_add_schedule_request_reason.py +27 -0
  560. trueppm_api/apps/scheduling/migrations/0004_velocity_suggestion.py +94 -0
  561. trueppm_api/apps/scheduling/migrations/0005_montecarlorun.py +61 -0
  562. trueppm_api/apps/scheduling/migrations/0006_montecarlorun_distribution.py +17 -0
  563. trueppm_api/apps/scheduling/migrations/0007_projectforecastsnapshot.py +65 -0
  564. trueppm_api/apps/scheduling/migrations/0008_alter_schedulerequest_reason.py +28 -0
  565. trueppm_api/apps/scheduling/migrations/0008_folded_schedulerequest_reason.py +34 -0
  566. trueppm_api/apps/scheduling/migrations/0009_alter_schedulerequest_reason.py +29 -0
  567. trueppm_api/apps/scheduling/migrations/0010_failedtask_resolution_note_failedtask_resolved_at_and_more.py +43 -0
  568. trueppm_api/apps/scheduling/migrations/0010_squashed_0016_release_0_4.py +106 -0
  569. trueppm_api/apps/scheduling/migrations/0011_failedtask_project.py +26 -0
  570. trueppm_api/apps/scheduling/migrations/0012_montecarlorun_diagnostic.py +17 -0
  571. trueppm_api/apps/scheduling/migrations/0013_montecarlorun_status_date.py +17 -0
  572. trueppm_api/apps/scheduling/migrations/0014_montecarlorun_plan_version.py +17 -0
  573. trueppm_api/apps/scheduling/migrations/0015_projectforecastsnapshot_cpm_finish_at_day_start.py +17 -0
  574. trueppm_api/apps/scheduling/migrations/0016_montecarlorun_finish_readings.py +32 -0
  575. trueppm_api/apps/scheduling/migrations/__init__.py +0 -0
  576. trueppm_api/apps/scheduling/models.py +542 -0
  577. trueppm_api/apps/scheduling/receivers.py +160 -0
  578. trueppm_api/apps/scheduling/risk_premium.py +334 -0
  579. trueppm_api/apps/scheduling/serializers.py +723 -0
  580. trueppm_api/apps/scheduling/services.py +1251 -0
  581. trueppm_api/apps/scheduling/signals.py +56 -0
  582. trueppm_api/apps/scheduling/tasks.py +2248 -0
  583. trueppm_api/apps/scheduling/telemetry.py +80 -0
  584. trueppm_api/apps/scheduling/units.py +35 -0
  585. trueppm_api/apps/scheduling/urls.py +57 -0
  586. trueppm_api/apps/scheduling/views.py +2908 -0
  587. trueppm_api/apps/sso/__init__.py +0 -0
  588. trueppm_api/apps/sso/apps.py +19 -0
  589. trueppm_api/apps/sso/extensions.py +130 -0
  590. trueppm_api/apps/sso/management/__init__.py +0 -0
  591. trueppm_api/apps/sso/management/commands/__init__.py +0 -0
  592. trueppm_api/apps/sso/management/commands/seed_sso_keycloak.py +172 -0
  593. trueppm_api/apps/sso/migrations/0001_initial.py +119 -0
  594. trueppm_api/apps/sso/migrations/0002_remove_oidcprovider_workspace_ssoproviderpolicy_and_more.py +169 -0
  595. trueppm_api/apps/sso/migrations/__init__.py +0 -0
  596. trueppm_api/apps/sso/models.py +148 -0
  597. trueppm_api/apps/sso/serializers.py +446 -0
  598. trueppm_api/apps/sso/services.py +1473 -0
  599. trueppm_api/apps/sso/urls.py +47 -0
  600. trueppm_api/apps/sso/views.py +935 -0
  601. trueppm_api/apps/sync/__init__.py +0 -0
  602. trueppm_api/apps/sync/apps.py +15 -0
  603. trueppm_api/apps/sync/backfill.py +208 -0
  604. trueppm_api/apps/sync/broadcast.py +369 -0
  605. trueppm_api/apps/sync/conflict.py +262 -0
  606. trueppm_api/apps/sync/consumers.py +548 -0
  607. trueppm_api/apps/sync/migrations/0001_initial.py +59 -0
  608. trueppm_api/apps/sync/migrations/0001_squashed_0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +77 -0
  609. trueppm_api/apps/sync/migrations/0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +41 -0
  610. trueppm_api/apps/sync/migrations/0003_boardevent.py +46 -0
  611. trueppm_api/apps/sync/migrations/0003_squashed_0005_release_0_4.py +77 -0
  612. trueppm_api/apps/sync/migrations/0004_seed_sync_seq.py +24 -0
  613. trueppm_api/apps/sync/migrations/0005_program_sync_sequence.py +35 -0
  614. trueppm_api/apps/sync/migrations/0006_boardevent_per_project_seq.py +77 -0
  615. trueppm_api/apps/sync/migrations/__init__.py +0 -0
  616. trueppm_api/apps/sync/models.py +272 -0
  617. trueppm_api/apps/sync/pagination.py +231 -0
  618. trueppm_api/apps/sync/sequence.py +488 -0
  619. trueppm_api/apps/sync/serializers.py +688 -0
  620. trueppm_api/apps/sync/tasks.py +260 -0
  621. trueppm_api/apps/sync/throttles.py +175 -0
  622. trueppm_api/apps/sync/upload.py +556 -0
  623. trueppm_api/apps/sync/urls.py +17 -0
  624. trueppm_api/apps/sync/views.py +957 -0
  625. trueppm_api/apps/sync/ws_auth.py +193 -0
  626. trueppm_api/apps/taskruns/__init__.py +0 -0
  627. trueppm_api/apps/taskruns/apps.py +11 -0
  628. trueppm_api/apps/taskruns/migrations/0001_initial.py +92 -0
  629. trueppm_api/apps/taskruns/migrations/__init__.py +0 -0
  630. trueppm_api/apps/taskruns/models.py +68 -0
  631. trueppm_api/apps/taskruns/serializers.py +92 -0
  632. trueppm_api/apps/taskruns/tasks.py +60 -0
  633. trueppm_api/apps/taskruns/tracker.py +286 -0
  634. trueppm_api/apps/taskruns/urls.py +46 -0
  635. trueppm_api/apps/taskruns/views.py +195 -0
  636. trueppm_api/apps/teams/__init__.py +8 -0
  637. trueppm_api/apps/teams/apps.py +16 -0
  638. trueppm_api/apps/teams/migrations/0001_initial.py +139 -0
  639. trueppm_api/apps/teams/migrations/0001_squashed_0002_default_teams.py +159 -0
  640. trueppm_api/apps/teams/migrations/0002_default_teams.py +62 -0
  641. trueppm_api/apps/teams/migrations/0003_team_sync_seq_teammembership_sync_seq.py +22 -0
  642. trueppm_api/apps/teams/migrations/0004_backfill_default_teams_on_upgrade.py +49 -0
  643. trueppm_api/apps/teams/migrations/__init__.py +0 -0
  644. trueppm_api/apps/teams/models.py +145 -0
  645. trueppm_api/apps/teams/permissions.py +149 -0
  646. trueppm_api/apps/teams/serializers.py +95 -0
  647. trueppm_api/apps/teams/services.py +440 -0
  648. trueppm_api/apps/teams/signals.py +61 -0
  649. trueppm_api/apps/teams/urls.py +34 -0
  650. trueppm_api/apps/teams/views.py +201 -0
  651. trueppm_api/apps/timetracking/__init__.py +0 -0
  652. trueppm_api/apps/timetracking/apps.py +9 -0
  653. trueppm_api/apps/timetracking/migrations/0001_initial.py +117 -0
  654. trueppm_api/apps/timetracking/migrations/0001_squashed_0004_release_0_4.py +167 -0
  655. trueppm_api/apps/timetracking/migrations/0002_timesheetsubmission.py +46 -0
  656. trueppm_api/apps/timetracking/migrations/0003_timeentry_deleted_at_timeentry_deleted_by.py +31 -0
  657. trueppm_api/apps/timetracking/migrations/0004_timeentry_sync_seq_and_more.py +24 -0
  658. trueppm_api/apps/timetracking/migrations/__init__.py +0 -0
  659. trueppm_api/apps/timetracking/models.py +178 -0
  660. trueppm_api/apps/timetracking/serializers.py +175 -0
  661. trueppm_api/apps/timetracking/services.py +211 -0
  662. trueppm_api/apps/timetracking/urls.py +47 -0
  663. trueppm_api/apps/timetracking/views.py +597 -0
  664. trueppm_api/apps/webhooks/__init__.py +0 -0
  665. trueppm_api/apps/webhooks/apps.py +8 -0
  666. trueppm_api/apps/webhooks/backfill.py +90 -0
  667. trueppm_api/apps/webhooks/dispatch.py +279 -0
  668. trueppm_api/apps/webhooks/migrations/0001_initial.py +146 -0
  669. trueppm_api/apps/webhooks/migrations/0001_squashed_0007_sprint_lifecycle_events.py +249 -0
  670. trueppm_api/apps/webhooks/migrations/0002_alter_webhook_events.py +32 -0
  671. trueppm_api/apps/webhooks/migrations/0003_delivery_status_created_idx.py +17 -0
  672. trueppm_api/apps/webhooks/migrations/0004_webhook_program_alter_webhook_project_and_more.py +64 -0
  673. trueppm_api/apps/webhooks/migrations/0005_webhook_delivery_sequence_numbers.py +30 -0
  674. trueppm_api/apps/webhooks/migrations/0006_webhook_format_alter_webhook_events_and_more.py +61 -0
  675. trueppm_api/apps/webhooks/migrations/0007_sprint_lifecycle_events.py +63 -0
  676. trueppm_api/apps/webhooks/migrations/0008_risk_baseline_comment_events.py +73 -0
  677. trueppm_api/apps/webhooks/migrations/0009_encrypt_webhook_secret_and_failure_counters.py +100 -0
  678. trueppm_api/apps/webhooks/migrations/0010_alter_webhook_disabled_at.py +21 -0
  679. trueppm_api/apps/webhooks/migrations/0011_webhookeditor.py +48 -0
  680. trueppm_api/apps/webhooks/migrations/0012_alter_webhook_disabled_at.py +21 -0
  681. trueppm_api/apps/webhooks/migrations/__init__.py +0 -0
  682. trueppm_api/apps/webhooks/models.py +437 -0
  683. trueppm_api/apps/webhooks/serializers.py +326 -0
  684. trueppm_api/apps/webhooks/tasks.py +680 -0
  685. trueppm_api/apps/webhooks/urls.py +22 -0
  686. trueppm_api/apps/webhooks/views.py +533 -0
  687. trueppm_api/apps/workflow_engine/__init__.py +0 -0
  688. trueppm_api/apps/workflow_engine/apps.py +23 -0
  689. trueppm_api/apps/workflow_engine/migrations/0001_initial.py +230 -0
  690. trueppm_api/apps/workflow_engine/migrations/0001_squashed_0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +234 -0
  691. trueppm_api/apps/workflow_engine/migrations/0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +16 -0
  692. trueppm_api/apps/workflow_engine/migrations/0003_workflowoutboxrow_workflow_outbox_recovery_idx.py +21 -0
  693. trueppm_api/apps/workflow_engine/migrations/__init__.py +0 -0
  694. trueppm_api/apps/workflow_engine/models.py +265 -0
  695. trueppm_api/apps/workflow_engine/tasks.py +371 -0
  696. trueppm_api/apps/workspace/__init__.py +0 -0
  697. trueppm_api/apps/workspace/apps.py +10 -0
  698. trueppm_api/apps/workspace/backfill.py +111 -0
  699. trueppm_api/apps/workspace/export.py +254 -0
  700. trueppm_api/apps/workspace/migrations/0001_initial.py +326 -0
  701. trueppm_api/apps/workspace/migrations/0001_squashed_0014_workspacemembership_availability_effective_from_and_more.py +829 -0
  702. trueppm_api/apps/workspace/migrations/0002_remove_workspace_fiscal_year_start_and_more.py +85 -0
  703. trueppm_api/apps/workspace/migrations/0003_workspaceexportjob.py +73 -0
  704. trueppm_api/apps/workspace/migrations/0004_alter_workspaceinvite_status.py +27 -0
  705. trueppm_api/apps/workspace/migrations/0005_workspace_iteration_label_and_more.py +26 -0
  706. trueppm_api/apps/workspace/migrations/0006_alter_groupmembership_unique_together_and_more.py +45 -0
  707. trueppm_api/apps/workspace/migrations/0007_workspace_public_sharing_override_policy.py +21 -0
  708. trueppm_api/apps/workspace/migrations/0008_workspace_mc_history_attribution_audience_and_more.py +44 -0
  709. trueppm_api/apps/workspace/migrations/0009_workspace_methodology_and_more.py +186 -0
  710. trueppm_api/apps/workspace/migrations/0010_workspace_logo.py +38 -0
  711. trueppm_api/apps/workspace/migrations/0011_historicalworkspace_task_duration_change_percent_override_policy_and_more.py +56 -0
  712. trueppm_api/apps/workspace/migrations/0012_historicalworkspace_allowed_attachment_types_and_more.py +64 -0
  713. trueppm_api/apps/workspace/migrations/0013_auditevent.py +70 -0
  714. trueppm_api/apps/workspace/migrations/0014_workspacemembership_availability_effective_from_and_more.py +39 -0
  715. trueppm_api/apps/workspace/migrations/0015_squashed_0027_release_0_4.py +199 -0
  716. trueppm_api/apps/workspace/migrations/0015_trash_restore_1113.py +34 -0
  717. trueppm_api/apps/workspace/migrations/0016_historicalworkspace_calendar_and_more.py +55 -0
  718. trueppm_api/apps/workspace/migrations/0017_historicalworkspace_estimation_scale_and_more.py +38 -0
  719. trueppm_api/apps/workspace/migrations/0018_historicalworkspace_feedback_enabled_and_more.py +32 -0
  720. trueppm_api/apps/workspace/migrations/0019_historicalworkspace_mcp_enabled_and_more.py +22 -0
  721. trueppm_api/apps/workspace/migrations/0020_viewer_ordinal_one.py +34 -0
  722. trueppm_api/apps/workspace/migrations/0021_group_sync_seq_groupmembership_sync_seq_and_more.py +27 -0
  723. trueppm_api/apps/workspace/migrations/0022_historicalworkspace_sprint_picker_ready_only_default_and_more.py +22 -0
  724. trueppm_api/apps/workspace/migrations/0023_alter_auditevent_event_type.py +32 -0
  725. trueppm_api/apps/workspace/migrations/0024_alter_auditevent_event_type.py +33 -0
  726. trueppm_api/apps/workspace/migrations/0025_alter_auditevent_event_type.py +36 -0
  727. trueppm_api/apps/workspace/migrations/0026_alter_auditevent_event_type.py +37 -0
  728. trueppm_api/apps/workspace/migrations/0027_alter_auditevent_event_type.py +42 -0
  729. trueppm_api/apps/workspace/migrations/__init__.py +0 -0
  730. trueppm_api/apps/workspace/models.py +857 -0
  731. trueppm_api/apps/workspace/permissions.py +187 -0
  732. trueppm_api/apps/workspace/serializers.py +590 -0
  733. trueppm_api/apps/workspace/services.py +967 -0
  734. trueppm_api/apps/workspace/signals.py +37 -0
  735. trueppm_api/apps/workspace/tasks.py +616 -0
  736. trueppm_api/apps/workspace/urls.py +113 -0
  737. trueppm_api/apps/workspace/views.py +1581 -0
  738. trueppm_api/asgi.py +49 -0
  739. trueppm_api/celery.py +40 -0
  740. trueppm_api/core/__init__.py +0 -0
  741. trueppm_api/core/admin_site.py +206 -0
  742. trueppm_api/core/auth_views.py +934 -0
  743. trueppm_api/core/constant_time.py +51 -0
  744. trueppm_api/core/csp.py +54 -0
  745. trueppm_api/core/db.py +87 -0
  746. trueppm_api/core/db_session.py +37 -0
  747. trueppm_api/core/demo_read_only.py +314 -0
  748. trueppm_api/core/exception_handlers.py +157 -0
  749. trueppm_api/core/export_downloads.py +56 -0
  750. trueppm_api/core/extension_providers.py +56 -0
  751. trueppm_api/core/extension_signals.py +147 -0
  752. trueppm_api/core/idempotent.py +260 -0
  753. trueppm_api/core/metadata.py +42 -0
  754. trueppm_api/core/middleware.py +51 -0
  755. trueppm_api/core/openapi.py +1221 -0
  756. trueppm_api/core/password_reset.py +513 -0
  757. trueppm_api/core/protect_conflict.py +100 -0
  758. trueppm_api/core/ratelimit.py +148 -0
  759. trueppm_api/core/redis_throttle.py +82 -0
  760. trueppm_api/core/refresh_cookie_policy.py +156 -0
  761. trueppm_api/core/request_body.py +86 -0
  762. trueppm_api/core/security_checks.py +1034 -0
  763. trueppm_api/core/storage_config.py +105 -0
  764. trueppm_api/core/text_decode.py +168 -0
  765. trueppm_api/core/throttling.py +514 -0
  766. trueppm_api/core/valkey.py +214 -0
  767. trueppm_api/core/valkey_cache.py +66 -0
  768. trueppm_api/core/valkey_checks.py +104 -0
  769. trueppm_api/core/valkey_config.py +39 -0
  770. trueppm_api/core/worker_broker_wait.py +149 -0
  771. trueppm_api/core/worker_heartbeat.py +134 -0
  772. trueppm_api/core/worker_selfheal.py +205 -0
  773. trueppm_api/fields.py +36 -0
  774. trueppm_api/permissions.py +30 -0
  775. trueppm_api/py.typed +0 -0
  776. trueppm_api/routing.py +11 -0
  777. trueppm_api/settings/__init__.py +0 -0
  778. trueppm_api/settings/base.py +2605 -0
  779. trueppm_api/settings/dev.py +296 -0
  780. trueppm_api/settings/prod.py +265 -0
  781. trueppm_api/urls.py +217 -0
  782. trueppm_api/workflows/__init__.py +38 -0
  783. trueppm_api/workflows/backends/__init__.py +6 -0
  784. trueppm_api/workflows/backends/default.py +297 -0
  785. trueppm_api/workflows/consumers/__init__.py +11 -0
  786. trueppm_api/workflows/consumers/requeue_failed_task.py +65 -0
  787. trueppm_api/workflows/interface.py +148 -0
  788. trueppm_api/workflows/registry.py +106 -0
  789. trueppm_api/workflows/services.py +90 -0
  790. trueppm_api/wsgi.py +11 -0
  791. trueppm_api-0.4.0.dist-info/METADATA +273 -0
  792. trueppm_api-0.4.0.dist-info/RECORD +799 -0
  793. trueppm_api-0.4.0.dist-info/WHEEL +4 -0
  794. trueppm_api-0.4.0.dist-info/licenses/LICENSE +201 -0
  795. trueppm_api-0.4.0.dist-info/licenses/NOTICE +7 -0
  796. trueppm_api-0.4.0.dist-info/licenses/NOTICES +104 -0
  797. trueppm_api-0.4.0.dist-info/licenses/licenses/GPL-3.0.txt +674 -0
  798. trueppm_api-0.4.0.dist-info/licenses/licenses/LGPL-3.0.txt +165 -0
  799. trueppm_api-0.4.0.dist-info/licenses/licenses/MPL-2.0.txt +373 -0
@@ -0,0 +1,1979 @@
1
+ """Celery tasks for the projects app — sprint close drain + burndown beat.
2
+
3
+ The transactional outbox pattern from ``apps/scheduling`` is mirrored here
4
+ for sprint close: the API endpoint inserts a ``SprintCloseRequest`` row in
5
+ the same DB transaction as the state change and returns 202 Accepted; this
6
+ drain task picks up PENDING rows and applies the actual close transition
7
+ under ``select_for_update`` (so concurrent drains never double-close).
8
+
9
+ See ADR-0037 for the full spec.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from datetime import timedelta
16
+ from typing import Any
17
+
18
+ from celery import shared_task
19
+ from celery.exceptions import SoftTimeLimitExceeded
20
+ from django.db import transaction
21
+ from django.utils import timezone
22
+
23
+ from trueppm_api.core.idempotent import idempotent_task
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ EXPORT_MAX_RETRIES = 3 # ADR-0219 §Durable Execution item 8
28
+ EXPORT_ORPHAN_WINDOW_MINUTES = 5 # ADR-0219 §Durable Execution item 3
29
+ EXPORT_DRAIN_BATCH_SIZE = 10
30
+ DEFAULT_EXPORT_RETENTION_DAYS = 7 # ADR-0219 §Durable Execution item 6 (shared with ADR-0174)
31
+
32
+ # Rows one purge run may reap, shared by the export and import purges (#2615).
33
+ # Sized so a full batch of storage DELETE round-trips finishes well inside the
34
+ # 55 s soft limit those tasks carry; a larger backlog drains over several runs.
35
+ PURGE_BATCH_SIZE = 500
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Config-change notices — outbox worker, drain, purge (#3009, ADR-1174)
40
+ # ---------------------------------------------------------------------------
41
+
42
+ # Pending rows younger than this are left to their own on-commit dispatch, which
43
+ # may still be in flight; the drain only picks up what that dispatch stranded.
44
+ CONFIG_NOTICE_ORPHAN_WINDOW = timedelta(minutes=5)
45
+ # Past this a dispatched or running row is presumed lost. Well clear of the emit's
46
+ # 150 s hard time limit, so a live emit is never re-driven underneath itself.
47
+ CONFIG_NOTICE_RECOVERY_WINDOW = timedelta(minutes=10)
48
+ CONFIG_NOTICE_DRAIN_BATCH_SIZE = 100
49
+ CONFIG_NOTICE_RETENTION = timedelta(days=7)
50
+
51
+
52
+ @idempotent_task(
53
+ lock_key_template="config_notice:{0}",
54
+ lock_ttl=180,
55
+ on_contention="skip",
56
+ soft_time_limit=120,
57
+ time_limit=150,
58
+ acks_late=True,
59
+ reject_on_worker_lost=True,
60
+ name="projects.emit_config_notice",
61
+ )
62
+ def emit_config_notice(self: object, request_id: str) -> None:
63
+ """Emit one queued config-change notice.
64
+
65
+ Idempotent on the outbox row: the business logic claims it with a conditional
66
+ UPDATE and no-ops on a row that is running elsewhere or already finished, so a
67
+ drain re-dispatch racing the on-commit dispatch sends the notice once.
68
+
69
+ Args:
70
+ request_id: ConfigNoticeRequest UUID string.
71
+ """
72
+ from trueppm_api.apps.projects.config_notice import run_config_notice_request
73
+
74
+ run_config_notice_request(request_id)
75
+
76
+
77
+ @idempotent_task(
78
+ lock_key_template="drain_config_notice_requests",
79
+ lock_ttl=60,
80
+ on_contention="skip",
81
+ soft_time_limit=25,
82
+ time_limit=30,
83
+ acks_late=True,
84
+ reject_on_worker_lost=True,
85
+ name="projects.drain_config_notice_requests",
86
+ )
87
+ def drain_config_notice_requests(self: object) -> None:
88
+ """Recover lost config-notice rows and dispatch stranded pending ones.
89
+
90
+ Runs every 30 seconds via Celery Beat. The singleton lock plus
91
+ ``on_contention="skip"`` means an overlapping tick is dropped rather than
92
+ queued — the next tick covers it.
93
+ """
94
+ _do_config_notice_drain()
95
+
96
+
97
+ @idempotent_task(
98
+ lock_key_template="purge_old_config_notice_requests",
99
+ lock_ttl=120,
100
+ on_contention="skip",
101
+ soft_time_limit=55,
102
+ time_limit=90,
103
+ acks_late=True,
104
+ reject_on_worker_lost=True,
105
+ name="projects.purge_old_config_notice_requests",
106
+ )
107
+ def purge_old_config_notice_requests(self: object) -> None:
108
+ """Delete done/dead ConfigNoticeRequest rows older than seven days. Nightly."""
109
+ _do_config_notice_purge()
110
+
111
+
112
+ def _do_config_notice_drain() -> None:
113
+ """Business logic for drain_config_notice_requests — extracted for testability."""
114
+ from trueppm_api.apps.projects.config_notice import MAX_CONFIG_NOTICE_ATTEMPTS
115
+ from trueppm_api.apps.projects.models import ConfigNoticeRequest, ConfigNoticeRequestStatus
116
+
117
+ now = timezone.now()
118
+ stale = ConfigNoticeRequest.objects.filter(
119
+ status__in=[ConfigNoticeRequestStatus.DISPATCHED, ConfigNoticeRequestStatus.RUNNING],
120
+ claimed_at__lt=now - CONFIG_NOTICE_RECOVERY_WINDOW,
121
+ )
122
+ abandoned = stale.filter(attempt_count__gte=MAX_CONFIG_NOTICE_ATTEMPTS).update(
123
+ status=ConfigNoticeRequestStatus.DEAD, completed_at=now
124
+ )
125
+ recovered = stale.filter(attempt_count__lt=MAX_CONFIG_NOTICE_ATTEMPTS).update(
126
+ status=ConfigNoticeRequestStatus.PENDING, celery_task_id=""
127
+ )
128
+ if abandoned:
129
+ logger.error(
130
+ "drain_config_notice_requests: abandoned %d notice(s) after %d attempts",
131
+ abandoned,
132
+ MAX_CONFIG_NOTICE_ATTEMPTS,
133
+ )
134
+ if recovered:
135
+ logger.warning("drain_config_notice_requests: recovered %d lost notice(s)", recovered)
136
+
137
+ pending = list(
138
+ ConfigNoticeRequest.objects.filter(
139
+ status=ConfigNoticeRequestStatus.PENDING,
140
+ requested_at__lt=now - CONFIG_NOTICE_ORPHAN_WINDOW,
141
+ )
142
+ .order_by("requested_at")
143
+ .values_list("pk", flat=True)[:CONFIG_NOTICE_DRAIN_BATCH_SIZE]
144
+ )
145
+ dispatched = 0
146
+ for pk in pending:
147
+ try:
148
+ result = emit_config_notice.delay(str(pk))
149
+ except SoftTimeLimitExceeded:
150
+ raise
151
+ except Exception:
152
+ logger.warning(
153
+ "drain_config_notice_requests: broker unavailable — %d notice(s) stay pending",
154
+ len(pending) - dispatched,
155
+ )
156
+ break
157
+ # Conditional: a concurrent on-commit dispatch may already have moved it.
158
+ ConfigNoticeRequest.objects.filter(pk=pk, status=ConfigNoticeRequestStatus.PENDING).update(
159
+ status=ConfigNoticeRequestStatus.DISPATCHED,
160
+ celery_task_id=str(result.id),
161
+ claimed_at=now,
162
+ )
163
+ dispatched += 1
164
+
165
+ if dispatched:
166
+ logger.info("drain_config_notice_requests: dispatched=%d", dispatched)
167
+
168
+
169
+ def _do_config_notice_purge() -> None:
170
+ """Business logic for purge_old_config_notice_requests — extracted for testability."""
171
+ from trueppm_api.apps.projects.models import ConfigNoticeRequest, ConfigNoticeRequestStatus
172
+
173
+ deleted, _ = ConfigNoticeRequest.objects.filter(
174
+ status__in=[ConfigNoticeRequestStatus.DONE, ConfigNoticeRequestStatus.DEAD],
175
+ requested_at__lt=timezone.now() - CONFIG_NOTICE_RETENTION,
176
+ ).delete()
177
+ logger.info("purge_old_config_notice_requests: deleted %d row(s)", deleted)
178
+
179
+
180
+ # ---------------------------------------------------------------------------
181
+ # close_sprint — applies a single SprintCloseRequest
182
+ # ---------------------------------------------------------------------------
183
+
184
+
185
+ # How many times a close may be attempted before the request is abandoned, and
186
+ # how long a failed one waits before the drain re-queues it (#2894). The budget
187
+ # is enforced by the drain rather than by the Celery decorator's ``max_retries``
188
+ # — see the exception handler in close_sprint for why a broker-level retry
189
+ # cannot work here.
190
+ _MAX_CLOSE_ATTEMPTS = 3
191
+ _CLOSE_RETRY_BACKOFF = timedelta(seconds=60)
192
+ # Per-sweep caps. Fresh closes and retries draw from separate dispatch budgets so
193
+ # neither can starve the other — see the drain for why one shared, ordered slice
194
+ # stopped being safe once failed rows could re-enter the pool.
195
+ _DISPATCH_BUDGET = 50
196
+ _RETRY_DISPATCH_BUDGET = 10
197
+ _RETRY_REQUEUE_BUDGET = 200
198
+ # Deliberately far below _RETRY_REQUEUE_BUDGET (#2992). Re-queueing is one bulk
199
+ # UPDATE whose cost barely moves with the row count; abandoning now costs a
200
+ # transaction, a BoardEvent insert and a channel-layer fan-out *per row*, and it
201
+ # runs ahead of the dispatch sweeps inside a 25 s soft limit. The path fires in
202
+ # bulk precisely during a correlated outage, which is the worst moment to spend
203
+ # that budget — so it takes a small bite and leaves the rest for the next sweep.
204
+ _ABANDON_BUDGET = 50
205
+
206
+
207
+ @idempotent_task(
208
+ lock_key_template="sprint_close_lock:{0}",
209
+ lock_ttl=120,
210
+ on_contention="skip",
211
+ max_retries=3,
212
+ retry_backoff=10,
213
+ retry_backoff_max=60,
214
+ retry_jitter=True,
215
+ soft_time_limit=55,
216
+ time_limit=90,
217
+ acks_late=True,
218
+ reject_on_worker_lost=True,
219
+ )
220
+ def close_sprint(self: object, request_id: str) -> None:
221
+ """Apply a queued sprint close transition.
222
+
223
+ Idempotency: if the SprintCloseRequest is already COMPLETED or FAILED, the
224
+ task is a no-op. If the sprint is already COMPLETED for any reason, the
225
+ request is short-circuited to COMPLETED. Re-entry under broker retry
226
+ therefore never produces duplicate close side-effects.
227
+
228
+ Recovery from a failure runs through the **drain**, not through the broker
229
+ (#2894). A failure rolls the transaction back and marks the row FAILED with
230
+ a ``next_attempt_at``; ``drain_sprint_close_requests`` resets it to PENDING
231
+ once that time passes and re-dispatches, up to ``_MAX_CLOSE_ATTEMPTS``. The
232
+ decorator's ``max_retries`` cannot serve this: its retry re-enters here and
233
+ hits the FAILED short-circuit above, so it would spend the budget without
234
+ running the close. When the budget is spent ``next_attempt_at`` stays null,
235
+ the row is abandoned, and the sprint remains ACTIVE — recoverable only by
236
+ issuing a fresh close request. That abandonment is announced on the board as
237
+ ``sprint_close_failed`` (#2992) via ``_finalize_close_failure``, which is the
238
+ one place any close request is marked FAILED; an intermediate, still-
239
+ retryable failure deliberately announces nothing.
240
+
241
+ On success the function:
242
+ 1. Snapshots ``completed_*`` from current task state
243
+ 2. Transitions sprint state to COMPLETED + sets closed_at
244
+ 3. Applies carry-over (FK move on incomplete tasks)
245
+ 4. Marks the SprintCloseRequest COMPLETED
246
+ 5. Enqueues a ScheduleRequest with ``reason=SPRINT_CLOSED`` for CPM recompute
247
+ 6. Broadcasts a ``sprint_closed`` board event to connected clients
248
+
249
+ Args:
250
+ request_id: SprintCloseRequest UUID string.
251
+ """
252
+ from trueppm_api.apps.projects.models import (
253
+ SprintCloseRequest,
254
+ SprintCloseRequestFailureReason,
255
+ SprintCloseRequestStatus,
256
+ SprintState,
257
+ )
258
+ from trueppm_api.apps.projects.services import (
259
+ apply_carry_over,
260
+ apply_pending_disposition,
261
+ notify_carryover_assignees,
262
+ snapshot_completed_metrics,
263
+ snapshot_sprint_task_outcomes,
264
+ )
265
+ from trueppm_api.apps.scheduling.models import (
266
+ ScheduleRequest,
267
+ ScheduleRequestReason,
268
+ )
269
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
270
+
271
+ try:
272
+ req = SprintCloseRequest.objects.select_related("sprint", "sprint__project").get(
273
+ pk=request_id
274
+ )
275
+ except SprintCloseRequest.DoesNotExist:
276
+ logger.warning("close_sprint: request %s not found, skipping", request_id)
277
+ return
278
+
279
+ if req.status in (SprintCloseRequestStatus.COMPLETED, SprintCloseRequestStatus.FAILED):
280
+ logger.info("close_sprint: request %s already %s — short-circuit", request_id, req.status)
281
+ return
282
+
283
+ # This increment MUST stay outside the `transaction.atomic()` below, and that
284
+ # placement is load-bearing rather than incidental (#2894): the retry budget
285
+ # is the only thing bounding the drain's re-queue loop, and it is enforced by
286
+ # comparing attempt_count. Wrapping close_sprint in @transaction.atomic — or
287
+ # moving this inside the block — rolls the increment back together with the
288
+ # failed close, so attempt_count never advances, the budget is never spent,
289
+ # and a permanently failing close is re-queued forever.
290
+ SprintCloseRequest.objects.filter(pk=req.pk).update(
291
+ status=SprintCloseRequestStatus.IN_FLIGHT,
292
+ started_at=timezone.now(),
293
+ attempt_count=req.attempt_count + 1,
294
+ )
295
+
296
+ try:
297
+ with transaction.atomic():
298
+ # Lock the sprint row: prevents two concurrent close attempts from
299
+ # double-snapshotting completed_* or applying carry-over twice.
300
+ from trueppm_api.apps.projects.models import Sprint
301
+
302
+ sprint = Sprint.objects.select_for_update().get(pk=req.sprint_id)
303
+
304
+ if _finalize_non_closable_sprint(req, sprint):
305
+ return
306
+
307
+ snapshot_completed_metrics(sprint)
308
+ sprint.state = SprintState.COMPLETED
309
+ sprint.closed_at = timezone.now()
310
+ sprint.save(
311
+ update_fields=[
312
+ "completed_points",
313
+ "completed_task_count",
314
+ "goal_outcome",
315
+ "state",
316
+ "closed_at",
317
+ ]
318
+ )
319
+
320
+ # ADR-0176 §2 (#982): snapshot the closing task membership BEFORE
321
+ # apply_carry_over mutates Task.sprint — otherwise "what didn't ship"
322
+ # is destroyed (carried tasks move to the next sprint, dropped tasks
323
+ # to the backlog). NOT wrapped in try/except: the audit is part of the
324
+ # close's definition of done, so a failure rolls the whole close back
325
+ # and the drain re-queues the request.
326
+ #
327
+ # That second clause was false when written (#2894) — the handler
328
+ # marked the row FAILED and nothing ever picked a FAILED row up. It
329
+ # is true now, but bounded: _MAX_CLOSE_ATTEMPTS tries, then the
330
+ # request is abandoned and the sprint stays ACTIVE. An audit failure
331
+ # that reproduces will still strand the close; it just no longer does
332
+ # so on the first try, silently.
333
+ snapshot_sprint_task_outcomes(sprint, carry_over_to=req.carry_over_to)
334
+
335
+ _clear_sprint_ranks(sprint)
336
+
337
+ carried_task_ids = apply_carry_over(sprint, req.carry_over_to)
338
+
339
+ # ADR-0102 §7: dispose of tasks still pending acceptance at close.
340
+ # Runs AFTER carry-over (so a carried task's new sprint_id is set) and
341
+ # never blocks the close. 'carry' re-flags pending tasks in the
342
+ # incoming sprint; 'reject' removes them from the sprint.
343
+ apply_pending_disposition(sprint, req.pending_disposition, by=req.requested_by)
344
+
345
+ # ADR-0232 (#1470): tell each carried task's assignee their committed
346
+ # work crossed the close→plan seam. Sourced from the faithful moved-id
347
+ # set; defers create_event_notifications to on_commit inside the
348
+ # service. Non-blocking like the reforecast digest below: a
349
+ # notification bug must never strand or revert a sprint close.
350
+ try:
351
+ notify_carryover_assignees(
352
+ sprint,
353
+ req.carry_over_to,
354
+ carried_task_ids,
355
+ actor_id=req.requested_by_id,
356
+ )
357
+ except Exception:
358
+ logger.exception(
359
+ "close_sprint: carryover notification failed for sprint %s — continuing close",
360
+ sprint.pk,
361
+ )
362
+
363
+ _recompute_and_reforecast_milestone(sprint, req)
364
+
365
+ SprintCloseRequest.objects.filter(pk=req.pk).update(
366
+ status=SprintCloseRequestStatus.COMPLETED,
367
+ completed_at=timezone.now(),
368
+ error_message="",
369
+ failure_reason="",
370
+ # Structural, not incidental: every terminal writer clears the
371
+ # retry clock, so "null means no further attempt" holds by
372
+ # construction rather than because no live path happens to leave
373
+ # a stale value behind.
374
+ next_attempt_at=None,
375
+ )
376
+
377
+ # Enqueue downstream CPM recompute with the SPRINT_CLOSED reason
378
+ # so the audit trail records why the recalculation fired.
379
+ project_id = sprint.project_id
380
+ ScheduleRequest.objects.create(
381
+ project_id=project_id,
382
+ reason=ScheduleRequestReason.SPRINT_CLOSED,
383
+ )
384
+
385
+ _compute_velocity_suggestions_safe(sprint)
386
+
387
+ sprint_id_str = str(sprint.pk)
388
+ project_id_str = str(project_id)
389
+ transaction.on_commit(
390
+ lambda: broadcast_board_event(
391
+ project_id_str,
392
+ "sprint_closed",
393
+ {"id": sprint_id_str},
394
+ )
395
+ )
396
+ # ADR-0147: emit the sprint.closed webhook. The completion snapshot in
397
+ # the payload is team velocity and is privacy-gated by the builder
398
+ # (ADR-0104) — built now, inside the close transaction, so the gate reads
399
+ # the committed policy and the on_commit callback does no DB work.
400
+ from trueppm_api.apps.projects.views import (
401
+ _dispatch_webhooks,
402
+ _sprint_closed_webhook_payload,
403
+ )
404
+
405
+ closed_payload = _sprint_closed_webhook_payload(sprint, source="sprint_close")
406
+ transaction.on_commit(
407
+ lambda: _dispatch_webhooks(project_id_str, "sprint.closed", closed_payload)
408
+ )
409
+ # The carried-over tasks changed sprint (and possibly status). Without
410
+ # a broadcast, connected clients keep rendering them under the closed
411
+ # sprint until a manual refetch. Emit one bulk event for the batch.
412
+ # Bind the ids via a default arg (matches the backlog_services pattern)
413
+ # so closure late-binding can't swap them if this grows more branches.
414
+ if carried_task_ids:
415
+
416
+ def _broadcast_carry_over(
417
+ pid: str = project_id_str, ids: list[str] = carried_task_ids
418
+ ) -> None:
419
+ broadcast_board_event(pid, "tasks_bulk_mutated", {"task_ids": ids})
420
+
421
+ transaction.on_commit(_broadcast_carry_over)
422
+
423
+ except Exception as exc:
424
+ logger.exception("close_sprint: failed for request %s", request_id)
425
+ # The whole close rolled back, so the sprint is still ACTIVE and the row
426
+ # is safe to run again from the top. Schedule a retry until the budget is
427
+ # spent; ``next_attempt_at=None`` on the last one is what makes it
428
+ # terminal (#2894).
429
+ #
430
+ # Deliberately NOT re-raised to drive the decorator's max_retries. A
431
+ # retry there re-enters close_sprint, which short-circuits on a FAILED
432
+ # row and returns immediately — the retry would burn the budget without
433
+ # ever reaching the work. The drain is the recovery path because it is
434
+ # the thing that can reset status back to PENDING first.
435
+ attempts = req.attempt_count + 1 # this run, already applied above
436
+ exhausted = attempts >= _MAX_CLOSE_ATTEMPTS
437
+ _finalize_close_failure(
438
+ req_pk=req.pk,
439
+ sprint_id=req.sprint_id,
440
+ project_id=req.sprint.project_id,
441
+ error_message=str(exc)[:1000],
442
+ failure_reason=SprintCloseRequestFailureReason.ERROR,
443
+ attempt_count=attempts,
444
+ next_attempt_at=None if exhausted else timezone.now() + _CLOSE_RETRY_BACKOFF,
445
+ )
446
+ if exhausted:
447
+ logger.error(
448
+ "close_sprint: request %s exhausted %d attempts — sprint %s stays ACTIVE",
449
+ request_id,
450
+ attempts,
451
+ req.sprint_id,
452
+ )
453
+
454
+
455
+ def _finalize_close_failure(
456
+ *,
457
+ req_pk: Any,
458
+ sprint_id: Any,
459
+ project_id: Any,
460
+ error_message: str,
461
+ failure_reason: str,
462
+ attempt_count: int,
463
+ next_attempt_at: Any = None,
464
+ expected_status: str | None = None,
465
+ ) -> None:
466
+ """Mark a close request FAILED and, when that is terminal, tell the board (#2992).
467
+
468
+ The single writer of ``status=FAILED``. It exists because the *terminal*
469
+ failure — the one a user has to be told about, because the sprint stays
470
+ ACTIVE forever — is reached from four independent places, and a broadcast
471
+ wired into only the obvious one would miss three:
472
+
473
+ 1. ``close_sprint``'s exception handler once the attempt budget is spent,
474
+ 2. ``_finalize_non_closable_sprint`` when the sprint was cancelled,
475
+ 3. the same function when the sprint is in some other non-closable state,
476
+ 4. ``_do_drain``'s orphan sweep, for a close that never raised at all
477
+ because its worker died mid-attempt on every try.
478
+
479
+ ``next_attempt_at`` is the terminality test, not ``status``: a FAILED row
480
+ with a live retry clock is one the drain will pick up again in a minute, and
481
+ announcing *that* as a failure would alarm a user about something that
482
+ self-heals. This is the same rule ``SprintCloseRequestStateSerializer.
483
+ get_terminal`` names on the read side, kept in one place on the write side so
484
+ the two cannot drift.
485
+
486
+ The broadcast is deferred with ``transaction.on_commit`` inside an explicit
487
+ ``atomic`` block because the four call sites do **not** share an ambient
488
+ transaction: two run inside ``close_sprint``'s ``with transaction.atomic()``
489
+ and two (the exception handler, which sits outside the block that just rolled
490
+ back, and the drain) run in worker autocommit. Registering the callback
491
+ against a transaction this function opens itself makes the ordering — row
492
+ durable, then announce — identical at all four, instead of correct at two by
493
+ construction and at the other two by accident.
494
+
495
+ The payload deliberately carries no ``error_message``. That field is
496
+ role-gated on ``GET /sprints/{id}/close-request/`` — raw exception text is
497
+ Admin-only and is withheld from agent tokens entirely, because a database or
498
+ broker failure puts internal hostnames and SQL fragments in it. A board
499
+ broadcast fans out to the whole project group with no per-recipient
500
+ filtering available, so putting the text here would silently reverse that
501
+ gate. Clients learn the failure happened from the event and read the text
502
+ they are entitled to from the endpoint. Everything in the payload below is
503
+ already unconditional on that endpoint for every reader who can receive the
504
+ event.
505
+
506
+ Args:
507
+ req_pk: SprintCloseRequest primary key.
508
+ sprint_id: The sprint that failed to close.
509
+ project_id: Board group to fan out on — a ``Project`` pk, which is what
510
+ makes this event deliverable (a program pk would not be).
511
+ error_message: Stored failure text; never broadcast.
512
+ failure_reason: A ``SprintCloseRequestFailureReason`` member.
513
+ attempt_count: Attempts made including the one that just failed.
514
+ next_attempt_at: When the drain may retry, or None for terminal.
515
+ expected_status: Only write if the row is still in this status. Used by
516
+ the drain, whose select-then-write split would otherwise clobber a
517
+ row that moved on in between.
518
+
519
+ The write is a check-and-set and the announcement is conditional on it. Two
520
+ races make a blind ``filter(pk=...).update()`` wrong here, and both end in
521
+ the same user-visible lie — "your sprint didn't close" about one that did:
522
+
523
+ * Django runs non-robust ``on_commit`` hooks from ``Atomic.__exit__``,
524
+ *after* the commit. ``close_sprint``'s success path registers three, and
525
+ one of them dispatches webhooks and can raise — which lands in the very
526
+ ``except`` block that calls this function, with the COMPLETED row already
527
+ durable. Excluding COMPLETED stops a committed close being rewritten as a
528
+ failure by its own post-commit fallout.
529
+ * The drain's orphan sweep selects candidates and then writes them one at a
530
+ time, so the guard that used to live in a single ``UPDATE … WHERE`` no
531
+ longer covers the write. ``expected_status`` puts it back.
532
+
533
+ Returning early when the update matched nothing keeps the broadcast honest:
534
+ an event is sent only for a row this call actually made terminal.
535
+ """
536
+ from trueppm_api.apps.projects.models import SprintCloseRequest, SprintCloseRequestStatus
537
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
538
+
539
+ with transaction.atomic():
540
+ rows = SprintCloseRequest.objects.filter(pk=req_pk)
541
+ if expected_status is not None:
542
+ rows = rows.filter(status=expected_status)
543
+ updated = rows.exclude(status=SprintCloseRequestStatus.COMPLETED).update(
544
+ status=SprintCloseRequestStatus.FAILED,
545
+ completed_at=timezone.now(),
546
+ error_message=error_message,
547
+ failure_reason=failure_reason,
548
+ next_attempt_at=next_attempt_at,
549
+ )
550
+ if next_attempt_at is not None or not updated:
551
+ return
552
+
553
+ # Bound to locals rather than read off the closure: the callback runs
554
+ # after this frame is gone, and the drain calls this in a loop.
555
+ sprint_id_str = str(sprint_id)
556
+ request_id_str = str(req_pk)
557
+ project_id_str = str(project_id)
558
+ reason = str(failure_reason)
559
+ attempts = int(attempt_count)
560
+ transaction.on_commit(
561
+ lambda: broadcast_board_event(
562
+ project_id_str,
563
+ "sprint_close_failed",
564
+ {
565
+ "id": sprint_id_str,
566
+ "request_id": request_id_str,
567
+ "failure_reason": reason,
568
+ "attempt_count": attempts,
569
+ # Constant by construction — this event is only ever emitted
570
+ # for a request that will not be retried. Stated on the wire
571
+ # so a consumer that never calls the read route still knows
572
+ # it is not looking at a transient blip.
573
+ "terminal": True,
574
+ },
575
+ )
576
+ )
577
+
578
+
579
+ def _finalize_non_closable_sprint(req: Any, sprint: Any) -> bool:
580
+ """Finalize the close request if the locked sprint can't be closed; return handled.
581
+
582
+ Returns True (and updates the ``SprintCloseRequest``) when the sprint is already
583
+ COMPLETED (mark the request COMPLETED — an earlier dispatch closed it), CANCELLED,
584
+ or otherwise not ACTIVE (mark the request FAILED). Returns False when the sprint is
585
+ ACTIVE and the close should proceed.
586
+ """
587
+ from trueppm_api.apps.projects.models import (
588
+ SprintCloseRequest,
589
+ SprintCloseRequestFailureReason,
590
+ SprintCloseRequestStatus,
591
+ SprintState,
592
+ )
593
+
594
+ if sprint.state == SprintState.COMPLETED:
595
+ # Already closed by an earlier dispatch; mark request done.
596
+ SprintCloseRequest.objects.filter(pk=req.pk).update(
597
+ status=SprintCloseRequestStatus.COMPLETED,
598
+ completed_at=timezone.now(),
599
+ next_attempt_at=None,
600
+ )
601
+ return True
602
+
603
+ if sprint.state == SprintState.CANCELLED:
604
+ _finalize_close_failure(
605
+ req_pk=req.pk,
606
+ sprint_id=sprint.pk,
607
+ project_id=sprint.project_id,
608
+ error_message="Sprint was cancelled before close could complete.",
609
+ failure_reason=SprintCloseRequestFailureReason.CANCELLED,
610
+ # ``req`` was read before the increment this attempt already applied.
611
+ attempt_count=req.attempt_count + 1,
612
+ # Terminal by nature: no retry can un-cancel a sprint. Leaving the
613
+ # clock null is what keeps the drain's retry sweep off this row, and
614
+ # is what makes the helper announce it.
615
+ next_attempt_at=None,
616
+ )
617
+ return True
618
+
619
+ if sprint.state != SprintState.ACTIVE:
620
+ _finalize_close_failure(
621
+ req_pk=req.pk,
622
+ sprint_id=sprint.pk,
623
+ project_id=sprint.project_id,
624
+ error_message=f"Sprint state {sprint.state} is not closable.",
625
+ failure_reason=SprintCloseRequestFailureReason.NOT_CLOSABLE,
626
+ attempt_count=req.attempt_count + 1,
627
+ next_attempt_at=None,
628
+ )
629
+ return True
630
+
631
+ return False
632
+
633
+
634
+ def _clear_sprint_ranks(sprint: Any) -> None:
635
+ """Clear the within-sprint execution order on close (#365, ADR-0105 §5).
636
+
637
+ A task returns to the product backlog ordered by ``priority_rank``; its
638
+ closed-sprint ``sprint_rank`` stays queryable on the HistoricalTask rows (the
639
+ pre-clear value on the create-time row, the null on the row the save() below
640
+ writes). Runs BEFORE apply_carry_over so a carried task re-enters its next sprint
641
+ un-ranked (re-seeded from priority_rank on that sprint's activate), never
642
+ inheriting a stale rank. save() (not bulk_update) so server_version bumps +
643
+ history is written.
644
+ """
645
+ from trueppm_api.apps.projects.models import Task
646
+
647
+ for task in Task.objects.filter(sprint_id=sprint.pk, is_deleted=False):
648
+ if task.sprint_rank is not None:
649
+ task.sprint_rank = None
650
+ task.save(update_fields=["sprint_rank", "server_version"])
651
+
652
+
653
+ def _recompute_and_reforecast_milestone(sprint: Any, req: Any) -> None:
654
+ """Recompute the bound milestone rollup and reforecast its finish (ADR-0074/0106).
655
+
656
+ ADR-0074: recompute the milestone rollup with the final ``completed_*`` snapshot.
657
+ Runs inside the drain transaction, after carry-over, so the milestone reflects the
658
+ closed sprint's final contribution before the sprint_closed broadcast goes out.
659
+
660
+ ADR-0106 §3 (#860) — the bridge WOW: reforecast the bound milestone's finish as a
661
+ range from the just-closed sprint's velocity. The snapshot write is synchronous
662
+ (durable with the close); the milestone_forecast_updated broadcast + Enterprise-seam
663
+ signal defer to on_commit inside the service. Wrapped non-blocking: a reforecast bug
664
+ must never strand or revert a sprint close (ADR-0106 §Durable 8).
665
+ """
666
+ if sprint.target_milestone_id is None:
667
+ return
668
+
669
+ from trueppm_api.apps.projects.services import recompute_milestone_rollup
670
+
671
+ recompute_milestone_rollup(sprint.target_milestone_id)
672
+
673
+ try:
674
+ from trueppm_api.apps.projects.services import (
675
+ notify_milestone_forecast_shift,
676
+ reforecast_bound_milestone,
677
+ )
678
+
679
+ forecast = reforecast_bound_milestone(sprint.target_milestone_id)
680
+ # #861 — push the PM cohort the milestone-confidence shift so the bridge
681
+ # reforecast isn't silent when the team closes the sprint outside the PM's
682
+ # session. Non-blocking with the reforecast itself: a digest failure must
683
+ # never strand close.
684
+ if forecast is not None:
685
+ notify_milestone_forecast_shift(forecast, sprint, actor_id=req.requested_by_id)
686
+ except Exception:
687
+ logger.exception(
688
+ "close_sprint: reforecast failed for milestone %s — continuing close",
689
+ sprint.target_milestone_id,
690
+ )
691
+
692
+
693
+ def _compute_velocity_suggestions_safe(sprint: Any) -> None:
694
+ """Compute velocity-calibration suggestions (ADR-0065), non-blocking on failure.
695
+
696
+ Any error logs and is swallowed so a calibration bug cannot strand a sprint close.
697
+ """
698
+ try:
699
+ from trueppm_api.apps.scheduling.services import compute_velocity_suggestions
700
+
701
+ compute_velocity_suggestions(sprint.pk)
702
+ except Exception:
703
+ logger.exception(
704
+ "close_sprint: velocity calibration failed for sprint %s — continuing close",
705
+ sprint.pk,
706
+ )
707
+
708
+
709
+ # ---------------------------------------------------------------------------
710
+ # Drain — every 30 seconds via Beat
711
+ # ---------------------------------------------------------------------------
712
+
713
+
714
+ @idempotent_task(
715
+ lock_key_template="drain_sprint_close_requests",
716
+ lock_ttl=60,
717
+ on_contention="skip",
718
+ soft_time_limit=25,
719
+ time_limit=30,
720
+ acks_late=True,
721
+ reject_on_worker_lost=True,
722
+ name="projects.drain_sprint_close_requests",
723
+ )
724
+ def drain_sprint_close_requests(self: object) -> None:
725
+ """Dispatch any pending or stranded SprintCloseRequest rows.
726
+
727
+ Beat: every 30 s. Like the scheduling drain, this also recovers IN_FLIGHT
728
+ rows that have aged past the 5-minute orphan window (worker died mid-close).
729
+ """
730
+ _do_drain()
731
+
732
+
733
+ def _warn_sweep_truncated(task_name: str, unreached: list[object]) -> None:
734
+ """Log (WARNING) that a Beat sweep hit its soft time limit with items left.
735
+
736
+ Operators otherwise see only a clean-looking partial run; naming the first
737
+ unreached ids makes the truncation greppable. Capped so a huge tail cannot
738
+ bloat the log line.
739
+ """
740
+ sample = ", ".join(str(pk) for pk in unreached[:20])
741
+ logger.warning(
742
+ "%s: soft time limit exceeded; %d item(s) not processed (first: %s)",
743
+ task_name,
744
+ len(unreached),
745
+ sample,
746
+ )
747
+
748
+
749
+ @idempotent_task(
750
+ lock_key_template="update_sprint_burndown_snapshots",
751
+ lock_ttl=300,
752
+ on_contention="skip",
753
+ soft_time_limit=120,
754
+ time_limit=180,
755
+ acks_late=True,
756
+ reject_on_worker_lost=True,
757
+ name="projects.update_sprint_burndown_snapshots",
758
+ )
759
+ def update_sprint_burndown_snapshots(self: object) -> None:
760
+ """Write yesterday's burndown row for every ACTIVE sprint.
761
+
762
+ Beat: 01:00 UTC daily. Real-time UPSERTs from the task_status_changed
763
+ signal cover today's row; this Beat task fills in days where no status
764
+ changed (and therefore no signal fired).
765
+ """
766
+ from trueppm_api.apps.projects.models import Sprint, SprintState
767
+ from trueppm_api.apps.projects.services import upsert_burndown_for_sprint
768
+
769
+ yesterday = timezone.localdate() - timedelta(days=1)
770
+ # Deterministic order so a truncated run always cuts the same tail and the
771
+ # WARNING below names exactly the sprints that were not reached.
772
+ # TODO(#4420): persisted cursor / per-item fan-out for sweeps that overrun.
773
+ sprints = list(Sprint.objects.filter(state=SprintState.ACTIVE, is_deleted=False).order_by("pk"))
774
+ for index, sprint in enumerate(sprints):
775
+ try:
776
+ upsert_burndown_for_sprint(sprint, snapshot_date=yesterday)
777
+ except SoftTimeLimitExceeded:
778
+ # Per-item fault isolation must not swallow the task-level time limit:
779
+ # an `except Exception` below would log this as one sprint's failure and
780
+ # keep looping until the hard kill, silently truncating the sweep.
781
+ _warn_sweep_truncated(
782
+ "update_sprint_burndown_snapshots", [s.pk for s in sprints[index:]]
783
+ )
784
+ raise
785
+ except Exception:
786
+ logger.exception("update_sprint_burndown_snapshots: failed for sprint %s", sprint.pk)
787
+
788
+
789
+ @idempotent_task(
790
+ lock_key_template="generate_recurring_occurrences",
791
+ lock_ttl=300,
792
+ on_contention="skip",
793
+ soft_time_limit=120,
794
+ time_limit=180,
795
+ acks_late=True,
796
+ reject_on_worker_lost=True,
797
+ name="projects.generate_recurring_occurrences",
798
+ )
799
+ def generate_recurring_occurrences(self: object) -> None:
800
+ """Lazily materialize upcoming occurrences for every active recurrence rule.
801
+
802
+ Beat: hourly. Generates only occurrences due within
803
+ ``settings.TRUEPPM_RECURRENCE_HORIZON_DAYS`` (a bounded look-ahead — never the
804
+ full series) that do not already exist, honoring each rule's end condition.
805
+ Idempotent via the (rule, date) unique constraint and the skip-on-contention
806
+ lock; per-rule try/except so one malformed rule cannot starve the sweep (ADR-0090).
807
+ """
808
+ from django.conf import settings as dj_settings
809
+
810
+ from trueppm_api.apps.projects.models import TaskRecurrenceRule
811
+ from trueppm_api.apps.projects.services import _generate_due_occurrences
812
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
813
+
814
+ horizon = getattr(dj_settings, "TRUEPPM_RECURRENCE_HORIZON_DAYS", 14)
815
+ total = 0
816
+ # Collect new occurrence ids per project so each project's open boards get a
817
+ # single bulk event rather than one per task.
818
+ created_by_project: dict[str, list[str]] = {}
819
+ # TODO(#4420): persisted cursor / per-item fan-out for sweeps that overrun.
820
+ rules = list(
821
+ TaskRecurrenceRule.objects.filter(is_deleted=False)
822
+ .select_related("task", "task__assignee")
823
+ .order_by("pk")
824
+ )
825
+ for index, rule in enumerate(rules):
826
+ try:
827
+ created = _generate_due_occurrences(rule, horizon_days=horizon)
828
+ except SoftTimeLimitExceeded:
829
+ _warn_sweep_truncated("generate_recurring_occurrences", [r.pk for r in rules[index:]])
830
+ raise
831
+ except Exception:
832
+ logger.exception("generate_recurring_occurrences: failed for rule %s", rule.pk)
833
+ continue
834
+ for task in created:
835
+ created_by_project.setdefault(str(task.project_id), []).append(str(task.id))
836
+ total += len(created)
837
+ if total:
838
+ logger.info("generate_recurring_occurrences: created %d occurrence(s)", total)
839
+
840
+ # Materialized occurrences are board-scoped tasks that show up on the project
841
+ # board; without a broadcast a connected client only sees them on its next manual
842
+ # refresh or delta pull (#1008). Emit one bulk event per project so open boards
843
+ # live-update. Deferred via on_commit to honor the broadcast contract (broadcast
844
+ # only after the rows are durably committed); this Beat task runs in autocommit,
845
+ # where the occurrences are already committed and the callback fires immediately.
846
+ for pid, task_ids in created_by_project.items():
847
+
848
+ def _broadcast(pid: str = pid, ids: list[str] = task_ids) -> None:
849
+ broadcast_board_event(pid, "tasks_bulk_mutated", {"task_ids": ids})
850
+
851
+ transaction.on_commit(_broadcast)
852
+
853
+
854
+ @idempotent_task(
855
+ lock_key_template="purge_sprint_close_requests",
856
+ lock_ttl=120,
857
+ on_contention="skip",
858
+ soft_time_limit=55,
859
+ time_limit=90,
860
+ acks_late=True,
861
+ reject_on_worker_lost=True,
862
+ name="projects.purge_sprint_close_requests",
863
+ )
864
+ def purge_sprint_close_requests(self: object) -> None:
865
+ """Delete COMPLETED / *terminally* FAILED SprintCloseRequest rows older than 7 days.
866
+
867
+ The retention window is measured from ``requested_at``, so a request that sat
868
+ PENDING for longer than the window — a drain or broker outage, which the purge
869
+ survives because it excludes PENDING — is already older than the cutoff the
870
+ moment it finally runs. Without the ``next_attempt_at`` guard below, a
871
+ transient failure on that first attempt would schedule a 60-second retry and
872
+ the nightly purge could delete the row before the retry ever fired: the sprint
873
+ stays ACTIVE *and* the record of why is gone, which is strictly worse than the
874
+ stranding #2894 exists to fix. A row with a live retry clock is not finished,
875
+ whatever its status says, so it is not eligible for retention purging.
876
+ """
877
+ from trueppm_api.apps.projects.models import (
878
+ SprintCloseRequest,
879
+ SprintCloseRequestStatus,
880
+ )
881
+
882
+ cutoff = timezone.now() - timedelta(days=7)
883
+ deleted, _ = (
884
+ SprintCloseRequest.objects.filter(
885
+ status__in=[
886
+ SprintCloseRequestStatus.COMPLETED,
887
+ SprintCloseRequestStatus.FAILED,
888
+ ],
889
+ requested_at__lt=cutoff,
890
+ )
891
+ .exclude(
892
+ status=SprintCloseRequestStatus.FAILED,
893
+ next_attempt_at__isnull=False,
894
+ )
895
+ .delete()
896
+ )
897
+ logger.info("purge_sprint_close_requests: deleted %d row(s)", deleted)
898
+
899
+
900
+ # ---------------------------------------------------------------------------
901
+ # Soft-deleted project retention purge (#1114, ADR-0173)
902
+ # ---------------------------------------------------------------------------
903
+
904
+ # Projects hard-deleted per transaction. Each project's DB-level CASCADE loads
905
+ # its whole child subtree (tasks, edges, sprints, risks, baselines, …) into the
906
+ # collector, so — unlike the flat single-table purges (webhook/taskrun/sync) — the
907
+ # delete is bounded into batches to cap collector memory and lock-hold time. A
908
+ # soft-deleted project is already invisible to every reader (#1112), so spreading
909
+ # the hard-delete across several transactions has no user-visible effect.
910
+ _PROJECT_PURGE_BATCH_SIZE = 50
911
+
912
+
913
+ def _do_project_purge(*, dry_run: bool = False, override_value: int | None = None) -> int:
914
+ """Business logic for purge_soft_deleted_projects — extracted for testability.
915
+
916
+ Hard-deletes (row + DB CASCADE children) projects whose soft-delete age exceeds
917
+ the window resolved by ``resolve_retention`` (operator override → the
918
+ ``TRUEPPM_PROJECT_SOFT_DELETE_RETENTION_DAYS`` default, ADR-0173); ``None``
919
+ disables the purge (unbounded retention). Returns the number of ``Project`` rows
920
+ deleted, or — when ``dry_run`` — the number eligible. ``override_value`` forces a
921
+ hypothetical window (used by the System Health impact estimate).
922
+
923
+ Eligibility is ``is_deleted=True AND deleted_at <= now - window``. A NULL
924
+ ``deleted_at`` is deliberately **excluded**: a project soft-deleted before the
925
+ ``deleted_at`` column existed has an unknown age and must never be silently
926
+ hard-deleted — the safe default is to retain it (an operator can still remove it
927
+ via ``?force=true``).
928
+
929
+ Several FKs to Project are ``on_delete=PROTECT`` and would block a bare
930
+ ``Project.delete()``, so the delete is delegated to ``hard_delete_projects``,
931
+ which resolves those children reflectively from ``_meta`` and purges them first —
932
+ the same helper the ``?force=true`` hard-delete path uses. This used to be a
933
+ hand-written ``ProjectMembership`` pre-delete asserting it was the *only* PROTECT
934
+ FK; that enumeration went stale when mention groups landed and a single project
935
+ that had ever carried one aborted the whole batch (#2372).
936
+
937
+ ``broadcast=True`` is passed on every batch so a purged project's board gets its
938
+ own ``project_hard_deleted`` event, same as every other hard-delete path (#3860,
939
+ #4374) — a connected client is unlikely this late in the retention window, but
940
+ a stale socket or a shortened window should not surface as silent desync.
941
+
942
+ HistoricalProject rows are intentionally not touched here; they age out via the
943
+ separate history retention purge.
944
+ """
945
+ from trueppm_api.apps.access.services import hard_delete_projects
946
+ from trueppm_api.apps.observability.retention import resolve_retention
947
+ from trueppm_api.apps.projects.models import Project
948
+
949
+ retention_days = (
950
+ override_value
951
+ if override_value is not None
952
+ else resolve_retention("TRUEPPM_PROJECT_SOFT_DELETE_RETENTION_DAYS")
953
+ )
954
+ if retention_days is None:
955
+ return 0
956
+
957
+ cutoff = timezone.now() - timedelta(days=retention_days)
958
+ eligible = Project.objects.filter(
959
+ is_deleted=True,
960
+ deleted_at__isnull=False,
961
+ deleted_at__lte=cutoff,
962
+ )
963
+ if dry_run:
964
+ return eligible.count()
965
+
966
+ project_ids = list(eligible.values_list("pk", flat=True))
967
+ deleted_projects = 0
968
+ for start in range(0, len(project_ids), _PROJECT_PURGE_BATCH_SIZE):
969
+ batch = project_ids[start : start + _PROJECT_PURGE_BATCH_SIZE]
970
+ # hard_delete_projects is itself @transaction.atomic, so each batch remains a
971
+ # single transaction — the batching still caps collector memory and lock-hold
972
+ # time without one failure rolling back previously purged batches.
973
+ deleted_projects += hard_delete_projects(batch, broadcast=True)
974
+ if deleted_projects:
975
+ logger.info(
976
+ "purge_soft_deleted_projects: hard-deleted %d soft-deleted project(s)",
977
+ deleted_projects,
978
+ )
979
+ return deleted_projects
980
+
981
+
982
+ @idempotent_task(
983
+ lock_key_template="purge_soft_deleted_projects",
984
+ lock_ttl=600,
985
+ on_contention="skip",
986
+ soft_time_limit=540,
987
+ time_limit=600,
988
+ acks_late=True,
989
+ reject_on_worker_lost=True,
990
+ name="projects.purge_soft_deleted_projects",
991
+ )
992
+ def purge_soft_deleted_projects(self: object) -> None:
993
+ """Hard-delete soft-deleted projects past the retention window.
994
+
995
+ Dispatchable directly, but not on its own Beat schedule — the consolidated
996
+ retention coordinator (``retention.run_purge``) owns scheduled purging and picks
997
+ this up via the ``purge_registry`` binding (ADR-0173 §C), running it alongside
998
+ the other retention purges in one unified ``PurgeRun``.
999
+ """
1000
+ _do_project_purge()
1001
+
1002
+
1003
+ # ---------------------------------------------------------------------------
1004
+ # Drain implementation — extracted for testability
1005
+ # ---------------------------------------------------------------------------
1006
+
1007
+
1008
+ _ORPHAN_WINDOW = timedelta(minutes=5)
1009
+
1010
+
1011
+ def _do_drain() -> None:
1012
+ from trueppm_api.apps.projects.models import (
1013
+ SprintCloseRequest,
1014
+ SprintCloseRequestFailureReason,
1015
+ SprintCloseRequestStatus,
1016
+ )
1017
+
1018
+ now = timezone.now()
1019
+ orphan_cutoff = now - _ORPHAN_WINDOW
1020
+
1021
+ # Recover IN_FLIGHT rows that have stalled past the orphan window — the
1022
+ # task_id may not match anything live, so we reset and let the next
1023
+ # dispatch attempt acquire the per-request lock fresh.
1024
+ #
1025
+ # Bounded by the same budget as the failure path (#2894). ``close_sprint``
1026
+ # increments ``attempt_count`` on every entry, so a close that orphans rather
1027
+ # than raising — a worker OOM-killed on each attempt — was recovered here
1028
+ # without limit while the counter climbed forever. A constant named as *the*
1029
+ # close attempt budget that only one of the two recovery paths honors is a
1030
+ # guard narrower than the class it names, which is how this bug survived in
1031
+ # the failure path to begin with.
1032
+ recovered = SprintCloseRequest.objects.filter(
1033
+ status=SprintCloseRequestStatus.IN_FLIGHT,
1034
+ started_at__lt=orphan_cutoff,
1035
+ attempt_count__lt=_MAX_CLOSE_ATTEMPTS,
1036
+ ).update(status=SprintCloseRequestStatus.PENDING)
1037
+
1038
+ # An orphan whose budget is spent must be *abandoned*, not left IN_FLIGHT.
1039
+ # Capping the recovery above without this would trade an unbounded loop for a
1040
+ # row wedged in a non-terminal state that no sweep touches and no reader can
1041
+ # interpret — the same silent stranding in a different status.
1042
+ #
1043
+ # Materialised row-by-row rather than left as one bulk .update() (#2992):
1044
+ # this is a terminal failure like any other, so it has to announce itself on
1045
+ # the sprint's board — and a bulk update returns a count, which cannot say
1046
+ # *which* projects to fan out to. Sliced for the same reason every other
1047
+ # statement in this sweep is: one UPDATE that costs the same whether it hits
1048
+ # one row or ten thousand becomes N BoardEvent inserts and N group_sends
1049
+ # once it broadcasts, inside a task with a soft time limit. A correlated
1050
+ # outage (workers OOM-killed across many projects) is exactly when this path
1051
+ # fires in bulk, so leaving it unbounded would turn a bad minute into a
1052
+ # worse one. The remainder is picked up on the next 30 s sweep.
1053
+ stalled = list(
1054
+ SprintCloseRequest.objects.filter(
1055
+ status=SprintCloseRequestStatus.IN_FLIGHT,
1056
+ started_at__lt=orphan_cutoff,
1057
+ attempt_count__gte=_MAX_CLOSE_ATTEMPTS,
1058
+ ).values("pk", "sprint_id", "sprint__project_id", "attempt_count")[:_ABANDON_BUDGET]
1059
+ )
1060
+ abandoned = 0
1061
+ for row in stalled:
1062
+ # Each row belongs to a different project, so this is one event per board
1063
+ # rather than a loop fanning the same event out N times. Isolated per row:
1064
+ # a channel-layer or BoardEvent fault on one project must not abort the
1065
+ # sweep before it dispatches the fresh, healthy closes at the bottom of
1066
+ # this function — the bulk UPDATE this replaced could not fail that way.
1067
+ try:
1068
+ _finalize_close_failure(
1069
+ req_pk=row["pk"],
1070
+ sprint_id=row["sprint_id"],
1071
+ project_id=row["sprint__project_id"],
1072
+ error_message=(
1073
+ "The close stopped responding on every attempt and was abandoned. "
1074
+ "The sprint is still open."
1075
+ ),
1076
+ failure_reason=SprintCloseRequestFailureReason.STALLED,
1077
+ attempt_count=row["attempt_count"],
1078
+ # Restores the predicate the single bulk UPDATE used to carry in
1079
+ # its WHERE clause. Without it the select-then-write split can
1080
+ # clobber a row that finished in between and announce a failure
1081
+ # for a sprint that closed.
1082
+ expected_status=SprintCloseRequestStatus.IN_FLIGHT,
1083
+ )
1084
+ except SoftTimeLimitExceeded:
1085
+ raise
1086
+ except Exception:
1087
+ logger.exception(
1088
+ "drain_sprint_close_requests: abandoning stalled request %s failed", row["pk"]
1089
+ )
1090
+ continue
1091
+ abandoned += 1
1092
+ if abandoned:
1093
+ logger.error(
1094
+ "drain_sprint_close_requests: abandoned %d close request(s) stalled past "
1095
+ "the attempt budget",
1096
+ abandoned,
1097
+ )
1098
+ if recovered:
1099
+ logger.warning(
1100
+ "drain_sprint_close_requests: recovered %d orphaned IN_FLIGHT row(s)",
1101
+ recovered,
1102
+ )
1103
+
1104
+ # Re-queue FAILED rows whose retry clock has come round (#2894). Before this
1105
+ # the drain recovered IN_FLIGHT only, so a single unsnapshottable task left
1106
+ # the sprint ACTIVE indefinitely behind a terminally-FAILED request, with no
1107
+ # path back except manual DB intervention.
1108
+ #
1109
+ # `next_attempt_at__isnull=False` is the whole guard: a failure nothing can
1110
+ # fix (sprint cancelled, sprint not closable) and an exhausted budget both
1111
+ # leave it null, so neither is picked up here. `completed_at` is cleared so
1112
+ # the row does not read as finished while it waits to run again.
1113
+ # Capped like the dispatch slices below: a correlated failure could otherwise
1114
+ # flip an unbounded number of rows, and hold their locks, in one statement
1115
+ # inside a task that has a soft time limit.
1116
+ retry_ids = SprintCloseRequest.objects.filter(
1117
+ status=SprintCloseRequestStatus.FAILED,
1118
+ next_attempt_at__isnull=False,
1119
+ next_attempt_at__lte=now,
1120
+ attempt_count__lt=_MAX_CLOSE_ATTEMPTS,
1121
+ ).values("pk")[:_RETRY_REQUEUE_BUDGET]
1122
+ requeued = SprintCloseRequest.objects.filter(pk__in=retry_ids).update(
1123
+ status=SprintCloseRequestStatus.PENDING,
1124
+ next_attempt_at=None,
1125
+ completed_at=None,
1126
+ # Cleared alongside completed_at: a row waiting to run again has not
1127
+ # started, and a stale started_at would both misread on the API and feed
1128
+ # the orphan sweep above a start time from a previous attempt.
1129
+ started_at=None,
1130
+ )
1131
+ if requeued:
1132
+ logger.warning(
1133
+ "drain_sprint_close_requests: re-queued %d failed close request(s) for retry",
1134
+ requeued,
1135
+ )
1136
+
1137
+ pending = list(
1138
+ SprintCloseRequest.objects.filter(
1139
+ status=SprintCloseRequestStatus.PENDING,
1140
+ requested_at__lt=now - timedelta(seconds=2),
1141
+ attempt_count=0,
1142
+ ).order_by("requested_at")[:_DISPATCH_BUDGET]
1143
+ )
1144
+ # Retries draw from their own budget rather than competing for the slice
1145
+ # above (#2894). A re-queued row keeps its original ``requested_at`` — that
1146
+ # field answers "when did the user ask", and the read route shows it — so it
1147
+ # sorts ahead of every newer close. Before the retry sweep existed nothing
1148
+ # old could re-enter the PENDING pool, so a single ordered slice was safe;
1149
+ # now a correlated failure would let the retry cohort fill the whole budget
1150
+ # and strand fresh user closes behind it. Two budgets, neither starving.
1151
+ pending += list(
1152
+ SprintCloseRequest.objects.filter(
1153
+ status=SprintCloseRequestStatus.PENDING,
1154
+ requested_at__lt=now - timedelta(seconds=2),
1155
+ attempt_count__gt=0,
1156
+ ).order_by("requested_at")[:_RETRY_DISPATCH_BUDGET]
1157
+ )
1158
+ dispatched = 0
1159
+ for req in pending:
1160
+ try:
1161
+ close_sprint.delay(str(req.id))
1162
+ except SoftTimeLimitExceeded:
1163
+ raise
1164
+ except Exception:
1165
+ logger.warning(
1166
+ "drain_sprint_close_requests: broker unavailable — request %s stays pending",
1167
+ req.id,
1168
+ )
1169
+ continue
1170
+ dispatched += 1
1171
+ if dispatched or recovered or requeued:
1172
+ logger.info(
1173
+ "drain_sprint_close_requests: dispatched=%d recovered=%d requeued=%d",
1174
+ dispatched,
1175
+ recovered,
1176
+ requeued,
1177
+ )
1178
+
1179
+
1180
+ # ---------------------------------------------------------------------------
1181
+ # cascade_project_soft_delete — offloaded child tombstone cascade (#1112)
1182
+ # ---------------------------------------------------------------------------
1183
+
1184
+
1185
+ @idempotent_task(
1186
+ lock_key_template="project_cascade_soft_delete:{0}",
1187
+ lock_ttl=600,
1188
+ on_contention="skip",
1189
+ max_retries=3,
1190
+ retry_backoff=10,
1191
+ retry_backoff_max=120,
1192
+ retry_jitter=True,
1193
+ soft_time_limit=540,
1194
+ time_limit=600,
1195
+ acks_late=True,
1196
+ reject_on_worker_lost=True,
1197
+ name="projects.cascade_project_soft_delete",
1198
+ )
1199
+ def cascade_project_soft_delete(self: object, project_id: str) -> None:
1200
+ """Tombstone a soft-deleted project's children off the request path (#1112).
1201
+
1202
+ ``ProjectViewSet.perform_destroy`` tombstones the project row synchronously
1203
+ (instant, so the project reads as gone) and enqueues this task to drain the
1204
+ potentially huge child cascade — tasks, dependency edges, sprints, risks, and
1205
+ baselines — that #1111 previously ran inline inside the request transaction.
1206
+
1207
+ Idempotency: the cascade only touches rows still ``is_deleted=False``, so a
1208
+ broker-retry, a duplicate dispatch, or the ``on_contention="skip"`` lock all
1209
+ resolve to a safe no-op. A vanished project (hard-deleted in the meantime, so
1210
+ its children are gone via DB CASCADE) is simply skipped.
1211
+
1212
+ No broadcast here: the ``project_deleted`` board event already fired from
1213
+ ``perform_destroy`` on commit, and child tombstones reach mobile clients via
1214
+ the sync delta pull (the ``sync_seq`` cursor this cascade stamps, ADR-0686),
1215
+ not over WebSocket — so there is nothing to re-broadcast and no double-fire
1216
+ risk.
1217
+ """
1218
+ from trueppm_api.apps.projects.models import (
1219
+ Project,
1220
+ cascade_project_children_soft_delete,
1221
+ )
1222
+
1223
+ if not Project.objects.filter(pk=project_id).exists():
1224
+ logger.info(
1225
+ "cascade_project_soft_delete: project %s gone (hard-deleted?) — skipping",
1226
+ project_id,
1227
+ )
1228
+ return
1229
+
1230
+ from trueppm_api.apps.projects.models import cross_project_edge_rows
1231
+ from trueppm_api.apps.projects.services import fan_out_cross_project_edges
1232
+
1233
+ with transaction.atomic():
1234
+ # Collect before the cascade tombstones the edges. The surviving endpoint's
1235
+ # project otherwise keeps CPM dates constrained by a predecessor that no
1236
+ # longer exists, with no event (#4592). A retry finds no live edges, so the
1237
+ # fan-out is idempotent.
1238
+ cross_edges = cross_project_edge_rows(project_id=project_id)
1239
+ cascade_project_children_soft_delete(project_id)
1240
+ fan_out_cross_project_edges(cross_edges, created=False, skip_project_ids={str(project_id)})
1241
+ logger.info("cascade_project_soft_delete: cascaded children for project %s", project_id)
1242
+
1243
+
1244
+ # ---------------------------------------------------------------------------
1245
+ # Async project export bundle (ADR-0219, #1266) — mirrors workspace export (ADR-0174)
1246
+ # ---------------------------------------------------------------------------
1247
+
1248
+
1249
+ @shared_task( # type: ignore[untyped-decorator]
1250
+ bind=True,
1251
+ max_retries=EXPORT_MAX_RETRIES,
1252
+ soft_time_limit=600,
1253
+ time_limit=660,
1254
+ acks_late=True,
1255
+ reject_on_worker_lost=True,
1256
+ name="projects.run_project_export",
1257
+ )
1258
+ def run_project_export(self: object, job_id: str) -> None:
1259
+ """Build the project export bundle for ``job_id`` (ADR-0219).
1260
+
1261
+ Idempotent: claims the job under ``select_for_update`` and no-ops unless it is
1262
+ ``pending``/``running``, so a duplicate delivery (broker retry, drain re-dispatch)
1263
+ cannot produce two archives. Transient failures retry up to ``EXPORT_MAX_RETRIES``
1264
+ (the job stays ``running`` so a retry is allowed); on exhaustion the job is marked
1265
+ ``failed`` and the Admin can request a fresh export.
1266
+ """
1267
+ from trueppm_api.apps.projects.export_bundle import build_and_store_project_archive
1268
+ from trueppm_api.apps.projects.models import ExportJobStatus, ProjectExportJob
1269
+
1270
+ with transaction.atomic():
1271
+ job = ProjectExportJob.objects.select_for_update().filter(pk=job_id).first()
1272
+ if job is None:
1273
+ logger.warning("run_project_export: job %s not found", job_id)
1274
+ return
1275
+ if job.status not in (ExportJobStatus.PENDING, ExportJobStatus.RUNNING):
1276
+ logger.info("run_project_export: job %s already %s, skipping", job_id, job.status)
1277
+ return
1278
+ job.status = ExportJobStatus.RUNNING
1279
+ job.started_at = timezone.now()
1280
+ job.celery_task_id = getattr(getattr(self, "request", None), "id", "") or ""
1281
+ job.save(update_fields=["status", "started_at", "celery_task_id"])
1282
+
1283
+ try:
1284
+ storage_path, size = build_and_store_project_archive(job_id)
1285
+ except Exception as exc:
1286
+ retries = getattr(getattr(self, "request", None), "retries", 0)
1287
+ if retries < EXPORT_MAX_RETRIES:
1288
+ logger.warning("run_project_export: job %s failed, retrying", job_id, exc_info=True)
1289
+ raise self.retry(exc=exc, countdown=10 * (2**retries)) from exc # type: ignore[attr-defined]
1290
+ logger.exception("run_project_export: job %s failed permanently", job_id)
1291
+ ProjectExportJob.objects.filter(pk=job_id).update(
1292
+ status=ExportJobStatus.FAILED,
1293
+ error_detail=str(exc)[:2000],
1294
+ completed_at=timezone.now(),
1295
+ )
1296
+ return
1297
+
1298
+ retention = _export_retention_days()
1299
+ expires_at = timezone.now() + timedelta(days=retention) if retention is not None else None
1300
+ ProjectExportJob.objects.filter(pk=job_id).update(
1301
+ status=ExportJobStatus.SUCCESS,
1302
+ file_path=storage_path,
1303
+ file_size=size,
1304
+ expires_at=expires_at,
1305
+ completed_at=timezone.now(),
1306
+ error_detail="",
1307
+ )
1308
+
1309
+
1310
+ @idempotent_task(
1311
+ lock_key_template="drain_project_exports",
1312
+ lock_ttl=60,
1313
+ on_contention="skip",
1314
+ soft_time_limit=25,
1315
+ time_limit=30,
1316
+ acks_late=True,
1317
+ reject_on_worker_lost=True,
1318
+ name="projects.drain_project_exports",
1319
+ )
1320
+ def drain_project_exports(self: object) -> None:
1321
+ """Re-dispatch project export jobs stuck in ``pending`` (broker down at on_commit)."""
1322
+ _do_drain_project_exports()
1323
+
1324
+
1325
+ @idempotent_task(
1326
+ lock_key_template="purge_expired_project_exports",
1327
+ lock_ttl=120,
1328
+ on_contention="skip",
1329
+ soft_time_limit=55,
1330
+ time_limit=90,
1331
+ acks_late=True,
1332
+ reject_on_worker_lost=True,
1333
+ name="projects.purge_expired_project_exports",
1334
+ )
1335
+ def purge_expired_project_exports(self: object) -> None:
1336
+ """Delete project export jobs past their link expiry, and their stored archives."""
1337
+ _do_purge_expired_project_exports()
1338
+
1339
+
1340
+ def _export_retention_days() -> int | None:
1341
+ from django.conf import settings
1342
+
1343
+ return getattr(settings, "TRUEPPM_EXPORT_RETENTION_DAYS", DEFAULT_EXPORT_RETENTION_DAYS)
1344
+
1345
+
1346
+ def _do_drain_project_exports() -> None:
1347
+ from trueppm_api.apps.projects.models import ExportJobStatus, ProjectExportJob
1348
+
1349
+ orphan_cutoff = timezone.now() - timedelta(minutes=EXPORT_ORPHAN_WINDOW_MINUTES)
1350
+ stuck = list(
1351
+ ProjectExportJob.objects.filter(
1352
+ status=ExportJobStatus.PENDING,
1353
+ celery_task_id="",
1354
+ created_at__lt=orphan_cutoff,
1355
+ ).order_by("created_at")[:EXPORT_DRAIN_BATCH_SIZE]
1356
+ )
1357
+ if not stuck:
1358
+ return
1359
+ for job in stuck:
1360
+ try:
1361
+ run_project_export.delay(str(job.id))
1362
+ except SoftTimeLimitExceeded:
1363
+ raise
1364
+ except Exception: # pragma: no cover - broker still down, next tick retries
1365
+ logger.warning("drain_project_exports: broker still unavailable for %s", job.id)
1366
+ break
1367
+ logger.info("drain_project_exports: re-dispatched %d job(s)", len(stuck))
1368
+
1369
+
1370
+ def _do_purge_expired_project_exports() -> None:
1371
+ from django.core.files.storage import default_storage
1372
+
1373
+ from trueppm_api.apps.projects.models import ProjectExportJob
1374
+
1375
+ retention = _export_retention_days()
1376
+ if retention is None: # retention disabled — keep archives indefinitely
1377
+ return
1378
+ expired = ProjectExportJob.objects.filter(expires_at__lt=timezone.now())
1379
+ count = 0
1380
+ for job in expired.iterator():
1381
+ if job.file_path:
1382
+ try:
1383
+ default_storage.delete(job.file_path)
1384
+ except OSError: # pragma: no cover - storage drift, still drop the row
1385
+ logger.warning(
1386
+ "purge_expired_project_exports: could not delete file for %s", job.id
1387
+ )
1388
+ job.delete()
1389
+ count += 1
1390
+ if count:
1391
+ logger.info("purge_expired_project_exports: deleted %d expired export(s)", count)
1392
+
1393
+
1394
+ # ---------------------------------------------------------------------------
1395
+ # Async program export bundle (ADR-0219, #1958) — the program-grain sibling of
1396
+ # the project export tasks above; identical durable-execution shape.
1397
+ # ---------------------------------------------------------------------------
1398
+
1399
+
1400
+ @shared_task( # type: ignore[untyped-decorator]
1401
+ bind=True,
1402
+ max_retries=EXPORT_MAX_RETRIES,
1403
+ soft_time_limit=600,
1404
+ time_limit=660,
1405
+ acks_late=True,
1406
+ reject_on_worker_lost=True,
1407
+ name="projects.run_program_export",
1408
+ )
1409
+ def run_program_export(self: object, job_id: str) -> None:
1410
+ """Build the program export bundle for ``job_id`` (ADR-0219, #1958).
1411
+
1412
+ Idempotent: claims the job under ``select_for_update`` and no-ops unless it is
1413
+ ``pending``/``running``, so a duplicate delivery (broker retry, drain re-dispatch)
1414
+ cannot produce two archives. Transient failures retry up to ``EXPORT_MAX_RETRIES``;
1415
+ on exhaustion the job is marked ``failed`` and the Admin can request a fresh export.
1416
+ """
1417
+ from trueppm_api.apps.projects.export_bundle import build_and_store_program_archive
1418
+ from trueppm_api.apps.projects.models import ExportJobStatus, ProgramExportJob
1419
+
1420
+ with transaction.atomic():
1421
+ job = ProgramExportJob.objects.select_for_update().filter(pk=job_id).first()
1422
+ if job is None:
1423
+ logger.warning("run_program_export: job %s not found", job_id)
1424
+ return
1425
+ if job.status not in (ExportJobStatus.PENDING, ExportJobStatus.RUNNING):
1426
+ logger.info("run_program_export: job %s already %s, skipping", job_id, job.status)
1427
+ return
1428
+ job.status = ExportJobStatus.RUNNING
1429
+ job.started_at = timezone.now()
1430
+ job.celery_task_id = getattr(getattr(self, "request", None), "id", "") or ""
1431
+ job.save(update_fields=["status", "started_at", "celery_task_id"])
1432
+
1433
+ try:
1434
+ storage_path, size = build_and_store_program_archive(job_id)
1435
+ except Exception as exc:
1436
+ retries = getattr(getattr(self, "request", None), "retries", 0)
1437
+ if retries < EXPORT_MAX_RETRIES:
1438
+ logger.warning("run_program_export: job %s failed, retrying", job_id, exc_info=True)
1439
+ raise self.retry(exc=exc, countdown=10 * (2**retries)) from exc # type: ignore[attr-defined]
1440
+ logger.exception("run_program_export: job %s failed permanently", job_id)
1441
+ ProgramExportJob.objects.filter(pk=job_id).update(
1442
+ status=ExportJobStatus.FAILED,
1443
+ error_detail=str(exc)[:2000],
1444
+ completed_at=timezone.now(),
1445
+ )
1446
+ return
1447
+
1448
+ retention = _export_retention_days()
1449
+ expires_at = timezone.now() + timedelta(days=retention) if retention is not None else None
1450
+ ProgramExportJob.objects.filter(pk=job_id).update(
1451
+ status=ExportJobStatus.SUCCESS,
1452
+ file_path=storage_path,
1453
+ file_size=size,
1454
+ expires_at=expires_at,
1455
+ completed_at=timezone.now(),
1456
+ error_detail="",
1457
+ )
1458
+
1459
+
1460
+ @idempotent_task(
1461
+ lock_key_template="drain_program_exports",
1462
+ lock_ttl=60,
1463
+ on_contention="skip",
1464
+ soft_time_limit=25,
1465
+ time_limit=30,
1466
+ acks_late=True,
1467
+ reject_on_worker_lost=True,
1468
+ name="projects.drain_program_exports",
1469
+ )
1470
+ def drain_program_exports(self: object) -> None:
1471
+ """Re-dispatch program export jobs stuck in ``pending`` (broker down at on_commit)."""
1472
+ _do_drain_program_exports()
1473
+
1474
+
1475
+ @idempotent_task(
1476
+ lock_key_template="purge_expired_program_exports",
1477
+ lock_ttl=120,
1478
+ on_contention="skip",
1479
+ soft_time_limit=55,
1480
+ time_limit=90,
1481
+ acks_late=True,
1482
+ reject_on_worker_lost=True,
1483
+ name="projects.purge_expired_program_exports",
1484
+ )
1485
+ def purge_expired_program_exports(self: object) -> None:
1486
+ """Delete program export jobs past their link expiry, and their stored archives."""
1487
+ _do_purge_expired_program_exports()
1488
+
1489
+
1490
+ def _do_drain_program_exports() -> None:
1491
+ from trueppm_api.apps.projects.models import ExportJobStatus, ProgramExportJob
1492
+
1493
+ orphan_cutoff = timezone.now() - timedelta(minutes=EXPORT_ORPHAN_WINDOW_MINUTES)
1494
+ stuck = list(
1495
+ ProgramExportJob.objects.filter(
1496
+ status=ExportJobStatus.PENDING,
1497
+ celery_task_id="",
1498
+ created_at__lt=orphan_cutoff,
1499
+ ).order_by("created_at")[:EXPORT_DRAIN_BATCH_SIZE]
1500
+ )
1501
+ if not stuck:
1502
+ return
1503
+ for job in stuck:
1504
+ try:
1505
+ run_program_export.delay(str(job.id))
1506
+ except SoftTimeLimitExceeded:
1507
+ raise
1508
+ except Exception: # pragma: no cover - broker still down, next tick retries
1509
+ logger.warning("drain_program_exports: broker still unavailable for %s", job.id)
1510
+ break
1511
+ logger.info("drain_program_exports: re-dispatched %d job(s)", len(stuck))
1512
+
1513
+
1514
+ def _do_purge_expired_program_exports() -> None:
1515
+ from django.core.files.storage import default_storage
1516
+
1517
+ from trueppm_api.apps.projects.models import ProgramExportJob
1518
+
1519
+ retention = _export_retention_days()
1520
+ if retention is None: # retention disabled — keep archives indefinitely
1521
+ return
1522
+ # Bounded per run (#2615). Each iteration is a storage DELETE plus a row
1523
+ # DELETE, and the task carries a 55 s soft limit — an unbounded walk over a
1524
+ # backlog larger than one window is SIGKILLed partway rather than draining,
1525
+ # so the same oversized backlog is retried from the start on every tick and
1526
+ # never shrinks. A slice drains it incrementally instead: whatever is left
1527
+ # is picked up by the next scheduled run.
1528
+ expired = ProgramExportJob.objects.filter(expires_at__lt=timezone.now()).order_by("expires_at")
1529
+ count = 0
1530
+ for job in expired[:PURGE_BATCH_SIZE]:
1531
+ if job.file_path:
1532
+ try:
1533
+ default_storage.delete(job.file_path)
1534
+ except OSError: # pragma: no cover - storage drift, still drop the row
1535
+ logger.warning(
1536
+ "purge_expired_program_exports: could not delete file for %s", job.id
1537
+ )
1538
+ job.delete()
1539
+ count += 1
1540
+ if count:
1541
+ logger.info("purge_expired_program_exports: deleted %d expired export(s)", count)
1542
+ if count == PURGE_BATCH_SIZE and (remaining := expired.count()):
1543
+ logger.info(
1544
+ "purge_expired_program_exports: batch full, %d expired export(s) remain for the "
1545
+ "next run",
1546
+ remaining,
1547
+ )
1548
+
1549
+
1550
+ # ---------------------------------------------------------------------------
1551
+ # Async program seed import (ADR-0726, #2574) — the mirror of the export tasks
1552
+ # above. Same durable-execution shape; the payload travels through storage.
1553
+ # ---------------------------------------------------------------------------
1554
+
1555
+ IMPORT_MAX_RETRIES = 3 # ADR-0726 §Durable Execution item 8
1556
+ IMPORT_ORPHAN_WINDOW_MINUTES = 10 # ADR-0726 §Durable Execution item 3
1557
+ IMPORT_DRAIN_BATCH_SIZE = 10
1558
+
1559
+
1560
+ def _import_retention_days() -> int | None:
1561
+ """Days a terminal import job (and its stored payload) is kept; ``None`` disables."""
1562
+ from django.conf import settings
1563
+
1564
+ value = getattr(settings, "TRUEPPM_IMPORT_RETENTION_DAYS", 7)
1565
+ return None if value in (None, 0) else int(value)
1566
+
1567
+
1568
+ @shared_task( # type: ignore[untyped-decorator]
1569
+ bind=True,
1570
+ max_retries=IMPORT_MAX_RETRIES,
1571
+ soft_time_limit=1800,
1572
+ time_limit=1860,
1573
+ acks_late=True,
1574
+ reject_on_worker_lost=True,
1575
+ name="projects.run_program_import",
1576
+ )
1577
+ def run_program_import(self: object, job_id: str) -> None:
1578
+ """Build the subtree for a queued seed import (ADR-0726, #2574).
1579
+
1580
+ The request already did the parts that must be synchronous: it validated the
1581
+ document, resolved and performed any confirmed replacement, and created the
1582
+ program shell. This task only fills that shell, which is why it is *purely
1583
+ additive* — and why the claim below is load-bearing rather than decorative.
1584
+ A duplicate delivery (drain re-dispatch, ``acks_late`` redelivery after a
1585
+ worker loss) would otherwise run the whole build a second time into the same
1586
+ program and double every task, dependency, and sprint; ``Task`` carries no
1587
+ ``(project, wbs_path)`` unique constraint to catch it.
1588
+
1589
+ Only transient faults retry. A validation or referential failure is
1590
+ deterministic — and the request already rejected those synchronously — so it
1591
+ goes straight to ``failed`` with the diagnostics on the row.
1592
+
1593
+ A failed job deliberately leaves the empty program shell in place rather than
1594
+ cleaning it up: the replaced subtree is in Trash, and the Owner needs both the
1595
+ shell and the failed job row to reason about what happened.
1596
+ """
1597
+ import json
1598
+
1599
+ from django.core.files.storage import default_storage
1600
+
1601
+ from trueppm_api.apps.projects.models import ImportJobStatus, ProgramImportJob
1602
+ from trueppm_api.apps.projects.seed import SeedValidationError
1603
+ from trueppm_api.apps.projects.seed import import_seed as run_import
1604
+
1605
+ with transaction.atomic():
1606
+ job = ProgramImportJob.objects.select_for_update().filter(pk=job_id).first()
1607
+ if job is None:
1608
+ logger.warning("run_program_import: job %s not found", job_id)
1609
+ return
1610
+ if job.status not in (ImportJobStatus.PENDING, ImportJobStatus.RUNNING):
1611
+ logger.info("run_program_import: job %s already %s, skipping", job_id, job.status)
1612
+ return
1613
+ job.status = ImportJobStatus.RUNNING
1614
+ job.started_at = timezone.now()
1615
+ job.celery_task_id = getattr(getattr(self, "request", None), "id", "") or ""
1616
+ job.save(update_fields=["status", "started_at", "celery_task_id"])
1617
+
1618
+ program = job.program
1619
+
1620
+ # ``requested_by`` is SET_NULL, so an account deleted between the 202 and
1621
+ # this run leaves the importer with no owner to build memberships against.
1622
+ # It fails safely today — the importer raises rather than granting anything
1623
+ # to ``None`` — but it does so as an unhandled exception that burns all three
1624
+ # retries first and lands a traceback string in ``error_detail``. The
1625
+ # condition is deterministic, so refuse it up front with a reason the
1626
+ # polling client can render (#2615).
1627
+ if job.requested_by_id is None:
1628
+ logger.warning("run_program_import: job %s has no requester, refusing", job_id)
1629
+ _fail_import_job(
1630
+ job_id,
1631
+ "The account that requested this import no longer exists. "
1632
+ "Re-import as an existing user.",
1633
+ )
1634
+ return
1635
+
1636
+ try:
1637
+ with default_storage.open(job.file_path, "rb") as handle:
1638
+ payload = json.loads(handle.read().decode("utf-8"))
1639
+ except Exception:
1640
+ # The payload is gone or unreadable: deterministic, so never retry. The
1641
+ # reason is logged, not persisted — a storage exception renders the
1642
+ # absolute key path, and ``error_detail`` is served verbatim to any
1643
+ # program Admin while ``file_path`` is deliberately withheld from the
1644
+ # same serializer.
1645
+ logger.exception("run_program_import: payload unreadable for job %s", job_id)
1646
+ _fail_import_job(job_id, "The uploaded seed could no longer be read. Re-import the file.")
1647
+ return
1648
+
1649
+ try:
1650
+ # ``target_program`` adopts the shell the request created, which also
1651
+ # tells the importer to skip its own replace pass entirely — the
1652
+ # replacement, if any, already happened inside the request the operator
1653
+ # authorized (ADR-0726 §4).
1654
+ run_import(
1655
+ payload,
1656
+ owner=job.requested_by,
1657
+ create_users=False,
1658
+ target_program=program,
1659
+ adopt_keys_from=job.replaced_project_ids,
1660
+ )
1661
+ except SeedValidationError as exc:
1662
+ _fail_import_job(job_id, "; ".join(exc.errors)[:2000])
1663
+ return
1664
+ except Exception as exc:
1665
+ retries = getattr(getattr(self, "request", None), "retries", 0)
1666
+ if retries < IMPORT_MAX_RETRIES:
1667
+ logger.warning("run_program_import: job %s failed, retrying", job_id, exc_info=True)
1668
+ raise self.retry(exc=exc, countdown=10 * (2**retries)) from exc # type: ignore[attr-defined]
1669
+ logger.exception("run_program_import: job %s failed permanently", job_id)
1670
+ _fail_import_job(job_id, str(exc)[:2000])
1671
+ return
1672
+
1673
+ retention = _import_retention_days()
1674
+ expires_at = timezone.now() + timedelta(days=retention) if retention is not None else None
1675
+ ProgramImportJob.objects.filter(pk=job_id).update(
1676
+ status=ImportJobStatus.SUCCESS,
1677
+ result_summary=_import_summary(program),
1678
+ expires_at=expires_at,
1679
+ completed_at=timezone.now(),
1680
+ error_detail="",
1681
+ )
1682
+
1683
+
1684
+ def _import_summary(program: Any) -> dict[str, int]:
1685
+ """Entity counts the polling client renders once the job reaches ``success``."""
1686
+ from trueppm_api.apps.projects.models import Dependency, Project, Sprint, Task
1687
+
1688
+ project_ids = list(
1689
+ Project.objects.filter(program=program, is_deleted=False).values_list("pk", flat=True)
1690
+ )
1691
+ return {
1692
+ "projects": len(project_ids),
1693
+ "tasks": Task.objects.filter(project_id__in=project_ids, is_deleted=False).count(),
1694
+ "sprints": Sprint.objects.filter(project_id__in=project_ids, is_deleted=False).count(),
1695
+ "dependencies": Dependency.objects.filter(
1696
+ predecessor__project_id__in=project_ids, is_deleted=False
1697
+ ).count(),
1698
+ }
1699
+
1700
+
1701
+ def _fail_import_job(job_id: str, detail: str) -> None:
1702
+ """Mark a job ``failed`` with a reason the polling client can render.
1703
+
1704
+ Persisted rather than only logged: an async import failure has to be visible
1705
+ on the surface that launched it, which is the whole point of returning a job
1706
+ handle instead of a 504.
1707
+ """
1708
+ from trueppm_api.apps.projects.models import ImportJobStatus, ProgramImportJob
1709
+
1710
+ retention = _import_retention_days()
1711
+ expires_at = timezone.now() + timedelta(days=retention) if retention is not None else None
1712
+ ProgramImportJob.objects.filter(pk=job_id).update(
1713
+ status=ImportJobStatus.FAILED,
1714
+ error_detail=detail or "The seed could not be imported.",
1715
+ expires_at=expires_at,
1716
+ completed_at=timezone.now(),
1717
+ )
1718
+
1719
+
1720
+ @idempotent_task(
1721
+ lock_key_template="drain_program_imports",
1722
+ lock_ttl=60,
1723
+ on_contention="skip",
1724
+ soft_time_limit=25,
1725
+ time_limit=30,
1726
+ acks_late=True,
1727
+ reject_on_worker_lost=True,
1728
+ name="projects.drain_program_imports",
1729
+ )
1730
+ def drain_program_imports(self: object) -> None:
1731
+ """Re-dispatch seed import jobs stuck in ``pending`` (broker down at on_commit)."""
1732
+ _do_drain_program_imports()
1733
+
1734
+
1735
+ @idempotent_task(
1736
+ lock_key_template="purge_expired_program_imports",
1737
+ lock_ttl=120,
1738
+ on_contention="skip",
1739
+ soft_time_limit=55,
1740
+ time_limit=90,
1741
+ acks_late=True,
1742
+ reject_on_worker_lost=True,
1743
+ name="projects.purge_expired_program_imports",
1744
+ )
1745
+ def purge_expired_program_imports(self: object) -> None:
1746
+ """Delete terminal seed import jobs past retention, and their stored payloads."""
1747
+ _do_purge_expired_program_imports()
1748
+
1749
+
1750
+ def _do_drain_program_imports() -> None:
1751
+ from trueppm_api.apps.projects.models import ImportJobStatus, ProgramImportJob
1752
+
1753
+ # Only rows whose on_commit dispatch demonstrably never landed: still
1754
+ # pending, never assigned a task id, and older than the window. A row inside
1755
+ # an open on_commit callback is invisible until commit, so the age floor is
1756
+ # what stops the drain racing an in-flight upload it would double-dispatch.
1757
+ orphan_cutoff = timezone.now() - timedelta(minutes=IMPORT_ORPHAN_WINDOW_MINUTES)
1758
+ stuck = list(
1759
+ ProgramImportJob.objects.filter(
1760
+ status=ImportJobStatus.PENDING,
1761
+ celery_task_id="",
1762
+ created_at__lt=orphan_cutoff,
1763
+ ).order_by("created_at")[:IMPORT_DRAIN_BATCH_SIZE]
1764
+ )
1765
+ if not stuck:
1766
+ return
1767
+ for job in stuck:
1768
+ try:
1769
+ run_program_import.delay(str(job.id))
1770
+ except SoftTimeLimitExceeded:
1771
+ raise
1772
+ except Exception: # pragma: no cover - broker still down, next tick retries
1773
+ logger.warning("drain_program_imports: broker still unavailable for %s", job.id)
1774
+ break
1775
+ logger.info("drain_program_imports: re-dispatched %d job(s)", len(stuck))
1776
+
1777
+
1778
+ def _do_purge_expired_program_imports() -> None:
1779
+ from django.core.files.storage import default_storage
1780
+
1781
+ from trueppm_api.apps.projects.models import ImportJobStatus, ProgramImportJob
1782
+
1783
+ retention = _import_retention_days()
1784
+ if retention is None: # retention disabled — keep rows indefinitely
1785
+ return
1786
+ # Bounded per run for the same reason as the export purge above (#2615).
1787
+ expired = ProgramImportJob.objects.filter(expires_at__lt=timezone.now()).order_by("expires_at")
1788
+ count = 0
1789
+ reaped = 0
1790
+ for job in expired[:PURGE_BATCH_SIZE]:
1791
+ if job.file_path:
1792
+ try:
1793
+ default_storage.delete(job.file_path)
1794
+ except OSError: # pragma: no cover - storage drift, still drop the row
1795
+ logger.warning(
1796
+ "purge_expired_program_imports: could not delete payload for %s", job.id
1797
+ )
1798
+ # A failed import deliberately keeps its program shell so the Owner can
1799
+ # reason about what happened (ADR-0726 §Durable Execution 8). That
1800
+ # reasoning needs the *job row*, and the job row is what this loop is
1801
+ # deleting — so past retention the shell is no longer evidence of
1802
+ # anything, it is only an empty program in the Owner's list that nothing
1803
+ # reaps. At the seed_import throttle's 6/min that is ~8,600 of them per
1804
+ # account per day. Retire it here, at the same moment its explanation
1805
+ # goes away, and only if it is still empty: anything the Owner has since
1806
+ # built under it makes it theirs, not the importer's leftover.
1807
+ # One transaction per job, not one for the batch: a storage error on the
1808
+ # next row must not roll back the rows already reaped, and the whole
1809
+ # point of the batch is that it can be interrupted and resumed. The
1810
+ # atomic block matters because ``soft_delete`` is two statements — the
1811
+ # row UPDATE and the ``deleted_version`` stamp the sync tombstone is read
1812
+ # from — and this runs in a beat task with no ambient transaction, so
1813
+ # without it a crash between them leaves a tombstone sync cannot see.
1814
+ with transaction.atomic():
1815
+ if job.status == ImportJobStatus.FAILED and _reap_empty_import_shell(job):
1816
+ reaped += 1
1817
+ job.delete()
1818
+ count += 1
1819
+ if count:
1820
+ logger.info("purge_expired_program_imports: deleted %d expired import(s)", count)
1821
+ if reaped:
1822
+ logger.info(
1823
+ "purge_expired_program_imports: retired %d empty failed-import shell(s)", reaped
1824
+ )
1825
+ if count == PURGE_BATCH_SIZE and (remaining := expired.count()):
1826
+ logger.info(
1827
+ "purge_expired_program_imports: batch full, %d expired import(s) remain for the "
1828
+ "next run",
1829
+ remaining,
1830
+ )
1831
+
1832
+
1833
+ def _reap_empty_import_shell(job: Any) -> bool:
1834
+ """Tombstone the empty program shell a failed import left behind (#2615).
1835
+
1836
+ Soft-deleted rather than hard-deleted: the program row's ``server_version``
1837
+ bump is what reaches offline sync consumers, and a hard delete would strand
1838
+ a client that had already seen the shell — the same reasoning that makes
1839
+ ``soft_delete_program_subtree`` tombstone the program instead of removing it.
1840
+ There is no program Trash (#2587), so this is not recoverable through the UI;
1841
+ that is why every guard below is a *reason not to touch it*.
1842
+
1843
+ Returns True when a shell was retired.
1844
+ """
1845
+ from trueppm_api.apps.projects.models import (
1846
+ ImportJobStatus,
1847
+ Program,
1848
+ ProgramImportJob,
1849
+ Project,
1850
+ )
1851
+
1852
+ program = Program.objects.filter(pk=job.program_id, is_deleted=False).first()
1853
+ if program is None: # already gone, or already tombstoned by a replace
1854
+ return False
1855
+ if Project.objects.filter(program_id=program.pk, is_deleted=False).exists():
1856
+ return False
1857
+ # A later import that succeeded into the same shell makes it real, even
1858
+ # though *this* job failed.
1859
+ if (
1860
+ ProgramImportJob.objects.filter(program_id=program.pk)
1861
+ .exclude(pk=job.pk)
1862
+ .exclude(status=ImportJobStatus.FAILED)
1863
+ .exists()
1864
+ ):
1865
+ return False
1866
+ # The ``server_version`` bump ``soft_delete`` writes is the delivery
1867
+ # mechanism: an offline client learns the shell is gone from its next sync
1868
+ # delta, which is the same path that carries every other program tombstone.
1869
+ #
1870
+ # Deliberately **no** ``program_deleted`` broadcast, unlike
1871
+ # ``soft_delete_program_subtree``. That one runs in a request a user is
1872
+ # watching; this runs in a nightly sweep, weeks later, over a shell that by
1873
+ # definition nobody has open. And ``broadcast_board_event`` is synchronous
1874
+ # (``async_to_sync`` over the channel layer) with no enclosing atomic block
1875
+ # here, so ``on_commit`` would fire it inline — up to ``PURGE_BATCH_SIZE``
1876
+ # blocking round-trips inside the same 55 s budget the batching above exists
1877
+ # to protect, for an event that no consumer can currently receive anyway
1878
+ # (program groups have no ``group_add``, #836).
1879
+ program.soft_delete()
1880
+ return True
1881
+
1882
+
1883
+ # ---------------------------------------------------------------------------
1884
+ # Schedule outline batch operation undo ledgers (ADR-0810, #2756)
1885
+ # ---------------------------------------------------------------------------
1886
+ # PasteManyOperation and CascadeClassificationOperation, not CsvImportRequest —
1887
+ # that table already has its own retention story (task_batch_services.py's
1888
+ # import-fix section). Shaped like purge_expired_project_exports above, not the
1889
+ # consolidated ADR-0173 retention coordinator (apps/observability): that
1890
+ # coordinator's RETENTION_SPECS is a deliberately curated, count-asserted set of
1891
+ # six tables surfaced in an operator-facing editor, and folding a seventh in
1892
+ # would be scope beyond what #2756 asked for. A plain settings-driven purge,
1893
+ # same shape as the export/import job purges already in this file, is
1894
+ # consistent with the (lighter) precedent those set.
1895
+
1896
+
1897
+ def _batch_operation_retention_days() -> int | None:
1898
+ from django.conf import settings
1899
+
1900
+ return getattr(settings, "TRUEPPM_BATCH_OPERATION_RETENTION_DAYS", 30)
1901
+
1902
+
1903
+ @idempotent_task(
1904
+ lock_key_template="purge_expired_batch_operations",
1905
+ lock_ttl=120,
1906
+ on_contention="skip",
1907
+ soft_time_limit=55,
1908
+ time_limit=90,
1909
+ acks_late=True,
1910
+ reject_on_worker_lost=True,
1911
+ name="projects.purge_expired_batch_operations",
1912
+ )
1913
+ def purge_expired_batch_operations(self: object) -> None:
1914
+ """Delete paste-many/cascade undo ledger rows past retention, undone or not."""
1915
+ _do_purge_expired_batch_operations()
1916
+
1917
+
1918
+ def _structural_operation_retention_days() -> int | None:
1919
+ """Structural rows get their own, shorter window (ADR-0880 Sec.9).
1920
+
1921
+ A structural act fires on every indent and every drag, so an afternoon of outlining
1922
+ is hundreds of rows where a paste-many is a handful. Sharing the 30-day batch
1923
+ window would accumulate an order of magnitude more rows for a horizon nobody uses:
1924
+ the undo affordance is session-scoped (the session trail caps at 10 entries), so
1925
+ 7 days comfortably outlives any session while keeping the table small.
1926
+ """
1927
+ from django.conf import settings
1928
+
1929
+ return getattr(settings, "TRUEPPM_STRUCTURAL_OPERATION_RETENTION_DAYS", 7)
1930
+
1931
+
1932
+ def _do_purge_expired_batch_operations() -> None:
1933
+ from trueppm_api.apps.projects.models import (
1934
+ CascadeClassificationOperation,
1935
+ PasteManyOperation,
1936
+ StructuralOperation,
1937
+ )
1938
+
1939
+ retention = _batch_operation_retention_days()
1940
+ paste_deleted = cascade_deleted = structural_deleted = 0
1941
+ if retention is not None: # None disables retention — keep rows indefinitely
1942
+ cutoff = timezone.now() - timedelta(days=retention)
1943
+ paste_deleted, _ = PasteManyOperation.objects.filter(created_at__lt=cutoff).delete()
1944
+ cascade_deleted, _ = CascadeClassificationOperation.objects.filter(
1945
+ created_at__lt=cutoff
1946
+ ).delete()
1947
+
1948
+ structural_retention = _structural_operation_retention_days()
1949
+ if structural_retention is not None:
1950
+ structural_cutoff = timezone.now() - timedelta(days=structural_retention)
1951
+ structural_deleted, _ = StructuralOperation.objects.filter(
1952
+ created_at__lt=structural_cutoff
1953
+ ).delete()
1954
+
1955
+ total = paste_deleted + cascade_deleted + structural_deleted
1956
+ if total:
1957
+ logger.info(
1958
+ "purge_expired_batch_operations: deleted %d paste-many + %d cascade "
1959
+ "+ %d structural row(s)",
1960
+ paste_deleted,
1961
+ cascade_deleted,
1962
+ structural_deleted,
1963
+ )
1964
+
1965
+
1966
+ # ---------------------------------------------------------------------------
1967
+ # Template application (ADR-0789, #2729)
1968
+ # ---------------------------------------------------------------------------
1969
+ # Celery's autodiscover_tasks() only imports ``<app>/tasks.py``, so a task defined
1970
+ # in a sibling module never registers and its Beat entry silently resolves to
1971
+ # nothing — the drain would appear scheduled and never run. Re-exported here so
1972
+ # the two template tasks are discovered, while their implementation stays in
1973
+ # ``template_tasks.py`` next to the rest of the template code.
1974
+ from trueppm_api.apps.projects.template_tasks import ( # noqa: E402
1975
+ apply_template,
1976
+ drain_template_apply_queue,
1977
+ )
1978
+
1979
+ __all__ = ["apply_template", "drain_template_apply_queue"]