Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ai-research): drop the month block fence from ML key commits (#101134)

Robbie1826184dc9fb
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
index 44bfeaa48ac3..fb73c402638e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
@@ -146,7 +146,7 @@ describe('ml-mirror-pipeline', () => {
topHog,
isDebugLoggingEnabled: () => false,
},
- { anonymizeMaxConcurrency: 4 }
+ { anonymizeMaxConcurrency: 4, nowMs: () => Date.UTC(2026, 8, 15, 13) }
)
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
index 89e81b630a9a..2d5ba5d5c71b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
@@ -29,12 +29,13 @@ import { MlImageFetchOutput, MlImageScrubOutput } from '~/ingestion/pipelines/se
import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
import { MlPrivacyBatchController } from './privacy/batch-controller'
-import { isSupportedMlSessionId } from './session-identifier-format'
+import { mlSessionIdDropReason } from './session-identifier-format'
export interface MlMirrorPipelineOptions {
/** Cap on sessions scrubbed concurrently; each in-flight scrub occupies a libuv threadpool thread. */
anonymizeMaxConcurrency: number
privacy?: MlPrivacyBatchController
+ nowMs?: () => number
}
/** Enables the image-collection lane: inlined images become refs, originals go to the scrub topic. */
@@ -68,11 +69,12 @@ export interface MlMirrorCollection {
collectUrls: boolean
}
-function createMlSessionIdFilterStep<T extends { headers: SessionReplayHeaders }>(): ProcessingStep<T, T> {
+function createMlSessionIdFilterStep<T extends { headers: SessionReplayHeaders }>(
+ nowMs: () => number
+): ProcessingStep<T, T> {
return function filterMlSessionId(input) {
- return Promise.resolve(
- isSupportedMlSessionId(input.headers.session_id) ? ok(input) : drop('session_id_not_uuid_v7')
- )
+ const reason = mlSessionIdDropReason(input.headers.session_id, nowMs())
+ return Promise.resolve(reason ? drop(reason) : ok(input))
}
}
@@ -113,7 +115,7 @@ export function createMlMirrorReplayPipeline(
b
.sequentially((b) =>
addSessionReplayPreprocessing(b, config)
- .pipe(createMlSessionIdFilterStep())
+ .pipe(createMlSessionIdFilterStep(mlOptions.nowMs ?? Date.now))
// Mirror only data from orgs that opted into AI training.
.pipe(createAiTrainingOptInFilterStep())
)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
index 2c6245448d90..56c6795a2d36 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.test.ts
@@ -21,7 +21,7 @@ import { MlKeyEncryption } from './crypto'
import { DynamoItem, MlPrivacyDynamoDB, encodeKey } from './dynamodb'
import { MlSessionKeyStore } from './key-store'
import { MlKeyReader } from './reader'
-import { MlSessionIdentity, imageKeyId, monthBlockId, monthKeyIndexId, sessionKeyId, tableKeyString } from './schema'
+import { MlSessionIdentity, imageKeyId, monthKeyIndexId, sessionKeyId, tableKeyString, teamBlockId } from './schema'
import { MlKafkaEncryption, encryptedKafkaValue } from './transport'
const session: MlSessionIdentity = {
@@ -218,7 +218,7 @@ describe('ML session key batches', () => {
expect(remaining).toBeGreaterThan(0)
})
- it('indexes monthly keys atomically and blocks a month during a competing batch', async () => {
+ it('indexes monthly keys atomically, ignores a month marker, and blocks on a team marker', async () => {
const october = { ...session, sessionId: '0199a13b-c000-7000-8000-000000000007' }
const first = await store.prepare([session, october])
await first.commit()
@@ -234,21 +234,31 @@ describe('ML session key batches', () => {
key_sk: { S: location.sk },
})
}
+ const locations = [
+ sessionKeyId(session.teamId, session.sessionId),
+ imageKeyId(session.teamId, '2025-09'),
+ sessionKeyId(october.teamId, october.sessionId),
+ imageKeyId(session.teamId, '2025-10'),
+ ]
+ const monthMarker = { pk: 'month:2025-09', sk: 'deleted' }
+ boundary.items.set(tableKeyString(monthMarker), { ...encodeKey(monthMarker), deleted: { BOOL: true } })
+ const ignoringMonth = await store.prepare([session])
+ jest.useFakeTimers()
+ const committingDespiteMonth = ignoringMonth.commit()
+ await jest.runAllTimersAsync()
+ await committingDespiteMonth
+ expect(ignoringMonth.get(session.teamId, session.sessionId)).not.toBeUndefined()
+ expect((await reader.read(locations)).size).toBe(4)
+ jest.useRealTimers()
const inFlight = await store.prepare([session])
- const blocked = monthBlockId('2025-09')
+ const blocked = teamBlockId(session.teamId)
boundary.items.set(tableKeyString(blocked), { ...encodeKey(blocked), deleted: { BOOL: true } })
jest.useFakeTimers()
const committing = inFlight.commit()
await jest.runAllTimersAsync()
await committing
expect(inFlight.get(session.teamId, session.sessionId)).toBeUndefined()
- const locations = [
- sessionKeyId(session.teamId, session.sessionId),
- imageKeyId(session.teamId, '2025-09'),
- sessionKeyId(october.teamId, october.sessionId),
- imageKeyId(session.teamId, '2025-10'),
- ]
- expect([...(await reader.read(locations))].map(([id]) => id)).toEqual(locations.slice(2).map(tableKeyString))
+ expect((await reader.read(locations)).size).toBe(0)
})
it('adopts a competing writer key', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
index e8051a0345ed..47ba3c936e98 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/key-store.ts
@@ -11,14 +11,13 @@ import {
TableKey,
imageKeyId,
keySessionMonth,
- monthBlockId,
monthKeyIndexId,
sessionKeyId,
tableKeyString,
teamBlockId,
} from './schema'
-// The month and team block markers are single items that every commit in the fleet checks, so DynamoDB cancels concurrent commits as TransactionConflict under normal load. The budget counts the re-reads as well as the waits and stays under the consumer's 60 s loop stall threshold.
+// Every commit for a team checks the same team block marker, so DynamoDB cancels concurrent commits for one team as TransactionConflict under normal load. The budget counts the re-reads as well as the waits and stays under the consumer's 60 s loop stall threshold.
const COMMIT_ATTEMPTS = 10
const COMMIT_BUDGET_MS = 45_000
const COMMIT_BACKOFF_BASE_MS = 100
@@ -125,7 +124,6 @@ export class MlKeyBatch {
public async read(): Promise<void> {
this.keys.clear()
const initial = this.identities.flatMap((identity) => [
- monthBlockId(sessionStartMonth(identity.sessionId)),
teamBlockId(identity.teamId),
sessionKeyId(identity.teamId, identity.sessionId),
])
@@ -135,7 +133,6 @@ export class MlKeyBatch {
const id = tableKeyString(sessionKeyId(identity.teamId, identity.sessionId))
if (
this.state.has(tableKeyString(teamBlockId(identity.teamId))) ||
- this.state.has(tableKeyString(monthBlockId(sessionStartMonth(identity.sessionId)))) ||
this.state.get(id)?.deleted?.BOOL === true
) {
continue
@@ -186,11 +183,9 @@ export class MlKeyBatch {
return image ? { session, image } : undefined
}
+ // The pipeline drops sessions older than the month deletion grace period, so a commit fences on the team marker alone; a month marker would be one item every commit in the fleet contends on.
private guards(identity: MlKeyIdentity): TransactWriteItem[] {
- return [
- this.db.check(monthBlockId(keySessionMonth(identity)), 'attribute_not_exists(pk)'),
- this.db.check(teamBlockId(identity.teamId), 'attribute_not_exists(pk)'),
- ]
+ return [this.db.check(teamBlockId(identity.teamId), 'attribute_not_exists(pk)')]
}
private put(key: TableKey, attributes: DynamoItem, condition?: string): TransactWriteItem {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader.ts
index 316a972fe46f..48db37a67498 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/reader.ts
@@ -1,6 +1,6 @@
import { KEY_READ_LEASE_MS, MlDataKey, MlKeyEncryption } from './crypto'
import { MlPrivacyDynamoDB } from './dynamodb'
-import { MlKeyIdentity, TableKey, keySessionMonth, monthBlockId, tableKeyString, teamBlockId } from './schema'
+import { MlKeyIdentity, TableKey, tableKeyString, teamBlockId } from './schema'
export class MlKeyReader {
constructor(
@@ -28,19 +28,11 @@ export class MlKeyReader {
...(sessionId ? { sessionId } : { sessionMonth: item.session_month?.S }),
})
}
- const state = await this.db.read(
- [...identities.values()].flatMap((identity) => [
- monthBlockId(keySessionMonth(identity)),
- teamBlockId(identity.teamId),
- ])
- )
+ const state = await this.db.read([...identities.values()].map((identity) => teamBlockId(identity.teamId)))
const result = new Map<string, MlDataKey>()
await Promise.all(
[...identities].map(async ([id, identity]) => {
- if (
- state.has(tableKeyString(monthBlockId(keySessionMonth(identity)))) ||
- state.has(tableKeyString(teamBlockId(identity.teamId)))
- ) {
+ if (state.has(tableKeyString(teamBlockId(identity.teamId)))) {
return
}
result.set(id, {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts
index a7c0e20f11bb..7fdbace621b0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts
@@ -52,10 +52,6 @@ export function keySessionMonth(identity: MlKeyIdentity): string {
return identity.sessionMonth
}
-export function monthBlockId(month: string): TableKey {
- return { pk: `month:${month}`, sk: 'deleted' }
-}
-
export function monthKeyIndexId(identity: MlKeyIdentity, key: TableKey): TableKey {
const id = tableKeyString(key)
return { pk: `month:${keySessionMonth(identity)}:shard:${sessionShard(id)}`, sk: `key:${id}` }
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.test.ts
new file mode 100644
index 000000000000..2aba350485d9
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.test.ts
@@ -0,0 +1,21 @@
+import { mlSessionIdDropReason } from './session-identifier-format'
+
+describe('mlSessionIdDropReason', () => {
+ const startedAt = Date.UTC(2026, 8, 15, 12)
+ const sessionId = '01a0a4f0-3200-7000-8000-000000000001'
+ const day = 24 * 60 * 60 * 1000
+
+ it.each([
+ ['at the age limit', startedAt + 14 * day, null],
+ ['past the age limit', startedAt + 14 * day + 1, 'session_id_too_old'],
+ ['at the future limit', startedAt - day, null],
+ ['past the future limit', startedAt - day - 1, 'session_id_in_future'],
+ ])('%s', (_, nowMs, reason) => {
+ expect(mlSessionIdDropReason(sessionId, nowMs)).toBe(reason)
+ })
+
+ it('rejects a session ID that is not a UUIDv7 before checking its age', () => {
+ expect(mlSessionIdDropReason('not-a-session', startedAt)).toBe('session_id_not_uuid_v7')
+ expect(mlSessionIdDropReason('6ba7b810-9dad-41d1-80b4-00c04fd430c8', startedAt)).toBe('session_id_not_uuid_v7')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts
index 2b789eb29efa..1938685365a2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts
@@ -13,9 +13,25 @@ export function usesRawSessionIdentifiers(sessionId: string): boolean {
return startedAt !== null && startedAt >= RAW_SESSION_IDENTIFIERS_START_MS && startedAt < Date.UTC(10000, 0, 1)
}
-export function isSupportedMlSessionId(sessionId: string): boolean {
+export const ML_SESSION_MAX_AGE_DAYS = 14
+export const ML_SESSION_MAX_FUTURE_DAYS = 1
+const DAY_MS = 24 * 60 * 60 * 1000
+
+export type MlSessionIdDropReason = 'session_id_not_uuid_v7' | 'session_id_too_old' | 'session_id_in_future'
+
+/** ML_SESSION_MAX_AGE_DAYS equals MONTH_DELETE_GRACE_DAYS in products/ai_training/backend/privacy/store.py, so a month opens for deletion only once no session that started in it can still arrive. */
+export function mlSessionIdDropReason(sessionId: string, nowMs: number): MlSessionIdDropReason | null {
const startedAt = sessionStartTimestampFromUuidV7(sessionId)
- return startedAt !== null && startedAt < Date.UTC(10000, 0, 1)
+ if (startedAt === null || startedAt >= Date.UTC(10000, 0, 1)) {
+ return 'session_id_not_uuid_v7'
+ }
+ if (startedAt < nowMs - ML_SESSION_MAX_AGE_DAYS * DAY_MS) {
+ return 'session_id_too_old'
+ }
+ if (startedAt > nowMs + ML_SESSION_MAX_FUTURE_DAYS * DAY_MS) {
+ return 'session_id_in_future'
+ }
+ return null
}
export function sessionStartMonth(sessionId: string): string {
diff --git a/products/ai_training/backend/management/commands/delete_ai_training_month.py b/products/ai_training/backend/management/commands/delete_ai_training_month.py
index 9396093b06b1..0b968224cd27 100644
--- a/products/ai_training/backend/management/commands/delete_ai_training_month.py
+++ b/products/ai_training/backend/management/commands/delete_ai_training_month.py
@@ -9,7 +9,7 @@ from products.ai_training.backend.privacy.store import AITrainingPrivacyStore
class Command(BaseCommand):
- help = "Permanently block an ML session month and remove its session and image keys."
+ help = "Permanently remove the session and image keys of an ML session month."
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument("session_month", help="UTC session start month, in YYYY-MM format")
diff --git a/products/ai_training/backend/privacy/reader.py b/products/ai_training/backend/privacy/reader.py
index 58abf68f12ae..c9685cc90937 100644
--- a/products/ai_training/backend/privacy/reader.py
+++ b/products/ai_training/backend/privacy/reader.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import re
import json
import time
import base64
@@ -10,7 +9,6 @@ from collections import OrderedDict
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import field
-from datetime import UTC, datetime
from threading import Lock
from typing import Protocol, TypedDict, cast
@@ -57,15 +55,6 @@ class TrainingKeyIdentity:
context["ref"] = ref
return context
- def month_block_location(self) -> TrainingKeyLocation:
- month = self.session_month
- if self.session_id:
- timestamp_ms = int(self.session_id[:8] + self.session_id[9:13], 16)
- month = datetime.fromtimestamp(timestamp_ms / 1000, UTC).strftime("%Y-%m")
- if month is None or re.fullmatch(r"[0-9]{4}-(0[1-9]|1[0-2])", month) is None:
- raise ValueError("ML key requires a session month")
- return TrainingKeyLocation(pk=f"month:{month}", sk="deleted")
-
def wrapping_context(self) -> dict[str, str]:
context = {
"purpose": "ai-research-session" if self.session_id else "ai-research-image",
@@ -194,21 +183,11 @@ class TrainingDataKeyReader:
session_month=str(row["session_month"]["S"]) if location.sk.startswith("image:") else None,
)
state = self.bulk_read(
- [
- location
- for identity in identities.values()
- for location in (
- identity.month_block_location(),
- TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted"),
- )
- ]
+ [TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted") for identity in identities.values()]
)
eligible: dict[TrainingKeyLocation, TrainingKeyIdentity] = {}
for location, identity in identities.items():
- if (
- identity.month_block_location() in state
- or TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted") in state
- ):
+ if TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted") in state:
continue
eligible[location] = identity
with ThreadPoolExecutor(max_workers=8) as executor:
diff --git a/products/ai_training/backend/privacy/store.py b/products/ai_training/backend/privacy/store.py
index 647ec27cd373..e4b4c3b7ef63 100644
--- a/products/ai_training/backend/privacy/store.py
+++ b/products/ai_training/backend/privacy/store.py
@@ -2,7 +2,7 @@ import re
import time
import hashlib
from collections.abc import Sequence
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Protocol, TypedDict, cast
from django.conf import settings
@@ -20,6 +20,8 @@ from products.ai_training.backend.privacy.reader import KEY_READ_LEASE_SECONDS
logger = structlog.get_logger(__name__)
KEY_SHARDS = 32
+# Equals ML_SESSION_MAX_AGE_DAYS in nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format.ts: ingestion drops sessions that started earlier than that, so no key for a month can appear after the month end plus this period.
+MONTH_DELETE_GRACE_DAYS = 14
DynamoItem = dict[str, dict[str, str | bool | bytes]]
@@ -47,6 +49,11 @@ def item_key(pk: str, sk: str) -> DynamoItem:
return {"pk": {"S": pk}, "sk": {"S": sk}}
+def month_end(session_month: str) -> datetime:
+ year, month = (int(part) for part in session_month.split("-"))
+ return datetime(year + month // 12, month % 12 + 1, 1, tzinfo=UTC)
+
+
def identity_digest(value: str) -> str:
return hashlib.sha256(value.encode()).hexdigest()
@@ -79,10 +86,15 @@ class AITrainingPrivacyStore:
def delete_month(self, session_month: str) -> int:
if re.fullmatch(r"[0-9]{4}-(0[1-9]|1[0-2])", session_month) is None:
raise ValueError("Session month must use YYYY-MM")
- self.client.put_item(
- TableName=self.table_name,
- Item={**item_key(f"month:{session_month}", "deleted"), "deleted": {"BOOL": True}},
- )
+ try:
+ deletable_from = month_end(session_month) + timedelta(days=MONTH_DELETE_GRACE_DAYS)
+ except ValueError as error:
+ raise ValueError("Session month must use YYYY-MM") from error
+ if timezone.now() < deletable_from:
+ raise ValueError(
+ f"Session month {session_month} can be deleted from {deletable_from:%Y-%m-%d}, "
+ f"{MONTH_DELETE_GRACE_DAYS} days after the month ends"
+ )
count = 0
for shard in range(KEY_SHARDS):
cursor = None
diff --git a/products/ai_training/backend/tests/test_privacy_reader.py b/products/ai_training/backend/tests/test_privacy_reader.py
index 754a39aedb2a..77bf0afecdbd 100644
--- a/products/ai_training/backend/tests/test_privacy_reader.py
+++ b/products/ai_training/backend/tests/test_privacy_reader.py
@@ -63,10 +63,10 @@ class TestTrainingDataKeyReader(TestCase):
self.assertIn(location, reader.read([location]))
self.assertIn(location, reader.read([location]))
self.assertEqual(kms.decrypt.call_count, 1)
- month = TrainingKeyLocation(pk="month:2025-09", sk="deleted")
- rows[month] = {**month.encoded(), "deleted": {"BOOL": True}}
+ team_block = TrainingKeyLocation(pk="team:7", sk="deleted")
+ rows[team_block] = {**team_block.encoded(), "deleted": {"BOOL": True}}
self.assertEqual(reader.read([location]), {})
- del rows[month]
+ del rows[team_block]
self.assertIn(location, reader.read([location]))
rows[location].pop("wrapped_key")
rows[location]["deleted"] = {"BOOL": True}
diff --git a/products/ai_training/backend/tests/test_privacy_store.py b/products/ai_training/backend/tests/test_privacy_store.py
index ad1d13f6f801..c2be6b21469b 100644
--- a/products/ai_training/backend/tests/test_privacy_store.py
+++ b/products/ai_training/backend/tests/test_privacy_store.py
@@ -1,5 +1,5 @@
import time
-from datetime import timedelta
+from datetime import datetime, timedelta
from unittest.mock import MagicMock, patch
@@ -30,10 +30,10 @@ class TestAITrainingPrivacyStore(SimpleTestCase):
self.assertEqual(store.called, enabled)
self.assertEqual(store.return_value.drain.called, enabled)
- def test_month_deletion_blocks_before_querying_and_shreds_all_index_pages(self) -> None:
+ def test_month_deletion_shreds_all_index_pages_without_writing_a_block(self) -> None:
client = MagicMock()
- cursor = item_key("month:2026-09:shard:0", "key:cursor")
- targets = [session_key(7, "01a09f92-e780-7000-8000-000000000001"), item_key("team:7", "image:1:2026-09")]
+ cursor = item_key("month:2025-09:shard:0", "key:cursor")
+ targets = [session_key(7, "01a09f92-e780-7000-8000-000000000001"), item_key("team:7", "image:1:2025-09")]
pages: list[DynamoResponse] = []
for index, target in enumerate(targets):
page: DynamoResponse = {"Items": [{"key_pk": target["pk"], "key_sk": target["sk"]}]}
@@ -43,13 +43,13 @@ class TestAITrainingPrivacyStore(SimpleTestCase):
pages.extend({"Items": []} for _ in range(31))
def query(**kwargs: object) -> DynamoResponse:
- self.assertEqual(client.put_item.call_args.kwargs["Item"]["pk"]["S"], "month:2026-09")
self.assertTrue(kwargs["ConsistentRead"])
return pages.pop(0)
client.query.side_effect = query
store = AITrainingPrivacyStore(client, "table")
- self.assertEqual(store.delete_month("2026-09"), 2)
+ self.assertEqual(store.delete_month("2025-09"), 2)
+ client.put_item.assert_not_called()
self.assertEqual(
[call.kwargs["TransactItems"][0]["Update"]["Key"] for call in client.transact_write_items.call_args_list],
targets,
@@ -58,6 +58,28 @@ class TestAITrainingPrivacyStore(SimpleTestCase):
self.assertEqual(client.query.call_count, 33)
with self.assertRaises(ValueError):
store.delete_month("2026-13")
+ with self.assertRaises(ValueError):
+ store.delete_month("9999-12")
+ self.assertEqual(client.query.call_count, 33)
+
+ @parameterized.expand(
+ [
+ ("2025-09", "2025-10-14T23:59:59+00:00", False),
+ ("2025-09", "2025-10-15T00:00:00+00:00", True),
+ ("2025-12", "2026-01-14T23:59:59+00:00", False),
+ ("2025-12", "2026-01-15T00:00:00+00:00", True),
+ ]
+ )
+ def test_month_deletion_opens_fourteen_days_after_the_month_ends(self, month: str, now: str, allowed: bool) -> None:
+ client = MagicMock()
+ client.query.return_value = {"Items": []}
+ store = AITrainingPrivacyStore(client, "table")
+ with patch("products.ai_training.backend.privacy.store.timezone.now", return_value=datetime.fromisoformat(now)):
+ if allowed:
+ self.assertEqual(store.delete_month(month), 0)
+ else:
+ with self.assertRaisesRegex(ValueError, "can be deleted from"):
+ store.delete_month(month)
def test_session_deletion_shreds_keys_without_querying_user_indexes(self) -> None:
client = MagicMock()
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 843ed52b5b5a..e26d66b6c5db 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -44,7 +44,7 @@ The authenticated payload also binds the dataset kind and, for images, the objec
Ingestion processes privacy state in batches:
-1. Bulk-read session keys, team blocks, month blocks, and image keys.
+1. Bulk-read session keys, team blocks, and image keys.
2. Resolve keys in memory while processing the batch.
3. Commit bounded DynamoDB transactions before publishing replay blocks or image messages.
4. On a competing write, bulk-read the winning state and retry with its keys.
@@ -106,10 +106,12 @@ Key creation writes a month index entry in the same DynamoDB transaction as the
The index uses 32 partitions named `month:<YYYY-MM>:shard:<0..31>` and stores key locations, without copying wrapped keys.
Session keys and image keys appear in this index.
-Run `python manage.py delete_ai_training_month YYYY-MM` to permanently block that UTC session month and remove its keys.
+Run `python manage.py delete_ai_training_month YYYY-MM` to remove the keys of that UTC session month.
+The mirror drops a session whose ID started more than 14 days in the past or more than 1 day in the future, and the command accepts a month from 14 days after the month ends, so a key cannot arrive after its index shard was swept.
+Neither side reads a shared block item for the month, because every commit in the fleet would contend on that one DynamoDB item.
The command uses strongly consistent queries and bounded writes.
-Rerun the command after an interrupted run; it preserves the month block and safely repeats completed pages.
-Readers reject blocked months even when a wrapped key remains during deletion.
+Rerun the command after an interrupted run; it safely repeats completed pages.
+Rerun it once for any month that an earlier version of the command deleted, because readers no longer honor the month block that version wrote.
Existing read leases expire within five minutes.
The matching monthly S3 folders can then be removed from each dataset.
Deleting a month does not affect another month's image keys.