from corehq.form_processor.reprocess import reprocess_unfinished_stub
from corehq.util.celery_utils import no_result_task
from corehq.util.datadog.gauges import datadog_counter
from couchforms.models import UnfinishedSubmissionStub


SUBMISSION_REPROCESS_CELERY_QUEUE = 'submission_reprocessing_queue'


@no_result_task(queue=SUBMISSION_REPROCESS_CELERY_QUEUE, acks_late=True)
def reprocess_submission(submssion_stub_id):
    try:
        stub = UnfinishedSubmissionStub.objects.get(id=submssion_stub_id)
    except UnfinishedSubmissionStub.DoesNotExist:
        return

    reprocess_unfinished_stub(stub)
    datadog_counter('commcare.submission_reprocessing.count')

@@ -225,16 +225,62 @@
 ionStub%0A
+from dimagi.utils.couch import CriticalSection
 %0A%0ASUBMIS
@@ -461,16 +461,93 @@
 ub_id):%0A
+    with CriticalSection(%5B'reprocess_submission_' + submssion_stub_id%5D):%0A    
     try:
@@ -547,16 +547,20 @@
    try:%0A
+    
         
@@ -625,16 +625,20 @@
 tub_id)%0A
+    
     exce
@@ -691,16 +691,20 @@
     
+    
 return%0A%0A
     
@@ -699,16 +699,20 @@
 return%0A%0A
+    
     repr
@@ -739,16 +739,20 @@
 b(stub)%0A
+    
     data

add critical section