Skip to content

Commit aa614f2

Browse files
bjesterclaude
andcommitted
Match sync filters in cleanupsyncs regardless of partition order
cleanupsyncs matched --sync-filter against the stored filter string with startswith. Kolibri passes the full filter string of the current sync, so after Scope began listing read-write partitions last, the command no longer matched transfer sessions stored in the old order, and left their buffers behind. A transfer session now matches if its filter starts with the given filter, as before, or has the same partitions in any order. The match runs in Python, after the other options narrow the candidates in the database. The command now loads the transfer sessions to close in batches of 500 IDs, so no query binds more parameters than older versions of SQLite allow. Refs #398 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 95df18d commit aa614f2

3 files changed

Lines changed: 102 additions & 22 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ List of the most important changes for each release.
1414
- Removes `SyncableModel.deferred_clean_fields` and `morango.models.core.ForeignKeyReference`
1515
- Removes `morango.sync.backends.utils.TemporaryTable` and `morango.sync.backends.utils.get_pk_field`
1616
- `Scope.read_filter` and `Scope.write_filter` now list the read-write partitions last, so deserialization, which follows the filter order, puts shared records before the records that reference them. A server that receives a push from a client on an older version deserializes in the client's filter order
17+
- `cleanupsyncs --sync-filter` now also matches transfer sessions whose filter has the same partitions in a different order, so it still cleans up sessions stored before the partition order changed
1718
- Removes the unused bulk write helpers `_bulk_full_record_upsert`, `_bulk_update` and `_bulk_insert`, and the temporary table helper `_create_temporary_table`, from the sync backends
1819

1920
## 0.8.15

‎morango/management/commands/cleanupsyncs.py‎

Lines changed: 48 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,14 @@
88

99
from morango.models import SyncSession
1010
from morango.models import TransferSession
11+
from morango.models.certificates import Filter
1112

1213
logger = logging.getLogger(__name__)
1314

15+
# the number of transfer sessions to query at once, which keeps each query below the limit of 999
16+
# bound parameters in older versions of SQLite
17+
TRANSFER_SESSION_BATCH_SIZE = 500
18+
1419

1520
class Command(BaseCommand):
1621
help = "Closes and cleans up the data for any incomplete sync sessions older than a certain number of hours."
@@ -45,7 +50,7 @@ def add_arguments(self, parser):
4550
"--sync-filter",
4651
type=str,
4752
default=None,
48-
help="Filters the TransferSession models to those with 'filters' starting with 'sync_filter'",
53+
help="Filters the TransferSession models to those with 'filters' starting with 'sync_filter', or with the same partitions in any order",
4954
)
5055
parser.add_argument(
5156
"--push",
@@ -60,6 +65,23 @@ def add_arguments(self, parser):
6065
help="Filters the TransferSession models to those with 'push' set to False",
6166
)
6267

68+
@staticmethod
69+
def _matching_ids(transfer_sessions, sync_filter):
70+
"""
71+
Returns the IDs of the transfer sessions whose filter starts with `sync_filter`, such as a
72+
dataset ID, or has the same partitions in any order. The partition order of a filter can
73+
change between versions, such as when `Scope` began listing read-write partitions last.
74+
"""
75+
partitions = Filter(sync_filter)
76+
return [
77+
transfer_session_id
78+
for transfer_session_id, transfer_session_filter in transfer_sessions.values_list(
79+
"id", "filter"
80+
)
81+
if transfer_session_filter.startswith(sync_filter)
82+
or Filter(transfer_session_filter) == partitions
83+
]
84+
6385
def handle(self, *args, **options):
6486

6587
# establish the cutoff time and date for stale sessions
@@ -85,33 +107,39 @@ def handle(self, *args, **options):
85107
last_activity_timestamp__lt=cutoff,
86108
)
87109

88-
if options["sync_filter"]:
89-
transfer_sessions = transfer_sessions.filter(filter__startswith=options["sync_filter"])
90-
91110
if options["push"] and not options["pull"]:
92111
transfer_sessions = transfer_sessions.filter(push=True)
93112

94113
if options["pull"] and not options["push"]:
95114
transfer_sessions = transfer_sessions.filter(push=False)
96115

97-
transfer_count = transfer_sessions.count()
98-
99-
# loop over the stale sessions one by one to close them out
100-
for i, transfer_session in enumerate(transfer_sessions):
101-
logger.info(
102-
"TransferSession {} of {}: deleting {} Buffers and {} RMC Buffers...".format(
103-
i + 1,
104-
transfer_count,
105-
transfer_session.buffer_set.all().count(),
106-
transfer_session.recordmaxcounterbuffer_set.all().count(),
116+
# ordering this last to keep manual filtering to a minimum
117+
if options["sync_filter"]:
118+
transfer_session_ids = self._matching_ids(transfer_sessions, options["sync_filter"])
119+
else:
120+
transfer_session_ids = list(transfer_sessions.values_list("id", flat=True))
121+
122+
transfer_count = len(transfer_session_ids)
123+
124+
# loop over the stale sessions one by one to close them out, querying them in batches
125+
for offset in range(0, transfer_count, TRANSFER_SESSION_BATCH_SIZE):
126+
batch_ids = transfer_session_ids[offset : offset + TRANSFER_SESSION_BATCH_SIZE]
127+
batch = TransferSession.objects.filter(id__in=batch_ids)
128+
for i, transfer_session in enumerate(batch, start=offset):
129+
logger.info(
130+
"TransferSession {} of {}: deleting {} Buffers and {} RMC Buffers...".format(
131+
i + 1,
132+
transfer_count,
133+
transfer_session.buffer_set.all().count(),
134+
transfer_session.recordmaxcounterbuffer_set.all().count(),
135+
)
107136
)
108-
)
109137

110-
# delete buffer data and mark as inactive
111-
with transaction.atomic():
112-
transfer_session.delete_buffers()
113-
transfer_session.active = False
114-
transfer_session.save()
138+
# delete buffer data and mark as inactive
139+
with transaction.atomic():
140+
transfer_session.delete_buffers()
141+
transfer_session.active = False
142+
transfer_session.save()
115143

116144
# in order to close a sync session, it must have no active transfer sessions
117145
# and must have no activity since the cutoff

‎tests/testapp/tests/test_management_commands.py‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import datetime
22
import uuid
33

4+
import mock
45
from django.core.management import call_command
56
from django.test import TestCase
67
from django.utils import timezone
@@ -11,7 +12,7 @@
1112
from .helpers import create_buffer_and_store_dummy_data
1213

1314

14-
def _create_sessions(last_activity_offset=0, sync_session=None, push=True):
15+
def _create_sessions(last_activity_offset=0, sync_session=None, push=True, filter="1:2\n"):
1516

1617
last_activity_timestamp = timezone.now() - datetime.timedelta(hours=last_activity_offset)
1718

@@ -29,7 +30,7 @@ def _create_sessions(last_activity_offset=0, sync_session=None, push=True):
2930
sync_session=sync_session,
3031
push=push,
3132
last_activity_timestamp=last_activity_timestamp,
32-
filter="1:2\n",
33+
filter=filter,
3334
)
3435

3536
return sync_session, transfer_session
@@ -127,6 +128,56 @@ def test_filtering_sessions_by_sync_filter_cleared(self):
127128
self.assertTransferSessionIsCleared(self.transfersession_new)
128129
self.assertSyncSessionIsNotActive(self.syncsession_new)
129130

131+
def test_filtering_sessions_by_sync_filter__prefix(self):
132+
"""A prefix of the stored filters, such as a dataset ID, matches them"""
133+
call_command("cleanupsyncs", sync_filter="1", expiration=0)
134+
self.assertTransferSessionIsCleared(self.transfersession_old)
135+
self.assertTransferSessionIsCleared(self.transfersession_new)
136+
137+
def test_filtering_sessions_by_sync_filter__partition_order(self):
138+
"""
139+
A filter with the same partitions in a different order matches, so sessions stored before
140+
`Scope` changed its partition order are still cleaned up
141+
"""
142+
_, reordered = _create_sessions(24, filter="1:2:rw\n1:2:ro")
143+
create_buffer_and_store_dummy_data(reordered.id)
144+
145+
call_command("cleanupsyncs", sync_filter="1:2:ro\n1:2:rw", expiration=0)
146+
147+
self.assertTransferSessionIsCleared(reordered)
148+
self.assertTransferSessionIsNotCleared(self.transfersession_old)
149+
self.assertTransferSessionIsNotCleared(self.transfersession_new)
150+
151+
def test_filtering_sessions_by_sync_filter__different_partitions(self):
152+
"""A filter with other partitions does not match"""
153+
_, other = _create_sessions(24, filter="1:2:rw\n1:2:ro")
154+
create_buffer_and_store_dummy_data(other.id)
155+
156+
call_command("cleanupsyncs", sync_filter="1:2:ro\n1:2:wo", expiration=0)
157+
158+
self.assertTransferSessionIsNotCleared(other)
159+
160+
@mock.patch("morango.management.commands.cleanupsyncs.TRANSFER_SESSION_BATCH_SIZE", 2)
161+
def test_sessions_cleared_in_batches(self):
162+
"""Sessions in every batch are cleared, including a partial last batch"""
163+
reordered = []
164+
for _ in range(3):
165+
_, transfer_session = _create_sessions(24, filter="1:2:rw\n1:2:ro")
166+
create_buffer_and_store_dummy_data(transfer_session.id)
167+
reordered.append(transfer_session)
168+
169+
call_command("cleanupsyncs", sync_filter="1:2:ro\n1:2:rw", expiration=0)
170+
171+
for transfer_session in reordered:
172+
self.assertTransferSessionIsCleared(transfer_session)
173+
self.assertTransferSessionIsNotCleared(self.transfersession_old)
174+
175+
@mock.patch("morango.management.commands.cleanupsyncs.TRANSFER_SESSION_BATCH_SIZE", 1)
176+
def test_sessions_cleared_in_batches__no_sync_filter(self):
177+
call_command("cleanupsyncs", expiration=1)
178+
self.assertTransferSessionIsCleared(self.transfersession_old)
179+
self.assertTransferSessionIsCleared(self.transfersession_new)
180+
130181
def test_filtering_sessions_by_push_cleared(self):
131182
call_command("cleanupsyncs", push=self.transfersession_old.push, expiration=0)
132183
self.assertTransferSessionIsCleared(self.transfersession_old)

0 commit comments

Comments
 (0)