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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
"""
Layer 1 – Virtual File System.

Stores all service codebases as in-memory strings keyed by
(service, filename).  Every task starts from a clean snapshot of
its own buggy codebase; edits accumulate on top of that snapshot.
"""
from __future__ import annotations
import copy
from typing import Dict, List, Optional, Tuple

# ---------------------------------------------------------------------------
# Buggy source code snapshots – one per task
# Each task mutates only the files it needs; unchanged files are shared via
# SHARED_FILES and merged in at reset() time.
# ---------------------------------------------------------------------------

SHARED_FILES: Dict[str, Dict[str, str]] = {
    "ad_ranking": {
        "utils.py": """\
from typing import Dict, List


def normalize_scores(ads: List[Dict]) -> List[Dict]:
    if not ads:
        return ads
    max_score = max(ad['score'] for ad in ads)
    min_score = min(ad['score'] for ad in ads)
    score_range = max_score - min_score or 1.0
    return [
        {**ad, 'normalized_score': (ad['score'] - min_score) / score_range}
        for ad in ads
    ]


def filter_by_budget(ads: List[Dict], daily_budget_cents: int) -> List[Dict]:
    return [ad for ad in ads if ad.get('spend_today_cents', 0) < daily_budget_cents]


def compute_roas(revenue: float, spend: float) -> float:
    return revenue / spend if spend > 0 else 0.0
""",
        "models.py": """\
from dataclasses import dataclass, field
from typing import List, Optional


@dataclass
class Ad:
    ad_id: str
    campaign_id: str
    category: str
    target_age: str
    clicks: int = 0
    impressions: int = 0
    spend_today_cents: int = 0
    active: bool = True
    score: float = 0.0


@dataclass
class UserContext:
    user_id: str
    interest: str
    age_group: str
    country: str
""",
    },
    "capi_pipeline": {
        "validator.py": """\
from typing import Dict, Any


REQUIRED_FIELDS = {'event_name', 'event_time', 'event_id'}


def validate_event(event: Dict[str, Any]) -> Tuple[bool, str]:
    missing = REQUIRED_FIELDS - set(event.keys())
    if missing:
        return False, f'Missing fields: {missing}'
    if not isinstance(event.get('event_time'), (int, float)):
        return False, 'event_time must be numeric'
    return True, 'ok'
""",
    },
    "whatsapp_sync": {
        "models.py": """\
from dataclasses import dataclass
from typing import Optional


@dataclass
class Message:
    id: int
    user_id: int
    sender_id: int
    content: str
    timestamp: int
    synced: bool = False
    thread_id: Optional[int] = None
""",
    },
}


# ---------------------------------------------------------------------------
# Task-specific buggy snapshots
# ---------------------------------------------------------------------------

TASK_SNAPSHOTS: Dict[int, Dict[str, Dict[str, str]]] = {

    # ------------------------------------------------------------------
    # Task 1 – Easy: Hallucinated attribute (ad.get_clicks())
    # ------------------------------------------------------------------
    1: {
        "ad_ranking": {
            "ranker.py": """\
import logging
from typing import List, Dict

logger = logging.getLogger(__name__)


class AdRanker:
    \"\"\"Scores and ranks candidate ads for a user.\"\"\"

    def __init__(self, api_client):
        self.api = api_client
        self.model_version = "v2.3.1"
        self._cache = {}

    def fetch_candidate_ads(self, user_id: str) -> List[Dict]:
        ads = self.api.get_all_ads(user_id)
        return [ad for ad in ads if ad.get('active', False)]

    def score_ads(self, ads: List[Dict], user_context: Dict) -> List[Dict]:
        scored = []
        for ad in ads:
            click_rate = ad.get_clicks() / max(ad.get('impressions', 1), 1)
            relevance = self._compute_relevance(ad, user_context)
            score = (click_rate * 0.4) + (relevance * 0.6)
            scored.append({**ad, 'score': round(score, 4)})
        return sorted(scored, key=lambda x: x['score'], reverse=True)

    def _compute_relevance(self, ad: Dict, context: Dict) -> float:
        category_match = 1.0 if ad.get('category') == context.get('interest') else 0.3
        age_match = 1.0 if ad.get('target_age') == context.get('age_group') else 0.5
        return round((category_match + age_match) / 2.0, 4)

    def rank(self, user_id: str, user_context: Dict) -> List[Dict]:
        candidates = self.fetch_candidate_ads(user_id)
        if not candidates:
            logger.warning(f"No candidates for user {user_id}")
            return []
        return self.score_ads(candidates, user_context)
""",
        },
    },

    # ------------------------------------------------------------------
    # Task 2 – Medium: Silent timestamp corruption in CAPI β†’ bad ROAS
    # ------------------------------------------------------------------
    2: {
        "capi_pipeline": {
            "transformer.py": """\
import logging
from typing import Dict, Any, List
from datetime import datetime

logger = logging.getLogger(__name__)


class EventTransformer:
    \"\"\"Transforms raw CAPI events into normalised format.\"\"\"

    SUPPORTED_EVENTS = {
        'Purchase', 'AddToCart', 'ViewContent', 'Lead', 'CompleteRegistration'
    }

    def __init__(self):
        self._processed_count = 0

    def transform(self, raw_event: Dict[str, Any]) -> Dict[str, Any]:
        if raw_event.get('event_name') not in self.SUPPORTED_EVENTS:
            logger.warning(f"Unknown event type: {raw_event.get('event_name')}")
            return None

        event_time = self._normalize_timestamp(raw_event.get('event_time', 0))

        transformed = {
            'event_id':    raw_event.get('event_id'),
            'event_name':  raw_event.get('event_name'),
            'event_time':  event_time,
            'user_data':   self._hash_user_data(raw_event.get('user_data', {})),
            'custom_data': raw_event.get('custom_data', {}),
            'processed_at': int(datetime.utcnow().timestamp()),
        }
        self._processed_count += 1
        return transformed

    def _normalize_timestamp(self, ts: Any) -> int:
        \"\"\"Normalise event timestamp to Unix seconds.\"\"\"
        ts = int(ts)
        # BUG: threshold is 1_000_000_000 (10 digits) instead of
        #      1_000_000_000_000 (13 digits for milliseconds).
        #      A normal unix-second timestamp like 1_700_000_000 passes the
        #      condition and gets divided by 1000 β†’ year ~1970+20 days.
        if ts > 1_000_000_000:
            return ts // 1000
        return ts

    def _hash_user_data(self, user_data: Dict) -> Dict:
        import hashlib
        hashed = {}
        for key, val in user_data.items():
            if key in ('email', 'phone', 'fn', 'ln'):
                hashed[key] = hashlib.sha256(
                    str(val).lower().encode()
                ).hexdigest()
            else:
                hashed[key] = val
        return hashed

    def batch_transform(self, events: List[Dict]) -> List[Dict]:
        return [t for e in events if (t := self.transform(e)) is not None]
""",
            "ingestor.py": """\
import logging
from typing import Dict, Any
from .transformer import EventTransformer

logger = logging.getLogger(__name__)


class EventIngestor:
    \"\"\"Ingests and validates CAPI event payloads.\"\"\"

    def __init__(self, transformer: EventTransformer):
        self.transformer = transformer
        self._event_buffer = []

    def ingest(self, raw_payload: Dict[str, Any]) -> Dict[str, Any]:
        try:
            events = raw_payload.get('data', [])
            if not events:
                return {'status': 'error', 'message': 'No events in payload'}
            transformed = self.transformer.batch_transform(events)
            self._event_buffer.extend(transformed)
            return {'status': 'ok', 'processed': len(transformed)}
        except Exception as e:
            logger.error(f"Ingest failed: {e}", exc_info=True)
            return {'status': 'error', 'message': str(e)}

    def flush(self) -> int:
        count = len(self._event_buffer)
        self._event_buffer.clear()
        logger.info(f"Flushed {count} events")
        return count
""",
        },
        "ad_ranking": {
            "ranker.py": """\
import logging
from typing import List, Dict

logger = logging.getLogger(__name__)


class AdRanker:
    \"\"\"Scores and ranks candidate ads for a user.\"\"\"

    def __init__(self, api_client):
        self.api = api_client
        self.model_version = "v2.3.1"

    def fetch_candidate_ads(self, user_id: str) -> List[Dict]:
        ads = self.api.get_all_ads(user_id)
        return [ad for ad in ads if ad.get('active', False)]

    def score_ads(self, ads: List[Dict], user_context: Dict) -> List[Dict]:
        scored = []
        for ad in ads:
            click_rate = ad.get('clicks', 0) / max(ad.get('impressions', 1), 1)
            relevance = self._compute_relevance(ad, user_context)
            score = (click_rate * 0.4) + (relevance * 0.6)
            scored.append({**ad, 'score': round(score, 4)})
        return sorted(scored, key=lambda x: x['score'], reverse=True)

    def _compute_relevance(self, ad: Dict, context: Dict) -> float:
        category_match = 1.0 if ad.get('category') == context.get('interest') else 0.3
        age_match = 1.0 if ad.get('target_age') == context.get('age_group') else 0.5
        return round((category_match + age_match) / 2.0, 4)

    def rank(self, user_id: str, user_context: Dict) -> List[Dict]:
        candidates = self.fetch_candidate_ads(user_id)
        if not candidates:
            logger.warning(f"No candidates for user {user_id}")
            return []
        return self.score_ads(candidates, user_context)
""",
        },
    },

    # ------------------------------------------------------------------
    # Task 3 – Medium-Hard: DB connection leak in WhatsApp sync handler
    # ------------------------------------------------------------------
    3: {
        "whatsapp_sync": {
            "handler.py": """\
import asyncio
import logging
from typing import List, Dict

logger = logging.getLogger(__name__)


class MessageSyncHandler:
    \"\"\"Handles real-time WhatsApp message synchronisation.\"\"\"

    def __init__(self, db_pool, message_queue):
        self.db_pool = db_pool
        self.queue = message_queue
        self._sync_count = 0

    async def sync_user_messages(self, user_id: str) -> List[Dict]:
        \"\"\"Fetch and mark-as-synced all pending messages for a user.\"\"\"
        conn = await self.db_pool.acquire()
        try:
            messages = await conn.fetch(
                "SELECT id, content, sender_id, timestamp "
                "FROM messages WHERE user_id = $1 AND synced = FALSE "
                "ORDER BY timestamp",
                user_id,
            )
            processed = []
            for msg in messages:
                await conn.execute(
                    "UPDATE messages SET synced = TRUE WHERE id = $1",
                    msg['id'],
                )
                processed.append(dict(msg))
            self._sync_count += len(processed)
            return processed
        except Exception as e:
            logger.error(f"Sync failed for user {user_id}: {e}")
            raise
        # BUG: missing `finally: await self.db_pool.release(conn)`
        # Under load the pool exhausts β†’ all sync requests hang indefinitely.

    async def process_queue(self, batch_size: int = 50) -> int:
        processed = 0
        while processed < batch_size:
            try:
                user_id = await asyncio.wait_for(
                    self.queue.get(), timeout=1.0
                )
                await self.sync_user_messages(user_id)
                processed += 1
            except asyncio.TimeoutError:
                break
        return processed
""",
            "db.py": """\
import logging
from typing import Dict, List

logger = logging.getLogger(__name__)

MIGRATIONS: List[Dict] = [
    {
        "version": "001",
        "description": "Create messages table",
        "up": (
            "CREATE TABLE messages ("
            "    id SERIAL PRIMARY KEY,"
            "    user_id INTEGER NOT NULL,"
            "    content TEXT,"
            "    sender_id INTEGER,"
            "    timestamp BIGINT,"
            "    synced BOOLEAN DEFAULT FALSE"
            ");"
        ),
    },
]


class MigrationRunner:
    def __init__(self, db_conn):
        self.conn = db_conn
        self._applied: List[str] = []

    async def apply(self, migration: Dict) -> bool:
        await self.conn.execute(migration['up'])
        self._applied.append(migration['version'])
        logger.info(f"Applied migration {migration['version']}")
        return True
""",
        },
    },

    # ------------------------------------------------------------------
    # Task 4 – Hard: Red-herring cascade from a bad DB migration (003)
    # ------------------------------------------------------------------
    4: {
        "whatsapp_sync": {
            "db.py": """\
import logging
from typing import Dict, List

logger = logging.getLogger(__name__)

# Migration 003 introduces a circular FK:
#   message_threads.parent_message_id β†’ messages.id
#   messages.thread_id                β†’ message_threads.id
# PostgreSQL refuses the self-referential constraint during ALTER TABLE,
# causing FK violation errors that cascade to all consumers of both tables.

MIGRATIONS: List[Dict] = [
    {
        "version": "001",
        "description": "Create messages table",
        "up": (
            "CREATE TABLE IF NOT EXISTS messages ("
            "    id SERIAL PRIMARY KEY,"
            "    user_id INTEGER NOT NULL,"
            "    content TEXT,"
            "    sender_id INTEGER,"
            "    timestamp BIGINT,"
            "    synced BOOLEAN DEFAULT FALSE"
            ");"
        ),
    },
    {
        "version": "002",
        "description": "Add user preferences",
        "up": (
            "CREATE TABLE IF NOT EXISTS user_preferences ("
            "    id SERIAL PRIMARY KEY,"
            "    user_id INTEGER NOT NULL,"
            "    notification_enabled BOOLEAN DEFAULT TRUE,"
            "    sync_frequency INTEGER DEFAULT 30"
            ");"
        ),
    },
    {
        "version": "003",
        "description": "Add message threads with back-reference",
        "up": (
            "CREATE TABLE IF NOT EXISTS message_threads ("
            "    id SERIAL PRIMARY KEY,"
            "    parent_message_id INTEGER REFERENCES messages(id) ON DELETE CASCADE,"
            "    participant_ids INTEGER[] NOT NULL,"
            "    created_at BIGINT"
            ");"
            "ALTER TABLE messages"
            "    ADD COLUMN thread_id INTEGER REFERENCES message_threads(id);"
        ),
        # BUG: circular FK β€” messages β†’ message_threads β†’ messages
        # Fix: remove the ALTER TABLE line (messages should NOT reference threads)
    },
]


class MigrationRunner:
    def __init__(self, db_conn):
        self.conn = db_conn
        self._applied: List[str] = []

    async def apply(self, migration: Dict) -> bool:
        await self.conn.execute(migration['up'])
        self._applied.append(migration['version'])
        logger.info(f"Applied migration {migration['version']}: {migration['description']}")
        return True

    async def rollback_version(self, version: str) -> bool:
        logger.warning(f"Rolling back migration {version}")
        self._applied = [v for v in self._applied if v != version]
        return True

    async def run_all(self):
        for migration in MIGRATIONS:
            await self.apply(migration)
""",
            "handler.py": """\
import asyncio
import logging
from typing import List, Dict

logger = logging.getLogger(__name__)


class MessageSyncHandler:
    def __init__(self, db_pool, message_queue):
        self.db_pool = db_pool
        self.queue = message_queue
        self._sync_count = 0

    async def sync_user_messages(self, user_id: str) -> List[Dict]:
        conn = await self.db_pool.acquire()
        try:
            messages = await conn.fetch(
                "SELECT id, content, sender_id, timestamp "
                "FROM messages WHERE user_id = $1 AND synced = FALSE "
                "ORDER BY timestamp",
                user_id,
            )
            processed = []
            for msg in messages:
                await conn.execute(
                    "UPDATE messages SET synced = TRUE WHERE id = $1",
                    msg['id'],
                )
                processed.append(dict(msg))
            self._sync_count += len(processed)
            return processed
        except Exception as e:
            logger.error(f"Sync failed for user {user_id}: {e}")
            raise
        finally:
            await self.db_pool.release(conn)

    async def process_queue(self, batch_size: int = 50) -> int:
        processed = 0
        while processed < batch_size:
            try:
                user_id = await asyncio.wait_for(
                    self.queue.get(), timeout=1.0
                )
                await self.sync_user_messages(user_id)
                processed += 1
            except asyncio.TimeoutError:
                break
        return processed
""",
        },
        "capi_pipeline": {
            "ingestor.py": """\
import logging
from typing import Dict, Any
from .transformer import EventTransformer

logger = logging.getLogger(__name__)


class EventIngestor:
    def __init__(self, transformer: EventTransformer):
        self.transformer = transformer
        self._event_buffer = []

    def ingest(self, raw_payload: Dict[str, Any]) -> Dict[str, Any]:
        try:
            events = raw_payload.get('data', [])
            if not events:
                return {'status': 'error', 'message': 'No events in payload'}
            transformed = self.transformer.batch_transform(events)
            self._event_buffer.extend(transformed)
            return {'status': 'ok', 'processed': len(transformed)}
        except Exception as e:
            logger.error(f"Ingest failed: {e}", exc_info=True)
            return {'status': 'error', 'message': str(e)}

    def flush(self) -> int:
        count = len(self._event_buffer)
        self._event_buffer.clear()
        return count
""",
            "transformer.py": """\
import logging
from typing import Dict, Any, List
from datetime import datetime

logger = logging.getLogger(__name__)


class EventTransformer:
    SUPPORTED_EVENTS = {
        'Purchase', 'AddToCart', 'ViewContent', 'Lead', 'CompleteRegistration'
    }

    def __init__(self):
        self._processed_count = 0

    def transform(self, raw_event: Dict[str, Any]) -> Dict[str, Any]:
        if raw_event.get('event_name') not in self.SUPPORTED_EVENTS:
            return None
        event_time = self._normalize_timestamp(raw_event.get('event_time', 0))
        transformed = {
            'event_id':    raw_event.get('event_id'),
            'event_name':  raw_event.get('event_name'),
            'event_time':  event_time,
            'user_data':   raw_event.get('user_data', {}),
            'custom_data': raw_event.get('custom_data', {}),
            'processed_at': int(datetime.utcnow().timestamp()),
        }
        self._processed_count += 1
        return transformed

    def _normalize_timestamp(self, ts: Any) -> int:
        ts = int(ts)
        if ts > 1_000_000_000_000:
            return ts // 1000
        return ts

    def batch_transform(self, events: List[Dict]) -> List[Dict]:
        return [t for e in events if (t := self.transform(e)) is not None]
""",
        },
        "ad_ranking": {
            "ranker.py": """\
import logging
from typing import List, Dict

logger = logging.getLogger(__name__)


class AdRanker:
    def __init__(self, api_client):
        self.api = api_client
        self.model_version = "v2.3.1"

    def fetch_candidate_ads(self, user_id: str) -> List[Dict]:
        ads = self.api.get_all_ads(user_id)
        return [ad for ad in ads if ad.get('active', False)]

    def score_ads(self, ads: List[Dict], user_context: Dict) -> List[Dict]:
        scored = []
        for ad in ads:
            click_rate = ad.get('clicks', 0) / max(ad.get('impressions', 1), 1)
            relevance = self._compute_relevance(ad, user_context)
            score = (click_rate * 0.4) + (relevance * 0.6)
            scored.append({**ad, 'score': round(score, 4)})
        return sorted(scored, key=lambda x: x['score'], reverse=True)

    def _compute_relevance(self, ad: Dict, context: Dict) -> float:
        category_match = 1.0 if ad.get('category') == context.get('interest') else 0.3
        age_match = 1.0 if ad.get('target_age') == context.get('age_group') else 0.5
        return round((category_match + age_match) / 2.0, 4)

    def rank(self, user_id: str, user_context: Dict) -> List[Dict]:
        candidates = self.fetch_candidate_ads(user_id)
        if not candidates:
            return []
        return self.score_ads(candidates, user_context)
""",
        },
    },

    # ------------------------------------------------------------------
    # Task 5 – Hard: PII data-leak via DEBUG_MODE=True in production
    # ------------------------------------------------------------------
    5: {
        "capi_pipeline": {
            "ingestor.py": """\
import logging
from typing import Dict, Any
from .transformer import EventTransformer

logger = logging.getLogger(__name__)

DEBUG_MODE = True   # BUG: must be False in production – leaks raw user PII


class EventIngestor:
    \"\"\"Ingests and validates CAPI event payloads.\"\"\"

    def __init__(self, transformer: EventTransformer):
        self.transformer = transformer
        self._event_buffer = []

    def ingest(self, raw_payload: Dict[str, Any]) -> Dict[str, Any]:
        try:
            events = raw_payload.get('data', [])
            if not events:
                return {'status': 'error', 'message': 'No events in payload'}

            transformed = self.transformer.batch_transform(events)
            self._event_buffer.extend(transformed)

            if DEBUG_MODE:
                # SECURITY BUG: exposes raw PII (emails, phone numbers) in the
                # HTTP response – visible in CDN logs, browser network tabs, etc.
                return {
                    'status': 'ok',
                    'processed': len(transformed),
                    'debug_data': {
                        'raw_payload':  raw_payload,
                        'user_emails':  [e.get('user_data', {}) for e in events],
                        'buffer_state': self._event_buffer,
                    },
                }

            return {'status': 'ok', 'processed': len(transformed)}

        except Exception as e:
            logger.error(f"Ingest failed: {e}", exc_info=True)
            return {'status': 'error', 'message': str(e)}

    def flush(self) -> int:
        count = len(self._event_buffer)
        self._event_buffer.clear()
        logger.info(f"Flushed {count} events")
        return count
""",
            "transformer.py": """\
import logging
from typing import Dict, Any, List
from datetime import datetime

logger = logging.getLogger(__name__)


class EventTransformer:
    SUPPORTED_EVENTS = {
        'Purchase', 'AddToCart', 'ViewContent', 'Lead', 'CompleteRegistration'
    }

    def __init__(self):
        self._processed_count = 0

    def transform(self, raw_event: Dict[str, Any]) -> Dict[str, Any]:
        if raw_event.get('event_name') not in self.SUPPORTED_EVENTS:
            return None
        event_time = self._normalize_timestamp(raw_event.get('event_time', 0))
        transformed = {
            'event_id':    raw_event.get('event_id'),
            'event_name':  raw_event.get('event_name'),
            'event_time':  event_time,
            'user_data':   self._hash_user_data(raw_event.get('user_data', {})),
            'custom_data': raw_event.get('custom_data', {}),
            'processed_at': int(datetime.utcnow().timestamp()),
        }
        self._processed_count += 1
        return transformed

    def _normalize_timestamp(self, ts: Any) -> int:
        ts = int(ts)
        if ts > 1_000_000_000_000:
            return ts // 1000
        return ts

    def _hash_user_data(self, user_data: Dict) -> Dict:
        import hashlib
        hashed = {}
        for key, val in user_data.items():
            if key in ('email', 'phone', 'fn', 'ln'):
                hashed[key] = hashlib.sha256(
                    str(val).lower().encode()
                ).hexdigest()
            else:
                hashed[key] = val
        return hashed

    def batch_transform(self, events: List[Dict]) -> List[Dict]:
        return [t for e in events if (t := self.transform(e)) is not None]
""",
        },
        "ad_ranking": {
            "ranker.py": """\
import logging
from typing import List, Dict

logger = logging.getLogger(__name__)


class AdRanker:
    def __init__(self, api_client):
        self.api = api_client
        self.model_version = "v2.3.1"

    def fetch_candidate_ads(self, user_id: str) -> List[Dict]:
        ads = self.api.get_all_ads(user_id)
        return [ad for ad in ads if ad.get('active', False)]

    def score_ads(self, ads: List[Dict], user_context: Dict) -> List[Dict]:
        scored = []
        for ad in ads:
            click_rate = ad.get('clicks', 0) / max(ad.get('impressions', 1), 1)
            relevance = self._compute_relevance(ad, user_context)
            score = (click_rate * 0.4) + (relevance * 0.6)
            scored.append({**ad, 'score': round(score, 4)})
        return sorted(scored, key=lambda x: x['score'], reverse=True)

    def _compute_relevance(self, ad: Dict, context: Dict) -> float:
        category_match = 1.0 if ad.get('category') == context.get('interest') else 0.3
        age_match = 1.0 if ad.get('target_age') == context.get('age_group') else 0.5
        return round((category_match + age_match) / 2.0, 4)

    def rank(self, user_id: str, user_context: Dict) -> List[Dict]:
        candidates = self.fetch_candidate_ads(user_id)
        if not candidates:
            return []
        return self.score_ads(candidates, user_context)
""",
        },
        "whatsapp_sync": {
            "handler.py": """\
import asyncio
import logging
from typing import List, Dict

logger = logging.getLogger(__name__)


class MessageSyncHandler:
    def __init__(self, db_pool, message_queue):
        self.db_pool = db_pool
        self.queue = message_queue
        self._sync_count = 0

    async def sync_user_messages(self, user_id: str) -> List[Dict]:
        conn = await self.db_pool.acquire()
        try:
            messages = await conn.fetch(
                "SELECT id, content, sender_id, timestamp "
                "FROM messages WHERE user_id = $1 AND synced = FALSE "
                "ORDER BY timestamp",
                user_id,
            )
            processed = []
            for msg in messages:
                await conn.execute(
                    "UPDATE messages SET synced = TRUE WHERE id = $1",
                    msg['id'],
                )
                processed.append(dict(msg))
            self._sync_count += len(processed)
            return processed
        except Exception as e:
            logger.error(f"Sync failed for user {user_id}: {e}")
            raise
        finally:
            await self.db_pool.release(conn)

    async def process_queue(self, batch_size: int = 50) -> int:
        processed = 0
        while processed < batch_size:
            try:
                user_id = await asyncio.wait_for(
                    self.queue.get(), timeout=1.0
                )
                await self.sync_user_messages(user_id)
                processed += 1
            except asyncio.TimeoutError:
                break
        return processed
""",
            "db.py": """\
import logging
from typing import Dict, List

logger = logging.getLogger(__name__)

MIGRATIONS: List[Dict] = [
    {
        "version": "001",
        "description": "Create messages table",
        "up": (
            "CREATE TABLE IF NOT EXISTS messages ("
            "    id SERIAL PRIMARY KEY,"
            "    user_id INTEGER NOT NULL,"
            "    content TEXT,"
            "    sender_id INTEGER,"
            "    timestamp BIGINT,"
            "    synced BOOLEAN DEFAULT FALSE"
            ");"
        ),
    },
]


class MigrationRunner:
    def __init__(self, db_conn):
        self.conn = db_conn
        self._applied: List[str] = []

    async def apply(self, migration: Dict) -> bool:
        await self.conn.execute(migration['up'])
        self._applied.append(migration['version'])
        return True
""",
        },
    },
}


# ---------------------------------------------------------------------------
# VirtualFileSystem
# ---------------------------------------------------------------------------

class EditRecord:
    __slots__ = ("step", "service", "filename", "line_idx", "old_code", "new_code")

    def __init__(self, step, service, filename, line_idx, old_code, new_code):
        self.step = step
        self.service = service
        self.filename = filename
        self.line_idx = line_idx
        self.old_code = old_code
        self.new_code = new_code

    def to_dict(self):
        return {
            "step": self.step,
            "service": self.service,
            "filename": self.filename,
            "line_number": self.line_idx + 1,
            "old_code": self.old_code,
            "new_code": self.new_code,
        }


class VirtualFileSystem:
    """In-memory multi-service file system with history tracking."""

    def __init__(self):
        self._files: Dict[str, Dict[str, str]] = {}
        self._history: List[EditRecord] = []
        self._task_id: int = 0

    # ------------------------------------------------------------------
    # Lifecycle
    # ------------------------------------------------------------------

    def reset(self, task_id: int) -> None:
        """Load the buggy snapshot for a specific task."""
        self._task_id = task_id
        self._history.clear()

        snapshot = TASK_SNAPSHOTS.get(task_id, {})
        # Start from shared base, then overlay task-specific files
        merged: Dict[str, Dict[str, str]] = {}
        for service, files in SHARED_FILES.items():
            merged[service] = dict(files)
        for service, files in snapshot.items():
            if service not in merged:
                merged[service] = {}
            merged[service].update(files)

        self._files = merged

    # ------------------------------------------------------------------
    # Read
    # ------------------------------------------------------------------

    def list_files(self, service: str) -> List[str]:
        return sorted(self._files.get(service, {}).keys())

    def list_services(self) -> List[str]:
        return sorted(self._files.keys())

    def read_file(self, service: str, filename: str) -> Tuple[bool, str]:
        """Return (found, content)."""
        content = self._files.get(service, {}).get(filename)
        if content is None:
            return False, f"File not found: {service}/{filename}"
        return True, content

    def get_file_lines(self, service: str, filename: str) -> Optional[List[str]]:
        found, content = self.read_file(service, filename)
        if not found:
            return None
        return content.splitlines()

    # ------------------------------------------------------------------
    # Write
    # ------------------------------------------------------------------

    def edit_line(
        self,
        service: str,
        filename: str,
        line_number: int,      # 1-based
        new_code: str,
        step: int = 0,
    ) -> Tuple[bool, str]:
        """Replace a single line (1-based). Returns (success, message)."""
        lines = self.get_file_lines(service, filename)
        if lines is None:
            return False, f"File not found: {service}/{filename}"

        idx = line_number - 1
        if not (0 <= idx < len(lines)):
            return False, f"Line {line_number} out of range (file has {len(lines)} lines)"

        old_code = lines[idx]
        lines[idx] = new_code
        self._files[service][filename] = "\n".join(lines)

        self._history.append(
            EditRecord(step, service, filename, idx, old_code, new_code)
        )
        return True, "ok"

    # ------------------------------------------------------------------
    # History / blame
    # ------------------------------------------------------------------

    def get_edit_history(
        self,
        service: Optional[str] = None,
        filename: Optional[str] = None,
    ) -> List[dict]:
        records = self._history
        if service:
            records = [r for r in records if r.service == service]
        if filename:
            records = [r for r in records if r.filename == filename]
        return [r.to_dict() for r in records]

    def git_blame(self, service: str, filename: str, line_number: int) -> str:
        """Return the last edit record for a specific line, or 'AI-generated' if untouched."""
        idx = line_number - 1
        matching = [
            r for r in reversed(self._history)
            if r.service == service and r.filename == filename and r.line_idx == idx
        ]
        if matching:
            r = matching[0]
            return (
                f"Step {r.step}: agent changed line {line_number} in "
                f"{service}/{filename}\n"
                f"  - {r.old_code!r}\n"
                f"  + {r.new_code!r}"
            )
        return (
            f"Line {line_number} in {service}/{filename} was last modified by: "
            f"Junior AI code-gen bot (commit a3f91b2, 2026-04-23 02:14 UTC)"
        )

    def build_git_diff(self) -> Optional[str]:
        if not self._history:
            return None
        lines = [f"--- Task {self._task_id} working diff ---"]
        for r in self._history:
            lines.append(
                f"@@ {r.service}/{r.filename} line {r.line_idx + 1} @@\n"
                f"-{r.old_code}\n"
                f"+{r.new_code}"
            )
        return "\n".join(lines)