internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: rucio/rucio

Issue:
gfal stat does checksum calls for all checksums
Motivation
----------
The stat command of gfal currently does a checksum call for each checksum in `GLOBALLY_SUPPORTED_CHECKSUMS` this currrently results in a very long processing time for SRM which finally times out after ~30 minutes.


Modification
------------
First try the `PREFERRED_CHCEKSUM` and if this validates successfully don't try the other checksums.




Discussion:

Resolving patch:
diff --git a/lib/rucio/rse/protocols/gfal.py b/lib/rucio/rse/protocols/gfal.py
--- a/lib/rucio/rse/protocols/gfal.py
+++ b/lib/rucio/rse/protocols/gfal.py
@@ -41,7 +41,7 @@
 
 from rucio.common import exception, config
 from rucio.common.constraints import STRING_TYPES
-from rucio.common.utils import GLOBALLY_SUPPORTED_CHECKSUMS
+from rucio.common.utils import GLOBALLY_SUPPORTED_CHECKSUMS, PREFERRED_CHECKSUM
 from rucio.rse.protocols import protocol
 
 try:
@@ -334,13 +334,15 @@ def stat(self, path):
 
             :raises ServiceUnavailable: if some generic error occured in the library.
 
-            :returns: a dict with two keys, filesize and adler32 of the file provided in path.
+            :returns: a dict with two keys, filesize and an element of GLOBALLY_SUPPORTED_CHECKSUMS.
         """
         ret = {}
         ctx = self.__ctx
 
+        path = str(path)
+
         try:
-            stat_str = str(ctx.stat(str(path)))
+            stat_str = str(ctx.stat(path))
         except Exception as error:
             msg = 'Error while processing gfal stat call. Error: %s'
             raise exception.ServiceUnavailable(msg % str(error))
@@ -350,22 +352,25 @@ def stat(self, path):
             msg = 'gfal stat call result has unknown format. Result: %s'
             raise exception.ServiceUnavailable(msg % stat_str)
 
-        ret['filesize'] = stat_str.split()[7]
+        ret['filesize'] = stats[7]
 
-        verified = False
         message = "\n"
+        try:
+            ret[PREFERRED_CHECKSUM] = ctx.checksum(path, str(PREFERRED_CHECKSUM.capitalize()))
+            return ret
+        except Exception as error:
+            message += 'Error while processing gfal checksum call (%s). Error: %s \n' % (PREFERRED_CHECKSUM, str(error))
 
         for checksum_name in GLOBALLY_SUPPORTED_CHECKSUMS:
+            if checksum_name == PREFERRED_CHECKSUM:
+                continue
             try:
-                ret[checksum_name] = ctx.checksum(str(path), str(checksum_name.capitalize()))
-                verified = True
+                ret[checksum_name] = ctx.checksum(path, str(checksum_name.capitalize()))
+                return ret
             except Exception as error:
                 message += 'Error while processing gfal checksum call (%s). Error: %s \n' % (checksum_name, str(error))
 
-        if not verified:
-            raise exception.RSEChecksumUnavailable(message)
-
-        return ret
+        raise exception.RSEChecksumUnavailable(message)
 
     def __gfal2_cancel(self):
         """


Test patch:
Repository: rucio/rucio

Issue:
Temporary unavailable files in bad_pfns not removed if processed after expiration date 
Motivation
----------
Minos : Temporary unavailable files in bad_pfns not removed if processed after expiration date 







Discussion:

Resolving patch:
diff --git a/lib/rucio/daemons/badreplicas/minos.py b/lib/rucio/daemons/badreplicas/minos.py
--- a/lib/rucio/daemons/badreplicas/minos.py
+++ b/lib/rucio/daemons/badreplicas/minos.py
@@ -28,6 +28,7 @@
 import threading
 import time
 
+from datetime import datetime
 from sys import stdout, argv
 
 from rucio.db.sqla.constants import BadFilesStatus, BadPFNStatus, ReplicaState
@@ -227,6 +228,9 @@ def minos(bulk=1000, once=False, sleep_time=60):
                                     if rep['rse_id'] in unavailable_states:
                                         logging.info(prepend_str + '%s is in unavailable state. Will be removed from the list of bad PFNs' % str(rep['pfn']))
                                         bulk_delete_bad_pfns(pfns=[rep['pfn']], session=None)
+                                    elif expires_at < datetime.now():
+                                        logging.info('%s PFN %s expiration time (%s) is older than now and is not in unavailable state. Removing the PFNs from bad_pfns', prepend_str, str(rep['pfn']), expires_at)
+                                        bulk_delete_bad_pfns(pfns=[rep['pfn']], session=None)
                                 except (DataIdentifierNotFound, ReplicaNotFound) as error:
                                     logging.error(prepend_str + 'Will remove %s from the list of bad PFNs' % str(rep['pfn']))
                                     bulk_delete_bad_pfns(pfns=[rep['pfn']], session=None)


Test patch:
Repository: rucio/rucio

Issue:
Conveyor Finisher fails to retry requests in the "protocol mismatch" state
Hi,

Even with conveyor.retry_protocol_mismatches set to True, the finisher seems to fail to retry protocol mismatch errors at all (it just ignores them). This seems to be handled by these lines:
https://github.com/rucio/rucio/blob/916987976a1f994a64e4ef3dce837b49141a8f1b/lib/rucio/daemons/conveyor/finisher.py#L215
https://github.com/rucio/rucio/blob/916987976a1f994a64e4ef3dce837b49141a8f1b/lib/rucio/daemons/conveyor/finisher.py#L278

But it never gets any requests in the MISMATCH_SCHEME state, seemingly because this constant isn't included in the main database query filter here:
https://github.com/rucio/rucio/blob/916987976a1f994a64e4ef3dce837b49141a8f1b/lib/rucio/daemons/conveyor/finisher.py#L121-L129

Would it be possible for this to be fixed?

Regards,
Simon



Discussion:

Resolving patch:
diff --git a/lib/rucio/daemons/conveyor/finisher.py b/lib/rucio/daemons/conveyor/finisher.py
--- a/lib/rucio/daemons/conveyor/finisher.py
+++ b/lib/rucio/daemons/conveyor/finisher.py
@@ -17,7 +17,7 @@
 # - Mario Lassnig <mario.lassnig@cern.ch>, 2015-2019
 # - Vincent Garonne <vgaronne@gmail.com>, 2015-2018
 # - Martin Barisits <martin.barisits@cern.ch>, 2015-2019
-# - Cedric Serfon <cedric.serfon@cern.ch>, 2017-2019
+# - Cedric Serfon <cedric.serfon@cern.ch>, 2017-2020
 # - Hannes Hansen <hannes.jakob.hansen@cern.ch>, 2018
 # - Robert Illingworth <illingwo@fnal.gov>, 2019
 # - Andrew Lister <andrew.lister@stfc.ac.uk>, 2019
@@ -119,8 +119,10 @@ def finisher(once=False, sleep_time=60, activities=None, bulk=100, db_bulk=1000)
                 logging.debug('%s Working on activity %s', prepend_str, activity)
                 time1 = time.time()
                 reqs = request_core.get_next(request_type=[RequestType.TRANSFER, RequestType.STAGEIN, RequestType.STAGEOUT],
-                                             state=[RequestState.DONE, RequestState.FAILED, RequestState.LOST, RequestState.SUBMITTING,
-                                                    RequestState.SUBMISSION_FAILED, RequestState.NO_SOURCES, RequestState.ONLY_TAPE_SOURCES],
+                                             state=[RequestState.DONE, RequestState.FAILED,
+                                                    RequestState.LOST, RequestState.SUBMITTING,
+                                                    RequestState.SUBMISSION_FAILED, RequestState.NO_SOURCES,
+                                                    RequestState.ONLY_TAPE_SOURCES, RequestState.MISMATCH_SCHEME],
                                              limit=db_bulk,
                                              older_than=datetime.datetime.utcnow(),
                                              total_workers=heart_beat['nr_threads'] - 1,


Test patch:
Repository: rucio/rucio

Issue:
Reaper 2.0 is creating error traces for SourceNotFound
Motivation
----------

For example:
```Thread [17/20] : Deletion NOTFOUND of HOST.1 as IP|HOST:PORT/PATH on MWT2_DATADISK```
This is different from the previous Reaper implementation. Such traces reduce the deletion efficiency as we are currently calculating it in our monitoring. Is it intentional?

Modification
------------

Potentially do not submit traces for `SourceNotFound`.


Discussion:
Need discussion
This issue was tagged erroneously. It is not related to the thread information contained in the messages.

Resolving patch:
diff --git a/lib/rucio/daemons/reaper/reaper2.py b/lib/rucio/daemons/reaper/reaper2.py
--- a/lib/rucio/daemons/reaper/reaper2.py
+++ b/lib/rucio/daemons/reaper/reaper2.py
@@ -19,7 +19,7 @@
 # - Wen Guan <wguan.icedew@gmail.com>, 2016
 # - Hannes Hansen <hannes.jakob.hansen@cern.ch>, 2018-2019
 # - Dimitrios Christidis <dimitrios.christidis@cern.ch>, 2019
-# - Cedric Serfon <cedric.serfon@cern.ch>, 2019
+# - Cedric Serfon <cedric.serfon@cern.ch>, 2019-2020
 # - Andrew Lister <andrew.lister@stfc.ac.uk>, 2019
 # - Brandon White <bjwhite@fnal.gov>, 2019
 #
@@ -48,7 +48,6 @@
 from dogpile.cache.api import NO_VALUE
 from sqlalchemy.exc import DatabaseError, IntegrityError
 
-from rucio.db.sqla.constants import ReplicaState
 from rucio.common.config import config_get
 from rucio.common.exception import (DatabaseException, RSENotFound, ConfigNotFound, ReplicaUnAvailable, ReplicaNotFound, ServiceUnavailable, RSEAccessDenied, ResourceTemporaryUnavailable, SourceNotFound)
 from rucio.common.utils import chunks
@@ -164,9 +163,6 @@ def delete_from_storage(replicas, prot, rse_info, staging_areas, prepend_str):
                 err_msg = 'Deletion NOTFOUND of %s:%s as %s on %s' % (replica['scope'], replica['name'], replica['pfn'], rse_name)
                 logging.warning('%s %s', prepend_str, err_msg)
                 deleted_files.append({'scope': replica['scope'], 'name': replica['name']})
-                if replica['state'] == ReplicaState.AVAILABLE:
-                    deletion_dict['reason'] = str(err_msg)
-                    add_message('deletion-failed', deletion_dict)
 
             except (ServiceUnavailable, RSEAccessDenied, ResourceTemporaryUnavailable) as error:
                 logging.warning('%s Deletion NOACCESS of %s:%s as %s on %s: %s', prepend_str, replica['scope'], replica['name'], replica['pfn'], rse_name, str(error))


Test patch:
Repository: rucio/rucio

Issue:
Crash when enabling multihop mode
Motivation
----------
The submitter crash when enabling multihop mode








Discussion:

Resolving patch:
diff --git a/lib/rucio/core/request.py b/lib/rucio/core/request.py
--- a/lib/rucio/core/request.py
+++ b/lib/rucio/core/request.py
@@ -12,7 +12,7 @@
 # - Wen Guan, <wen.guan@cern.ch>, 2014-2016
 # - Joaquin Bogado, <jbogadog@cern.ch>, 2016
 # - Thomas Beermann, <thomas.beermann@cern.ch>, 2016
-# - Cedric Serfon, <cedric.serfon@cern.ch>, 2017-2019
+# - Cedric Serfon, <cedric.serfon@cern.ch>, 2017-2020
 # - Hannes Hansen, <hannes.jakob.hansen@cern.ch>, 2018-2019
 # - Andrew Lister, <andrew.lister@stfc.ac.uk>, 2019
 #
@@ -485,6 +485,7 @@ def set_request_state(request_id, new_state, transfer_id=None, transferred_at=No
 
     record_counter('core.request.set_request_state')
 
+    rowcount = 0
     try:
         update_items = {'state': new_state, 'updated_at': datetime.datetime.utcnow()}
         if transferred_at:
diff --git a/lib/rucio/core/transfer.py b/lib/rucio/core/transfer.py
--- a/lib/rucio/core/transfer.py
+++ b/lib/rucio/core/transfer.py
@@ -8,7 +8,7 @@
 # Authors:
 # - Martin Barisits, <martin.barisits@cern.ch>, 2017-2018
 # - Mario Lassnig, <mario.lassnig@cern.ch>, 2017-2018
-# - Cedric Serfon, <cedric.serfon@cern.ch>, 2018-2019
+# - Cedric Serfon, <cedric.serfon@cern.ch>, 2018-2020
 # - Hannes Hansen, <hannes.jakob.hansen@cern.ch>, 2018
 # - Robert Illingworth, <illingwo@fnal.gov>, 2019
 # - Andrew Lister, <andrew.lister@stfc.ac.uk>, 2019
@@ -1038,7 +1038,11 @@ def get_transfer_requests_and_source_replicas(total_workers=0, worker_number=0,
                         # Need to fail all the intermediate requests + the initial one and exit the multihop loop
                         logging.warning('Multihop : A request already exists for the transfer between %s and %s. Will cancel all the parent requests', source_rse_name, dest_rse_name)
                         parent_requests.append(req_id)
-                        set_requests_state(request_ids=parent_requests, new_state=RequestState.FAILED, session=session)
+                        try:
+                            set_requests_state(request_ids=parent_requests, new_state=RequestState.FAILED, session=session)
+                        except UnsupportedOperation:
+                            logging.error('Multihop : Cannot cancel all the parent requests : %s', str(parent_requests))
+
                         # Remove from the transfer dictionary all the requests
                         for cur_req_id in parent_requests:
                             transfers.pop(cur_req_id, None)


Test patch:
Repository: rucio/rucio

Issue:
Do not mangle XCache URLs when using signed URLs; Fix #3503
Do not mangle XCache URLs when using signed URLs; Fix #3503


Discussion:

Resolving patch:
diff --git a/lib/rucio/core/transfer.py b/lib/rucio/core/transfer.py
--- a/lib/rucio/core/transfer.py
+++ b/lib/rucio/core/transfer.py
@@ -1,18 +1,30 @@
-# Copyright European Organization for Nuclear Research (CERN)
+# Copyright 2013-2020 CERN for the benefit of the ATLAS collaboration.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
-# You may not use this file except in compliance with the License.
+# you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at
-# http://www.apache.org/licenses/LICENSE-2.0
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
 #
 # Authors:
-# - Martin Barisits, <martin.barisits@cern.ch>, 2017-2018
-# - Mario Lassnig, <mario.lassnig@cern.ch>, 2017-2018
-# - Cedric Serfon, <cedric.serfon@cern.ch>, 2018-2020
-# - Hannes Hansen, <hannes.jakob.hansen@cern.ch>, 2018
-# - Robert Illingworth, <illingwo@fnal.gov>, 2019
-# - Andrew Lister, <andrew.lister@stfc.ac.uk>, 2019
-# - Brandon White, <bjwhite@fnal.gov>, 2019
+# - Mario Lassnig <mario.lassnig@cern.ch>, 2013-2020
+# - Martin Barisits <martin.barisits@cern.ch>, 2017-2019
+# - Vincent Garonne <vgaronne@gmail.com>, 2017
+# - Igor Mandrichenko <rucio@fermicloud055.fnal.gov>, 2018
+# - Cedric Serfon <cedric.serfon@cern.ch>, 2018-2020
+# - dciangot <diego.ciangottini@cern.ch>, 2018
+# - Robert Illingworth <illingwo@fnal.gov>, 2018-2019
+# - Hannes Hansen <hannes.jakob.hansen@cern.ch>, 2018
+# - Andrew Lister <andrew.lister@stfc.ac.uk>, 2019
+# - Brandon White <bjwhite@fnal.gov>, 2019
+# - maatthias <maatthias@gmail.com>, 2019
+# - Gabriele <sucre.91@hotmail.it>, 2019
 #
 # PY3K COMPATIBLE
 
@@ -832,7 +844,7 @@ def get_transfer_requests_and_source_replicas(total_workers=0, worker_number=0,
                                      'dest_spacetoken': dest_spacetoken,
                                      'overwrite': overwrite,
                                      'bring_online': bring_online,
-                                     'copy_pin_lifetime': dict_attributes.get('lifetime', -1),
+                                     'copy_pin_lifetime': dict_attributes.get('lifetime', 172800),
                                      'external_host': external_host,
                                      'selection_strategy': 'auto',
                                      'rule_id': rule_id,


Test patch:
Repository: rucio/rucio

Issue:
Thread workload hashing is incorrect for MySQL and PostgreSQL
Motivation
----------
For both the MySQL and PostgreSQL database types, the hashing algorithm used to partition worker thread responsibilities has the divisor of the modulo operation being incorrectly computed, erroneously using total_threads-1 instead of the raw value of total threads. This has the consequence of preventing some threads from ever being assigned work. 

Modification
------------
I will provide a fix for this. I intend to create a function in db/sqla/util.py to do this, as this pattern for workload partitioning is repeated 21 times throughout the codebase.





Discussion:

Resolving patch:
diff --git a/lib/rucio/transfertool/fts3.py b/lib/rucio/transfertool/fts3.py
--- a/lib/rucio/transfertool/fts3.py
+++ b/lib/rucio/transfertool/fts3.py
@@ -359,7 +359,7 @@ def bulk_query(self, transfer_ids, timeout=None):
         responses = {}
         fts_session = requests.Session()
         xfer_ids = ','.join(transfer_ids)
-        jobs = fts_session.get('%s/jobs/%s?files=file_state,dest_surl,finish_time,start_time,reason,source_surl,file_metadata' % (self.external_host, xfer_ids),
+        jobs = fts_session.get('%s/jobs/%s?files=file_state,dest_surl,finish_time,start_time,staging_start,staging_finished,reason,source_surl,file_metadata' % (self.external_host, xfer_ids),
                                verify=self.verify,
                                cert=self.cert,
                                headers={'Content-Type': 'application/json'},
@@ -700,6 +700,8 @@ def __format_new_response(self, fts_job_response, fts_files_response):
                                      'src_url': file_resp.get('source_surl', None),
                                      'dst_url': file_resp.get('dest_surl', None),
                                      'started_at': datetime.datetime.strptime(file_resp['start_time'], '%Y-%m-%dT%H:%M:%S') if file_resp['start_time'] else None,
+                                     'staging_start': datetime.datetime.strptime(file_resp['staging_start'], '%Y-%m-%dT%H:%M:%S') if file_resp['staging_start'] else None,
+                                     'staging_finished': datetime.datetime.strptime(file_resp['staging_finished'], '%Y-%m-%dT%H:%M:%S') if file_resp['staging_finished'] else None,
                                      'transferred_at': datetime.datetime.strptime(file_resp['finish_time'], '%Y-%m-%dT%H:%M:%S') if file_resp['finish_time'] else None,
                                      'duration': duration,
                                      'reason': file_resp.get('reason', None),


Test patch:
Repository: rucio/rucio

Issue:
Add quote/rule approvers to CMS
Motivation
----------

CMS RSEs will also need these approvals mechanisms


Modification
------------





Discussion:

Resolving patch:
diff --git a/lib/rucio/core/permission/cms.py b/lib/rucio/core/permission/cms.py
--- a/lib/rucio/core/permission/cms.py
+++ b/lib/rucio/core/permission/cms.py
@@ -475,6 +475,17 @@ def perm_approve_rule(issuer, kwargs):
     """
     if _is_root(issuer) or has_account_attribute(account=issuer, key='admin'):
         return True
+
+    rule = get_rule(rule_id=kwargs['rule_id'])
+    rses = parse_expression(rule['rse_expression'])
+
+    # Those in rule_approvers can approve the rule
+    for rse in rses:
+        rse_attr = list_rse_attributes(rse_id=rse['id'])
+        rule_approvers = rse_attr.get('rule_approvers', None)
+        if rule_approvers and issuer.external in rule_approvers.split(','):
+            return True
+
     return False
 
 
@@ -760,6 +771,13 @@ def perm_set_local_account_limit(issuer, kwargs):
             admin_in_country.append(kv['key'].partition('-')[2])
     if admin_in_country and list_rse_attributes(rse_id=kwargs['rse_id']).get('country') in admin_in_country:
         return True
+
+    # Those listed as quota approvers can add to quotas
+    rse_attr = list_rse_attributes(rse_id=kwargs['rse_id'])
+    quota_approvers = rse_attr.get('quota_approvers', None)
+    if quota_approvers and issuer.external in quota_approvers.split(','):
+        return True
+
     return False
 
 
@@ -823,6 +841,12 @@ def perm_delete_local_account_limit(issuer, kwargs):
             admin_in_country.append(kv['key'].partition('-')[2])
     if admin_in_country and list_rse_attributes(rse_id=kwargs['rse_id']).get('country') in admin_in_country:
         return True
+
+    rse_attr = list_rse_attributes(rse_id=kwargs['rse_id'])
+    quota_approvers = rse_attr.get('quota_approvers', None)
+    if quota_approvers and issuer.external in quota_approvers.split(','):
+        return True
+
     return False
 
 


Test patch:
Repository: rucio/rucio

Issue:
Fix variable initialization in delete_replica
Motivation
----------
The rowcount variable is not properly reinitialized in `delete_replicas`





Discussion:

Resolving patch:
diff --git a/lib/rucio/core/replica.py b/lib/rucio/core/replica.py
--- a/lib/rucio/core/replica.py
+++ b/lib/rucio/core/replica.py
@@ -14,7 +14,7 @@
 #
 # Authors:
 # - Vincent Garonne <vgaronne@gmail.com>, 2013-2018
-# - Cedric Serfon <cedric.serfon@cern.ch>, 2013-2019
+# - Cedric Serfon <cedric.serfon@cern.ch>, 2013-2020
 # - Ralph Vigne <ralph.vigne@cern.ch>, 2013-2014
 # - Martin Barisits <martin.barisits@cern.ch>, 2013-2019
 # - Mario Lassnig <mario.lassnig@cern.ch>, 2014-2019
@@ -1407,6 +1407,7 @@ def delete_replicas(rse_id, files, ignore_availability=True, session=None):
             filter(or_(*chunk)).\
             delete(synchronize_session=False)
 
+    rowcount = 0
     for chunk in chunks(replica_condition, 10):
         for (scope, name, rid, replica_bytes) in session.query(models.RSEFileAssociation.scope, models.RSEFileAssociation.name, models.RSEFileAssociation.rse_id, models.RSEFileAssociation.bytes).\
                 with_hint(models.RSEFileAssociation, "INDEX(REPLICAS REPLICAS_PK)", 'oracle').filter(models.RSEFileAssociation.rse_id == rse_id).filter(or_(*chunk)):


Test patch:
Repository: rucio/rucio

Issue:
Bug when a file with no available replicas is declared
Motivation
----------
When a replica has no replicas `AVAILABLE` and one declare one of these replicas as lost, all the requests for the other replicas are canceled but not the one of the file that was declared.








Discussion:

Resolving patch:
diff --git a/lib/rucio/core/rule.py b/lib/rucio/core/rule.py
--- a/lib/rucio/core/rule.py
+++ b/lib/rucio/core/rule.py
@@ -16,7 +16,7 @@
 # - Vincent Garonne <vgaronne@gmail.com>, 2012-2018
 # - Mario Lassnig <mario.lassnig@cern.ch>, 2013-2018
 # - Martin Barisits <martin.barisits@cern.ch>, 2013-2020
-# - Cedric Serfon <cedric.serfon@cern.ch>, 2014-2019
+# - Cedric Serfon <cedric.serfon@cern.ch>, 2014-2020
 # - David Cameron <d.g.cameron@gmail.com>, 2014
 # - Joaquin Bogado <jbogado@linti.unlp.edu.ar>, 2014-2018
 # - Thomas Beermann <thomas.beermann@cern.ch>, 2014-2015
@@ -41,9 +41,9 @@
 from copy import deepcopy
 from datetime import datetime, timedelta
 from re import match
-from six import string_types
 from string import Template
 
+from six import string_types
 from sqlalchemy.exc import IntegrityError, StatementError
 from sqlalchemy.orm.exc import NoResultFound
 from sqlalchemy.sql import func
@@ -1700,6 +1700,8 @@ def update_rules_for_lost_replica(scope, name, rse_id, nowait=False, session=Non
 
     locks = session.query(models.ReplicaLock).filter(models.ReplicaLock.scope == scope, models.ReplicaLock.name == name, models.ReplicaLock.rse_id == rse_id).with_for_update(nowait=nowait).all()
     replica = session.query(models.RSEFileAssociation).filter(models.RSEFileAssociation.scope == scope, models.RSEFileAssociation.name == name, models.RSEFileAssociation.rse_id == rse_id).with_for_update(nowait=nowait).one()
+    requests = session.query(models.Request).filter(models.Request.scope == scope, models.Request.name == name, models.Request.dest_rse_id == rse_id).with_for_update(nowait=nowait).all()
+
     rse = get_rse_name(rse_id, session=session)
 
     datasets = []
@@ -1708,6 +1710,9 @@ def update_rules_for_lost_replica(scope, name, rse_id, nowait=False, session=Non
         if {'name': parent['name'], 'scope': parent['scope']} not in datasets:
             datasets.append({'name': parent['name'], 'scope': parent['scope']})
 
+    for request in requests:
+        session.delete(request)
+
     for lock in locks:
         rule = session.query(models.ReplicationRule).filter(models.ReplicationRule.id == lock.rule_id).with_for_update(nowait=nowait).one()
         rule_state_before = rule.state


Test patch: