@@ -207,7 +207,44 @@ def jira_status_reconciliation_task(*args, **kwargs):
207207 return jira_status_reconciliation (* args , ** kwargs )
208208
209209
210- @app .task
210+
211+ @app .task (bind = True )
212+ def async_import_history_cleanup (* args , ** kwargs ):
213+ with pghistory .context (source = "import_history_cleanup_task" ):
214+ _async_import_history_cleanup_impl ()
215+
216+
217+ def _async_import_history_cleanup_impl ():
218+ """Delete oldest Test_Import records when a test exceeds max_import_history."""
219+ try :
220+ system_settings = System_Settings .objects .get ()
221+ max_history = system_settings .max_import_history
222+ max_per_run = settings .IMPORT_HISTORY_MAX_PER_OBJECT
223+ except System_Settings .DoesNotExist :
224+ return
225+
226+ if max_history is None :
227+ logger .info ("skipping import history cleanup: max_import_history not configured" )
228+ return
229+
230+ logger .info ("cleaning up import history (max per test: %s, max deletes per run: %s)" , max_history , max_per_run )
231+
232+ tests_with_excess = Test_Import .objects \
233+ .values ("test" ) \
234+ .annotate (import_count = Count ("id" )) \
235+ .filter (import_count__gt = max_history )[:max_per_run ]
236+
237+ total_deleted_count = 0
238+ for entry in tests_with_excess :
239+ test_id = entry ["test" ]
240+ imports = Test_Import .objects .filter (test_id = test_id ).order_by ("created" )
241+ excess_count = entry ["import_count" ] - max_history
242+ for test_import in imports [:excess_count ]:
243+ logger .debug ("deleting Test_Import id %s for test %s" , test_import .id , test_id )
244+ test_import .delete ()
245+ total_deleted_count += 1
246+
247+ logger .info ("total import history records deleted: %s" , total_deleted_count )
211248def fix_loop_duplicates_task (* args , ** kwargs ):
212249 # Wrap with pghistory context for audit trail
213250 with pghistory .context (source = "fix_loop_duplicates" ):
0 commit comments