Skip to content

Commit 9b76601

Browse files
authored
Merge pull request #6458 from rtibblesbot/issue-6456-ea872e
Backfill included_presets on public files during deploy
2 parents 9093f6a + 3a94929 commit 9b76601

3 files changed

Lines changed: 281 additions & 1 deletion

File tree

‎Makefile‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ migrate:
3939
# 4) Remove the management command from this `deploy-migrate` recipe
4040
# 5) Repeat!
4141
deploy-migrate:
42-
echo "Nothing to do here!"
42+
# studio#6456: remove after release.
43+
python contentcuration/manage.py backfill_public_file_included_presets
4344

4445
contentnodegc:
4546
python contentcuration/manage.py garbage_collect
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from django.core.management.base import BaseCommand
2+
from django.core.management.base import CommandError
3+
from django.db import transaction
4+
from django.db.models import Case
5+
from django.db.models import Value
6+
from django.db.models import When
7+
from kolibri_public.models import File
8+
from le_utils.constants.format_presets import RENDERABLE_PRESETS_ORDER
9+
10+
11+
class Command(BaseCommand):
12+
help = "Set included_presets on eligible kolibri_public files, in batches."
13+
14+
def add_arguments(self, parser):
15+
parser.add_argument("--batch-size", type=int, default=10000)
16+
17+
def handle(self, *args, **options):
18+
batch_size = options["batch_size"]
19+
if batch_size < 1:
20+
raise CommandError("--batch-size must be >= 1")
21+
22+
unfilled = File.objects.filter(
23+
included_presets__isnull=True,
24+
supplementary=False,
25+
preset__in=RENDERABLE_PRESETS_ORDER,
26+
)
27+
unfilled_pks = unfilled.order_by("pk").values_list("pk", flat=True)
28+
when_statements = [
29+
When(preset=preset, then=Value(2 ** index))
30+
for index, preset in enumerate(RENDERABLE_PRESETS_ORDER)
31+
]
32+
included_presets = Case(*when_statements)
33+
34+
batch_start = unfilled_pks.first()
35+
while batch_start is not None:
36+
with transaction.atomic():
37+
batch_pks = list(
38+
File.objects.filter(pk__gte=batch_start)
39+
.order_by("pk")
40+
.values_list("pk", flat=True)[:batch_size]
41+
)
42+
unfilled.filter(pk__in=batch_pks).update(
43+
included_presets=included_presets
44+
)
45+
46+
if len(batch_pks) == batch_size:
47+
self.stdout.write("backfilled through pk={}".format(batch_pks[-1]))
48+
batch_start = (
49+
unfilled_pks.filter(pk__gt=batch_pks[-1]).first() if batch_pks else None
50+
)
51+
if batch_start is None:
52+
batch_start = unfilled_pks.first()
53+
54+
self.stdout.write("backfill complete")
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
from datetime import timedelta
2+
from io import StringIO
3+
4+
from django.core.management import call_command
5+
from django.db import connection
6+
from django.db import IntegrityError
7+
from django.db import transaction
8+
from django.test import TransactionTestCase
9+
from django.utils import timezone
10+
from kolibri_public import models
11+
from kolibri_public.tests.base import uuid4_hex
12+
from le_utils.constants import content_kinds
13+
from le_utils.constants import format_presets
14+
from le_utils.constants.format_presets import RENDERABLE_PRESETS_ORDER
15+
16+
17+
class BackfillPublicFileIncludedPresetsTestCase(TransactionTestCase):
18+
def setUp(self):
19+
self.contentnode = models.ContentNode.objects.create(
20+
pk=uuid4_hex(),
21+
channel_id=uuid4_hex(),
22+
content_id=uuid4_hex(),
23+
kind=content_kinds.TOPIC,
24+
title="node",
25+
options={},
26+
)
27+
self.local_file = models.LocalFile.objects.create(pk=uuid4_hex())
28+
29+
def _create_file(self, pk_number, preset, **kwargs):
30+
return models.File.objects.create(
31+
pk="{:032x}".format(pk_number),
32+
local_file=self.local_file,
33+
contentnode=self.contentnode,
34+
preset=preset,
35+
**kwargs,
36+
)
37+
38+
def test_backfills_eligible_files_across_batches_and_is_idempotent(self):
39+
first_audio = self._create_file(1, format_presets.AUDIO)
40+
first_document = self._create_file(2, format_presets.DOCUMENT)
41+
unknown = self._create_file(3, "unknown_preset")
42+
supplementary = self._create_file(4, format_presets.AUDIO, supplementary=True)
43+
document_bit = 2 ** RENDERABLE_PRESETS_ORDER.index(format_presets.DOCUMENT)
44+
already_set = self._create_file(
45+
5, format_presets.AUDIO, included_presets=document_bit
46+
)
47+
second_audio = self._create_file(6, format_presets.AUDIO)
48+
second_document = self._create_file(7, format_presets.DOCUMENT)
49+
last_audio = self._create_file(8, format_presets.AUDIO)
50+
51+
expected = {
52+
file.pk: 2 ** RENDERABLE_PRESETS_ORDER.index(file.preset)
53+
for file in (
54+
first_audio,
55+
first_document,
56+
second_audio,
57+
second_document,
58+
last_audio,
59+
)
60+
}
61+
expected.update(
62+
{
63+
unknown.pk: None,
64+
supplementary.pk: None,
65+
already_set.pk: document_bit,
66+
}
67+
)
68+
69+
call_command("backfill_public_file_included_presets", batch_size=2)
70+
self.assertEqual(
71+
dict(models.File.objects.values_list("id", "included_presets")), expected
72+
)
73+
with transaction.atomic():
74+
with connection.cursor() as cursor:
75+
cursor.execute(
76+
"""
77+
CREATE FUNCTION reject_backfill_write() RETURNS trigger
78+
LANGUAGE plpgsql AS $$
79+
BEGIN
80+
RAISE EXCEPTION 'Unexpected write to %', TG_TABLE_NAME;
81+
END;
82+
$$;
83+
CREATE TRIGGER reject_backfill_write
84+
BEFORE INSERT OR UPDATE OR DELETE ON kolibri_public_file
85+
FOR EACH ROW EXECUTE FUNCTION reject_backfill_write();
86+
"""
87+
)
88+
call_command("backfill_public_file_included_presets", batch_size=2)
89+
transaction.set_rollback(True)
90+
91+
def test_backfills_legacy_file_remapped_behind_cursor(self):
92+
first_file = self._create_file(10, format_presets.AUDIO)
93+
second_file = self._create_file(20, format_presets.AUDIO)
94+
output = StringIO()
95+
with transaction.atomic():
96+
with connection.cursor() as cursor:
97+
cursor.execute(
98+
"""
99+
CREATE FUNCTION remap_legacy_file() RETURNS trigger
100+
LANGUAGE plpgsql AS $$
101+
DECLARE
102+
remapped_file kolibri_public_file%%ROWTYPE;
103+
BEGIN
104+
DELETE FROM kolibri_public_file WHERE id = TG_ARGV[0]::uuid
105+
RETURNING * INTO remapped_file;
106+
remapped_file.included_presets := NULL;
107+
INSERT INTO kolibri_public_file VALUES (remapped_file.*);
108+
RETURN NULL;
109+
END;
110+
$$;
111+
CREATE TRIGGER remap_legacy_file
112+
AFTER UPDATE OF included_presets ON kolibri_public_file
113+
FOR EACH ROW WHEN (NEW.id = %s AND NEW.included_presets IS NOT NULL)
114+
EXECUTE FUNCTION remap_legacy_file(%s);
115+
""",
116+
[second_file.pk, first_file.pk],
117+
)
118+
call_command(
119+
"backfill_public_file_included_presets", batch_size=1, stdout=output
120+
)
121+
122+
first_file.refresh_from_db()
123+
self.assertEqual(
124+
first_file.included_presets,
125+
2 ** RENDERABLE_PRESETS_ORDER.index(first_file.preset),
126+
)
127+
first_batch = f"backfilled through pk={first_file.pk}"
128+
self.assertEqual(output.getvalue().splitlines().count(first_batch), 2)
129+
transaction.set_rollback(True)
130+
131+
def test_tail_batch_remains_bounded_when_files_are_inserted(self):
132+
self._create_file(1, format_presets.AUDIO)
133+
inserted = False
134+
135+
def insert_after_batch_read(execute, sql, params, many, context):
136+
nonlocal inserted
137+
result = execute(sql, params, many, context)
138+
if not inserted and connection.in_atomic_block:
139+
inserted = True
140+
for pk_number in range(2, 5):
141+
self._create_file(pk_number, format_presets.AUDIO)
142+
return result
143+
144+
with connection.cursor() as cursor:
145+
cursor.execute(
146+
"""
147+
CREATE FUNCTION check_backfill_batch_size() RETURNS trigger
148+
LANGUAGE plpgsql AS $$
149+
BEGIN
150+
IF (SELECT count(*) FROM updated_files) > 2 THEN
151+
RAISE EXCEPTION 'Backfill batch exceeds two rows';
152+
END IF;
153+
RETURN NULL;
154+
END;
155+
$$;
156+
CREATE TRIGGER check_backfill_batch_size
157+
AFTER UPDATE ON kolibri_public_file
158+
REFERENCING NEW TABLE AS updated_files
159+
FOR EACH STATEMENT EXECUTE FUNCTION check_backfill_batch_size();
160+
"""
161+
)
162+
try:
163+
with connection.execute_wrapper(insert_after_batch_read):
164+
call_command("backfill_public_file_included_presets", batch_size=2)
165+
finally:
166+
with connection.cursor() as cursor:
167+
cursor.execute(
168+
"DROP TRIGGER check_backfill_batch_size ON kolibri_public_file; "
169+
"DROP FUNCTION check_backfill_batch_size();"
170+
)
171+
172+
audio_bit = 2 ** RENDERABLE_PRESETS_ORDER.index(format_presets.AUDIO)
173+
self.assertEqual(
174+
dict(models.File.objects.values_list("id", "included_presets")),
175+
{"{:032x}".format(pk_number): audio_bit for pk_number in range(1, 5)},
176+
)
177+
178+
def test_can_resume_after_a_later_batch_fails(self):
179+
first_file = self._create_file(1, format_presets.AUDIO)
180+
second_file = self._create_file(2, format_presets.DOCUMENT)
181+
with connection.cursor() as cursor:
182+
cursor.execute(
183+
"ALTER TABLE kolibri_public_file ADD CONSTRAINT backfill_failure "
184+
"CHECK (id != %s OR included_presets IS NULL)",
185+
[second_file.pk],
186+
)
187+
try:
188+
with self.assertRaisesMessage(IntegrityError, "backfill_failure"):
189+
call_command("backfill_public_file_included_presets", batch_size=1)
190+
finally:
191+
with connection.cursor() as cursor:
192+
cursor.execute(
193+
"ALTER TABLE kolibri_public_file DROP CONSTRAINT backfill_failure"
194+
)
195+
196+
first_file.refresh_from_db()
197+
second_file.refresh_from_db()
198+
self.assertEqual(
199+
first_file.included_presets,
200+
2 ** RENDERABLE_PRESETS_ORDER.index(first_file.preset),
201+
)
202+
self.assertIsNone(second_file.included_presets)
203+
204+
call_command("backfill_public_file_included_presets", batch_size=1)
205+
206+
second_file.refresh_from_db()
207+
self.assertEqual(
208+
second_file.included_presets,
209+
2 ** RENDERABLE_PRESETS_ORDER.index(second_file.preset),
210+
)
211+
212+
def test_backfill_preserves_channel_publish_timestamp(self):
213+
self._create_file(1, format_presets.AUDIO)
214+
published_at = timezone.now() - timedelta(days=1)
215+
channel = models.ChannelMetadata.objects.create(
216+
pk=self.contentnode.channel_id,
217+
root=self.contentnode,
218+
public=True,
219+
last_updated=published_at,
220+
)
221+
222+
call_command("backfill_public_file_included_presets", batch_size=1)
223+
224+
channel.refresh_from_db()
225+
self.assertEqual(channel.last_updated, published_at)

0 commit comments

Comments
 (0)