File size: 60,358 Bytes
ed663e5
80a02b9
ed663e5
 
80a02b9
 
 
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
ed663e5
 
 
 
80a02b9
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
ed663e5
 
80a02b9
ed663e5
 
 
8d1b820
 
ed663e5
8d1b820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d1b820
ed663e5
 
8d1b820
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
8d1b820
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d1b820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
8d1b820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
80a02b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
 
80a02b9
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d1b820
 
 
 
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
 
 
 
 
 
ed663e5
 
 
 
80a02b9
ed663e5
 
 
 
 
80a02b9
 
 
 
 
 
ed663e5
 
 
 
 
 
 
 
80a02b9
ed663e5
80a02b9
ed663e5
 
 
80a02b9
ed663e5
 
80a02b9
 
ed663e5
 
 
 
 
80a02b9
ed663e5
 
80a02b9
ed663e5
 
 
 
 
 
 
 
 
 
 
80a02b9
ed663e5
80a02b9
ed663e5
80a02b9
 
 
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
ed663e5
80a02b9
ed663e5
 
 
80a02b9
 
 
 
 
 
 
 
 
 
 
 
ed663e5
 
80a02b9
 
 
ed663e5
 
80a02b9
 
 
 
 
 
 
ed663e5
 
80a02b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
ed663e5
 
80a02b9
ed663e5
 
 
 
 
 
 
80a02b9
 
 
ed663e5
 
 
80a02b9
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed663e5
 
 
 
 
 
 
80a02b9
 
 
 
ed663e5
 
80a02b9
 
 
ed663e5
 
 
80a02b9
 
 
 
 
 
 
 
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
 
 
 
 
 
 
 
 
ed663e5
 
80a02b9
 
 
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
 
ed663e5
 
 
 
 
 
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
#!/usr/bin/env python3
"""Synthetic secret-injection dataset generator with cross-document coreference (v3).

Streams permissively-licensed files from codeparrot/github-code-clean (parquet shards
on the Hugging Face Hub), groups files into clusters (real multi-file repos, synthetic
"bundles" of unrelated files, or singletons), gives every cluster an entity pool of
secrets / emails / synthetic persons, injects format-correct synthetic secrets at
positions drawn from Samsung/CredData placement priors (priors.json) with entities
recurring across the files of a cluster, injects labeled hard negatives, and writes
span-labeled JSONL plus a per-cluster entity table (gold replacements included).

Examples
  # 2 GB using the first shards, 4 worker processes, downloading shards on the fly
  python generate_dataset.py --out /data/poc --target-bytes 2e9 --workers 4

  # scale: ~40 GB
  python generate_dataset.py --out /data/full --target-bytes 40e9 --workers 8 --start-shard 0

  # use pre-downloaded shards
  python generate_dataset.py --out /data/poc --shard-dir ./shards --target-bytes 2e9

Dependencies: python>=3.9, pyarrow, faker (stdlib otherwise).
"""
import argparse, base64, hashlib, json, os, random, re, string, sys, time, unicodedata, uuid, urllib.request
from multiprocessing import Pool

try:
    import pyarrow.parquet as pq
    import pyarrow.compute as pc
except ImportError:
    sys.exit("pip install pyarrow")
try:
    from faker import Faker
except ImportError:
    sys.exit("pip install faker")

HF_URL = "https://huggingface.co/datasets/codeparrot/github-code-clean/resolve/main/data/train-{i:05d}-of-00880.parquet"
N_SHARDS = 880
PERMISSIVE = {"mit", "apache-2.0", "bsd-3-clause", "bsd-2-clause", "isc", "unlicense", "cc0-1.0"}

# --------------------------------------------------------------------------------------
# Language syntax table: comment prefix, assignment template, quote char, extra forms
# --------------------------------------------------------------------------------------
# assign: how a hardcoded variable looks. {n}=name {q}=quote {v}=value
LANG = {
    "Python":      dict(c="#", assign=["{n} = {q}{v}{q}", "{N} = {q}{v}{q}", "self.{n} = {q}{v}{q}", "os.environ[{q}{N}{q}] = {q}{v}{q}"], q=["'", '"'], kw=["{q}{n}{q}: {q}{v}{q},", "{n}={q}{v}{q},"]),
    "JavaScript":  dict(c="//", assign=["const {n} = {q}{v}{q};", "let {n} = {q}{v}{q};", "var {n} = {q}{v}{q};", "const {N} = {q}{v}{q};", "process.env.{N} = {q}{v}{q};"], q=["'", '"', "`"], kw=["{n}: {q}{v}{q},", "{q}{n}{q}: {q}{v}{q},"]),
    "TypeScript":  dict(c="//", assign=["const {n} = {q}{v}{q};", "private {n} = {q}{v}{q};", "const {N}: string = {q}{v}{q};", "export const {N} = {q}{v}{q};"], q=["'", '"'], kw=["{n}: {q}{v}{q},"]),
    "Java":        dict(c="//", assign=["String {n} = {q}{v}{q};", "private static final String {N} = {q}{v}{q};", "final String {n} = {q}{v}{q};"], q=['"'], kw=["props.setProperty({q}{n}{q}, {q}{v}{q});"]),
    "C#":          dict(c="//", assign=["string {n} = {q}{v}{q};", "private const string {N} = {q}{v}{q};", "var {n} = {q}{v}{q};"], q=['"'], kw=["[{q}{n}{q}] = {q}{v}{q},"]),
    "GO":          dict(c="//", assign=["{n} := {q}{v}{q}", "const {n} = {q}{v}{q}", "var {n} = {q}{v}{q}", "{N} = {q}{v}{q}"], q=['"', "`"], kw=["{q}{n}{q}: {q}{v}{q},", "{n}: {q}{v}{q},"]),
    "PHP":         dict(c="//", assign=["${n} = {q}{v}{q};", "define({q}{N}{q}, {q}{v}{q});", "$config[{q}{n}{q}] = {q}{v}{q};"], q=["'", '"'], kw=["{q}{n}{q} => {q}{v}{q},"]),
    "Ruby":        dict(c="#", assign=["{n} = {q}{v}{q}", "{N} = {q}{v}{q}", "@{n} = {q}{v}{q}", "ENV[{q}{N}{q}] = {q}{v}{q}"], q=["'", '"'], kw=["{n}: {q}{v}{q},", ":{n} => {q}{v}{q},"]),
    "C":           dict(c="//", assign=["const char *{n} = {q}{v}{q};", "static const char {n}[] = {q}{v}{q};", "#define {N} {q}{v}{q}"], q=['"'], kw=[]),
    "C++":         dict(c="//", assign=["const std::string {n} = {q}{v}{q};", "std::string {n} = {q}{v}{q};", "#define {N} {q}{v}{q}", "static const char* {n} = {q}{v}{q};"], q=['"'], kw=[]),
    "Rust":        dict(c="//", assign=["let {n} = {q}{v}{q};", "const {N}: &str = {q}{v}{q};", "static {N}: &str = {q}{v}{q};"], q=['"'], kw=[]),
    "Scala":       dict(c="//", assign=["val {n} = {q}{v}{q}", "private val {n} = {q}{v}{q}"], q=['"'], kw=["{q}{n}{q} -> {q}{v}{q},"]),
    "Kotlin":      dict(c="//", assign=["val {n} = {q}{v}{q}", "const val {N} = {q}{v}{q}"], q=['"'], kw=[]),
    "Shell":       dict(c="#", assign=["{N}={q}{v}{q}", "export {N}={q}{v}{q}", "{n}={q}{v}{q}"], q=['"', "'", ""], kw=["--{n} {q}{v}{q} \\"]),
    "PowerShell":  dict(c="#", assign=["${n} = {q}{v}{q}", "$env:{N} = {q}{v}{q}"], q=['"', "'"], kw=[]),
    "Batchfile":   dict(c="REM", assign=["set {N}={v}", "SET {N}={v}"], q=[""], kw=[]),
    "Perl":        dict(c="#", assign=["my ${n} = {q}{v}{q};", "${n} = {q}{v}{q};"], q=["'", '"'], kw=["{n} => {q}{v}{q},"]),
    "Lua":         dict(c="--", assign=["local {n} = {q}{v}{q}", "{n} = {q}{v}{q}"], q=['"', "'"], kw=["{n} = {q}{v}{q},"]),
    "Julia":       dict(c="#", assign=["{n} = {q}{v}{q}", "const {N} = {q}{v}{q}"], q=['"'], kw=[]),
    "Haskell":     dict(c="--", assign=["{n} = {q}{v}{q}"], q=['"'], kw=[]),
    "SQL":         dict(c="--", assign=["SET @{n} = {q}{v}{q};", "IDENTIFIED BY {q}{v}{q};", "CREATE USER '{u}'@'%' IDENTIFIED BY {q}{v}{q};"], q=["'"], kw=[]),
    "Dockerfile":  dict(c="#", assign=["ENV {N}={v}", "ENV {N} {v}", "ARG {N}={v}"], q=[""], kw=[]),
    "Makefile":    dict(c="#", assign=["{N} = {v}", "{N} := {v}", "export {N}={v}"], q=[""], kw=[]),
    "CMake":       dict(c="#", assign=["set({N} {q}{v}{q})"], q=['"'], kw=[]),
    "HTML":        dict(c="<!--", assign=['<input type="hidden" name="{n}" value="{v}">', '<meta name="{n}" content="{v}">', "var {n} = {q}{v}{q};"], q=['"'], kw=[]),
    "CSS":         dict(c="/*", assign=["/* {n}: {v} */"], q=[""], kw=[]),
    "Markdown":    dict(c="", assign=["`{n}={v}`", "{n}: `{v}`", "    {N}={v}", "- **{n}**: `{v}`"], q=[""], kw=[]),
    "TeX":         dict(c="%", assign=["\\newcommand{{\\{n}}}{{{v}}}"], q=[""], kw=[]),
    "Visual Basic": dict(c="'", assign=["Dim {n} As String = {q}{v}{q}", "Const {N} As String = {q}{v}{q}"], q=['"'], kw=[]),
    "FORTRAN":     dict(c="!", assign=["character(len=*), parameter :: {n} = {q}{v}{q}"], q=["'", '"'], kw=[]),
    "Assembly":    dict(c=";", assign=["{n} db {q}{v}{q}, 0"], q=['"'], kw=[]),
}
GENERIC = dict(c="#", assign=["{n} = {q}{v}{q}", "{N}={v}"], q=['"', ""], kw=[])

# --------------------------------------------------------------------------------------
# Value generators.  Each returns (value, value_type).
# --------------------------------------------------------------------------------------
R = random.Random()
fake = Faker()
HEX = "0123456789abcdef"
B62 = string.ascii_letters + string.digits
B64 = B62 + "+/"
B64URL = B62 + "-_"

def rs(alpha, n):
    return "".join(R.choice(alpha) for _ in range(n))

def b64(n):
    return base64.b64encode(os.urandom(n)).decode()

def b64url(n):
    raw = n if isinstance(n, bytes) else os.urandom(n)
    return base64.urlsafe_b64encode(raw).decode().rstrip("=")

JWT_NAME = None   # set by the entity pool so an owned JWT carries its owner's name in the payload (no span: the payload is opaque)

def gen_jwt():
    hdr = b64url(json.dumps({"alg": R.choice(["HS256", "RS256"]), "typ": "JWT"}).encode())
    pl = b64url(json.dumps({"sub": str(R.randint(1000, 999999)), "name": JWT_NAME or fake.name(), "iat": R.randint(1500000000, 1750000000), "exp": R.randint(1750000000, 1900000000)}).encode())
    return f"{hdr}.{pl}.{b64url(32)}"

def gen_password():
    """Password sub-generators spanning CredData's charset buckets (lower 49%, digit+lower 16%, mixed 10%, ...).
    The final mix is set by charset-targeted sampling (see gen_value), not by the branch probabilities here."""
    k = R.random()
    if k < 0.30:   # pure lowercase: dictionary words, as in most real leaked passwords
        return R.choice([fake.word() + fake.word(), fake.word() + R.choice(["pass", "pwd", "admin", "secret", "test", "root"]), fake.user_name().replace(".", "").replace("_", ""), rs(string.ascii_lowercase, R.randint(5, 12))])
    if k < 0.45:   # lowercase + digits
        return R.choice([fake.word() + str(R.randint(1, 9999)), rs(string.ascii_lowercase + string.digits, R.randint(6, 12)), fake.word() + str(R.randint(10, 99)) + fake.word()])
    if k < 0.55:   # lowercase + symbol
        return R.choice([fake.word() + R.choice(["_", "-", ".", "!", "@"]) + fake.word(), fake.word() + R.choice(["!", "#", "$"])])
    if k < 0.70:   # mixed case, digits, symbols (Faker-style strong passwords)
        return fake.password(length=R.randint(8, 16), special_chars=R.random() < 0.6)
    if k < 0.85:   # capitalised word + digits (+ symbol)
        return R.choice(["", "", "admin", "root", "dev", "test", "db", "qa"]) + fake.word().capitalize() + R.choice(["", "", "!", "#", "@"]) + str(R.randint(1, 2024))
    if k < 0.92:
        return fake.word() + "_" + fake.word() + str(R.randint(10, 99))
    if k < 0.96:
        return str(R.randint(10 ** 5, 10 ** 9))                       # digits only
    return rs(string.ascii_uppercase, R.randint(6, 10)) if R.random() < 0.5 else fake.word().capitalize() + fake.word().capitalize()

def gen_pem():
    kind = R.choice(["RSA PRIVATE KEY", "RSA PRIVATE KEY", "PRIVATE KEY", "EC PRIVATE KEY", "OPENSSH PRIVATE KEY", "DSA PRIVATE KEY"])
    nbytes = {"EC PRIVATE KEY": R.randint(100, 160), "OPENSSH PRIVATE KEY": R.randint(300, 420)}.get(kind, R.randint(600, 1200))
    body = b64(nbytes)
    lines = [body[i:i + 64] for i in range(0, len(body), 64)]
    return f"-----BEGIN {kind}-----\n" + "\n".join(lines) + f"\n-----END {kind}-----"

def gen_email():
    k = R.random()
    if k < 0.5:
        return fake.free_email()
    if k < 0.75:
        return fake.user_name() + "@" + fake.domain_name()
    if k < 0.9:
        return fake.company_email()
    return fake.first_name().lower() + "." + fake.last_name().lower() + "@" + R.choice(["gmail.com", "outlook.com", "yahoo.com", "protonmail.com", "qq.com"])

# label -> list of (weight, value_type, fn)
GENERATORS = {
    "api_key": [
        (3, "aws_access_key_id", lambda: "AKIA" + rs(string.ascii_uppercase + string.digits, 16)),
        (3, "aws_secret_access_key", lambda: rs(B64, 40)),
        (2, "google_api_key", lambda: "AIza" + rs(B64URL, 35)),
        (2, "stripe_secret_key", lambda: R.choice(["sk_live_", "sk_test_", "rk_live_"]) + rs(B62, 24)),
        (1, "sendgrid_api_key", lambda: "SG." + rs(B64URL, 22) + "." + rs(B64URL, 43)),
        (1, "twilio_api_key", lambda: "SK" + rs(HEX, 32)),
        (1, "mailgun_api_key", lambda: "key-" + rs(HEX, 32)),
        (1, "openai_api_key", lambda: "sk-" + R.choice(["", "proj-"]) + rs(B62, 48)),
        (1, "anthropic_api_key", lambda: "sk-ant-api03-" + rs(B64URL, 93) + "AA"),
        (1, "azure_client_secret", lambda: rs(B62 + "~._-", 40)),
        (6, "generic_hex_key", lambda: rs(HEX, R.choice([32, 32, 40, 48, 64, 64]))),
        (2, "generic_hex_key_upper", lambda: rs(HEX.upper(), R.choice([32, 40, 64]))),
        (4, "generic_base64_secret", lambda: b64(R.choice([24, 32, 32, 48, 64]))),
        (2, "generic_alnum_key", lambda: rs(B62, R.choice([20, 24, 32, 40]))),
        (1, "generic_lower_key", lambda: rs(string.ascii_lowercase, R.choice([16, 20, 24, 32]))),
        (1, "generic_upper_key", lambda: rs(string.ascii_uppercase + string.digits, R.choice([16, 20, 25, 32]))),
        (1, "generic_digit_key", lambda: rs(string.digits, R.choice([12, 16, 20, 32]))),
        (1, "generic_hex_dashed_key", lambda: "-".join(rs(HEX, 8) for _ in range(R.choice([3, 4, 5])))),
    ],
    "token": [
        (3, "github_pat", lambda: R.choice(["ghp_", "gho_", "ghs_"]) + rs(B62, 36)),
        (1, "github_fine_grained_pat", lambda: "github_pat_" + rs(B62, 22) + "_" + rs(B62, 59)),
        (2, "slack_token", lambda: R.choice(["xoxb-", "xoxp-", "xoxa-2-"]) + str(R.randint(10 ** 10, 10 ** 12)) + "-" + str(R.randint(10 ** 10, 10 ** 12)) + "-" + rs(B62, 24)),
        (1, "slack_webhook", lambda: "https://hooks.slack.com/services/T" + rs(string.ascii_uppercase + string.digits, 8) + "/B" + rs(string.ascii_uppercase + string.digits, 8) + "/" + rs(B62, 24)),
        (4, "jwt", gen_jwt),
        (1, "gitlab_pat", lambda: "glpat-" + rs(B62 + "_-", 20)),
        (1, "npm_token", lambda: "npm_" + rs(B62, 36)),
        (1, "discord_bot_token", lambda: rs(B64URL, 24) + "." + rs(B64URL, 6) + "." + rs(B64URL, 27)),
        (1, "digitalocean_pat", lambda: "dop_v1_" + rs(HEX, 64)),
        (1, "hf_token", lambda: "hf_" + rs(B62, 34)),
        (3, "bearer_token_opaque", lambda: rs(B64URL, R.choice([32, 40, 43, 64]))),
        (2, "basic_auth_b64", lambda: base64.b64encode(f"{fake.user_name()}:{gen_password()}".encode()).decode()),
        (3, "generic_hex_token", lambda: rs(HEX, R.choice([32, 40, 48, 64]))),
        (2, "generic_alnum_token", lambda: rs(B62, R.choice([24, 32, 40, 48]))),
        (2, "generic_dashed_token", lambda: "-".join(rs(string.ascii_lowercase + string.digits, R.choice([4, 6, 8])) for _ in range(R.choice([3, 4, 5, 6])))),
        (1, "generic_upper_token", lambda: rs(string.ascii_uppercase + string.digits, R.choice([20, 24, 32]))),
    ],
    "password": [(1, "password", gen_password)],
    "private_key": [(1, "pem_private_key", gen_pem)],
    "email": [(1, "email", gen_email)],
}

def pick_weighted(items):
    tot = sum(w for w, *_ in items)
    r = R.uniform(0, tot)
    for it in items:
        r -= it[0]
        if r <= 0:
            return it
    return items[-1]

def charset(v):
    s = set()
    if re.search(r"[a-z]", v): s.add("lower")
    if re.search(r"[A-Z]", v): s.add("upper")
    if re.search(r"[0-9]", v): s.add("digit")
    if re.search(r"[^A-Za-z0-9]", v): s.add("symbol")
    return "+".join(sorted(s))

def _profile_generators(n=300):
    """Empirical P(charset | generator), used to steer sampling toward CredData's charset mix."""
    prof = {}
    for label, gens in GENERATORS.items():
        for w, vt, fn in gens:
            c = {}
            for _ in range(n):
                cs = charset(fn()); c[cs] = c.get(cs, 0) + 1
            prof[vt] = {k: v / n for k, v in c.items()}
    return prof

GEN_PROFILE = None
CHARSET_TARGET = {}   # label -> {charset: weight}; filled from priors.json by Priors()

def gen_value(label):
    """Pick a generator and value.  When a charset target exists for the label (api_key, password, token),
    first draw a target charset from CredData's distribution, then draw a generator proportionally to
    base_weight * P(charset | generator) and rejection-sample (<=12 tries) until the value matches."""
    global GEN_PROFILE
    gens = GENERATORS[label]
    tgt = CHARSET_TARGET.get(label)
    if not tgt:
        w, vt, fn = pick_weighted(gens)
        return fn(), vt
    if GEN_PROFILE is None:
        GEN_PROFILE = _profile_generators()
    cs = R.choices(list(tgt), list(tgt.values()))[0]
    cands = [(w * GEN_PROFILE[vt].get(cs, 0), vt, fn) for w, vt, fn in gens if GEN_PROFILE[vt].get(cs, 0) > 0]
    if not cands:
        w, vt, fn = pick_weighted(gens)
        return fn(), vt
    w, vt, fn = pick_weighted(cands)
    v = fn()
    for _ in range(12):
        if charset(v) == cs:
            break
        v = fn()
    return v, vt

GEN_BY_VT = {vt: fn for gens in GENERATORS.values() for _, vt, fn in gens}
FIXED_LEN_VT = {"aws_access_key_id", "aws_secret_access_key", "google_api_key", "stripe_secret_key", "sendgrid_api_key", "twilio_api_key",
                "mailgun_api_key", "anthropic_api_key", "azure_client_secret", "github_pat", "github_fine_grained_pat", "gitlab_pat",
                "npm_token", "digitalocean_pat", "hf_token", "discord_bot_token"}
BAD_VALUE_CHARS = set("'\"`")   # the renderer rewrites quotes inside values; entity values must survive rendering unchanged

# --------------------------------------------------------------------------------------
# Persons and entity pool (v3: cross-document coreference)
# --------------------------------------------------------------------------------------
PERSON_LOCALES = ["en_US"] * 7 + ["de_DE", "es_ES", "fr_FR", "it_IT", "pt_BR", "nl_NL", "pl_PL", "sv_SE", "en_GB", "en_IN"]
_FAKERS = {}

def faker_for(locale):
    if locale not in _FAKERS:
        _FAKERS[locale] = Faker(locale)
    return _FAKERS[locale]

def ascii_name(s):
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
    s = re.sub(r"[^A-Za-z\- ]", "", s).strip(" -")
    return s if re.fullmatch(r"[A-Za-z][A-Za-z\-]*", s) else None

USERNAME_TEMPLATES = {
    "f_last": lambda f, l: (f[0] + l).lower(),
    "first.last": lambda f, l: f"{f}.{l}".lower(),
    "f_last_dd": lambda f, l: (f[0] + l).lower() + "{dd}",
    "first_l": lambda f, l: (f + l[0]).lower(),
    "last_f": lambda f, l: (l + f[0]).lower(),
    "first_last": lambda f, l: f"{f}_{l}".lower(),
}
FREE_DOMAINS = ["gmail.com", "outlook.com", "yahoo.com", "protonmail.com", "hotmail.com", "icloud.com", "gmx.de", "qq.com"]
PERSON_FORMS = ["full_name", "first_name", "last_name", "username", "handle", "email"]
PERSON_FORM_LABEL = {"full_name": "person_name", "first_name": "person_name", "last_name": "person_name", "username": "username", "handle": "username", "email": "email"}
PERSON_FORM_W = {"full_name": 40, "username": 25, "email": 20, "first_name": 10, "last_name": 3, "handle": 2}
PERSON_NAMES = {   # variable names per surface form (assignment / json / yaml contexts)
    "full_name": {"author": 30, "maintainer": 10, "owner": 10, "name": 10, "created_by": 8, "contact": 5, "reviewer": 5, "full_name": 5, "developer": 4, "display_name": 4},
    "first_name": {"first_name": 20, "name": 10, "owner": 5, "assignee": 5, "contact": 3},
    "last_name": {"last_name": 20, "surname": 5, "family_name": 5},
    "username": {"user": 20, "username": 20, "owner": 10, "maintainer": 10, "created_by": 8, "login": 8, "author": 5, "assignee": 5, "user_name": 5, "db_user": 5, "ssh_user": 3},
    "handle": {"handle": 10, "twitter": 10, "github": 10, "owner": 5, "author": 5, "slack": 3},
    "email": {"email": 30, "author_email": 10, "contact": 10, "maintainer_email": 8, "owner_email": 5, "user_email": 5, "from_email": 5, "reply_to": 3},
}
PERSON_COMMENT_TMPL = {
    "full_name": ["{c} Author: {v}", "{c} @author {v}", "{c} Copyright (c) {y} {v}", "{c} Maintainer: {v}", "{c} Written by {v}", "{c} Reviewed by {v}", "{c} Contact: {v}", "{c} created by {v} on {d}"],
    "first_name": ["{c} TODO({v}): clean this up", "{c} ask {v} before changing this", "{c} thanks {v}", "{c} FIXME {v}: handle the error case", "{c} {v}: this is a workaround"],
    "last_name": ["{c} see {v} et al.", "{c} per {v}'s review", "{c} Mr. {v} owns this module"],
    "username": ["{c} TODO({v}): clean this up", "{c} owner: {v}", "{c} reviewed-by: {v}", "{c} login as {v}", "{c} maintainer {v}", "{c} assigned to {v}", "{c} run as user {v}"],
    "handle": ["{c} ping {v} if this breaks", "{c} cc {v}", "{c} owner {v}", "{c} reviewer: {v}"],
    "email": ["{c} Contact: {v}", "{c} Author email: {v}", "{c} report bugs to {v}", "{c} maintainer: {v}", "{c} {v}"],
}

def make_person(repl_of=None):
    """Synthetic person identity: dict of surface forms + the templates that derive them (so a replacement persona
    can be derived with the same templates). repl_of: existing person whose templates/locale/domain are reused."""
    for _ in range(50):
        loc = repl_of["locale"] if repl_of else R.choice(PERSON_LOCALES)
        fk = faker_for(loc)
        first, last = ascii_name(fk.first_name()), ascii_name(fk.last_name())
        if first and last and first.lower() != last.lower() and 2 <= len(first) <= 16 and 2 <= len(last) <= 20:
            break
    else:
        first, last, loc = "Alex", "Morgan", "en_US"
    t = repl_of["templates"] if repl_of else {
        "username": R.choice(list(USERNAME_TEMPLATES)), "dd": f"{R.randint(0, 99):02d}",
        "email": R.choice(["username@domain", "username@domain", "first.last@free", "first.last@domain"]),
        "domain": R.choice([fake.domain_name(), fake.domain_name(), fake.free_email_domain()]), "free": R.choice(FREE_DOMAINS)}
    uname = USERNAME_TEMPLATES[t["username"]](first, last).replace("{dd}", t["dd"]).replace("-", "")
    fl = f"{first}.{last}".lower().replace("-", "")
    email = {"username@domain": f"{uname}@{t['domain']}", "first.last@free": f"{fl}@{t['free']}", "first.last@domain": f"{fl}@{t['domain']}"}[t["email"]]
    forms = {"full_name": f"{first} {last}", "first_name": first, "last_name": last, "username": uname, "handle": "@" + uname, "email": email}
    return {"forms": forms, "templates": t, "locale": loc}

def same_shape(value):
    """Random string with the same length and per-position character class. Hex-only values stay hex (lower or upper);
    otherwise lower/upper/digit positions keep their class and symbols are copied."""
    low = R.choice
    if re.fullmatch(r"[0-9a-f]+", value) and re.search(r"[a-f]", value):
        return "".join(low("abcdef") if ch.isalpha() else low(string.digits) for ch in value)
    if re.fullmatch(r"[0-9A-F]+", value) and re.search(r"[A-F]", value):
        return "".join(low("ABCDEF") if ch.isalpha() else low(string.digits) for ch in value)
    return "".join(low(string.ascii_lowercase) if ch.islower() else low(string.ascii_uppercase) if ch.isupper() else low(string.digits) if ch.isdigit() else ch for ch in value)

VT_PREFIX = {   # vendor formats: the prefix is part of the format and must survive replacement
    "aws_access_key_id": ["AKIA"], "google_api_key": ["AIza"], "stripe_secret_key": ["sk_live_", "sk_test_", "rk_live_"], "sendgrid_api_key": ["SG."],
    "twilio_api_key": ["SK"], "mailgun_api_key": ["key-"], "openai_api_key": ["sk-proj-", "sk-"], "anthropic_api_key": ["sk-ant-api03-"],
    "github_pat": ["ghp_", "gho_", "ghs_"], "github_fine_grained_pat": ["github_pat_"], "slack_token": ["xoxb-", "xoxp-", "xoxa-2-"],
    "slack_webhook": ["https://hooks.slack.com/services/T"], "gitlab_pat": ["glpat-"], "npm_token": ["npm_"], "digitalocean_pat": ["dop_v1_"], "hf_token": ["hf_"],
}
VT_SUFFIX = {"anthropic_api_key": "AA"}

def gen_replacement(vt, value, label):
    """A fresh value of the same value_type and format, different from value: same length and per-position character
    class (vendor prefixes/suffixes kept, hex stays hex), PEMs keep header kind and line count, JWTs are regenerated
    (three base64url segments), passwords and emails are redrawn from their generator with the same charset class."""
    if vt == "pem_private_key":
        parts = value.split("\n"); body = "".join(parts[1:-1]); pad = len(body) - len(body.rstrip("="))
        body = rs(B64, len(body) - pad) + "=" * pad
        return parts[0] + "\n" + "\n".join(body[i:i + 64] for i in range(0, len(body), 64)) + "\n" + parts[-1]
    if vt == "jwt":
        return gen_jwt()
    if vt in ("password", "email"):
        fn = GEN_BY_VT[vt]; cs = charset(value); best = None
        for _ in range(8):
            v = fn()
            if v == value or BAD_VALUE_CHARS & set(v): continue
            if charset(v) == cs and abs(len(v) - len(value)) <= 3: return v
            if best is None and charset(v) == cs: best = v
        return best or same_shape(value)
    pre = next((p for p in VT_PREFIX.get(vt, []) if value.startswith(p)), "")
    suf = VT_SUFFIX.get(vt, "") if value.endswith(VT_SUFFIX.get(vt, "\0")) else ""
    core = value[len(pre):len(value) - len(suf)]
    for _ in range(3):
        v = pre + same_shape(core) + suf
        if v != value: return v
    return v

class EntityPool:
    """Per-cluster registry of entities (secrets, emails, persons) with canonical and replacement surface forms."""
    def __init__(self, cluster_id, n_persons):
        self.cid = cluster_id; self.entities = []; self.by_label = {}; self.persons = []; self.secrets = []
        self.used = set()                       # every original and replacement string in the cluster (uniqueness)
        for _ in range(n_persons):
            self.new_person()
        self.first_name_unique = {}
        for p in self.persons:
            f = p["forms"]["first_name"].lower()
            self.first_name_unique[f] = self.first_name_unique.get(f, 0) + 1

    def _add(self, e):
        e["entity_id"] = f"{self.cid}/e{len(self.entities):03d}"; e["n_mentions"] = 0; e["docs"] = set()
        self.entities.append(e); self.by_label.setdefault(e["entity_type"], []).append(e)
        if e["entity_type"] != "person": self.secrets.append(e)
        return e

    def new_person(self):
        for _ in range(20):
            p = make_person()
            if not any(v in self.used for v in p["forms"].values()):
                break
        own = {v.lower() for v in p["forms"].values()}
        for _ in range(20):
            rp = make_person(repl_of=p)
            if not any(v.lower() in own or v in self.used for v in rp["forms"].values()):
                break
        self.used.update(p["forms"].values()); self.used.update(rp["forms"].values())
        e = self._add({"entity_type": "person", "value_type": "person", "canonical": p["forms"]["full_name"], "forms": p["forms"],
                       "replacement_canonical": rp["forms"]["full_name"], "replacement_forms": rp["forms"], "owner_entity_id": None,
                       "_templates": p["templates"], "_password": None})
        self.persons.append(e)
        return e

    def person_password(self, person):
        """A password entity owned by the person (used for url credentials / basic auth); created once per person."""
        if person["_password"] is None:
            person["_password"] = self.new_secret("password", owner=person)
        return person["_password"]

    def new_secret(self, label, owner=None):
        global JWT_NAME
        JWT_NAME = owner["forms"]["full_name"] if owner else None
        for _ in range(20):
            if label == "token" and owner and R.random() < 0.15:
                pw = self.person_password(owner)
                value, vt = base64.b64encode(f"{owner['forms']['username']}:{pw['canonical']}".encode()).decode(), "basic_auth_b64"
                repl = base64.b64encode(f"{owner['replacement_forms']['username']}:{pw['replacement_canonical']}".encode()).decode()
            else:
                value, vt = gen_value(label)
                repl = gen_replacement(vt, value, label)
            if value not in self.used and repl not in self.used and value != repl and not (BAD_VALUE_CHARS & set(value)):
                break
        JWT_NAME = None
        self.used.add(value); self.used.add(repl)
        return self._add({"entity_type": label, "value_type": vt, "canonical": value, "forms": {"literal": value},
                          "replacement_canonical": repl, "replacement_forms": {"literal": repl},
                          "owner_entity_id": owner["entity_id"] if owner else None})

    def pick(self, label):
        c = self.by_label.get(label)
        return R.choice(c) if c else None

    def person_form(self, person):
        w = dict(PERSON_FORM_W)
        if self.first_name_unique.get(person["forms"]["first_name"].lower(), 0) > 1:
            w.pop("first_name")
        return R.choices(list(w), list(w.values()))[0]

    def note(self, e, doc_index):
        e["n_mentions"] += 1; e["docs"].add(doc_index)

    def table(self):
        """Entity rows for the cluster. Persons without any mention are dropped and owner links to them cleared."""
        alive = {e["entity_id"] for e in self.entities if e["n_mentions"] > 0}
        out = []
        for e in self.entities:
            if e["entity_id"] not in alive:
                continue
            out.append({"entity_id": e["entity_id"], "entity_type": e["entity_type"], "value_type": e["value_type"], "canonical": e["canonical"],
                        "forms": e["forms"], "replacement_canonical": e["replacement_canonical"], "replacement_forms": e["replacement_forms"],
                        "owner_entity_id": e["owner_entity_id"] if e["owner_entity_id"] in alive else None,
                        "n_mentions": e["n_mentions"], "n_docs": len(e["docs"])})
        return out

# Hard negatives: (value_type, fn, label_of_similar_secret)
HARD_NEGATIVES = [
    ("placeholder_name", lambda: R.choice(["John Doe", "Jane Doe", "Jane Smith", "Your Name", "Anonymous", "unknown", "nobody", "admin", "root", "guest", "test user", "Firstname Lastname", "<your name>", "author name", "user", "someone"])),
    ("placeholder", lambda: R.choice(["CHANGEME", "changeme", "<YOUR_API_KEY>", "YOUR_API_KEY_HERE", "xxxxxxxxxxxxxxxxxxxx", "********", "REPLACE_ME", "TODO", "<password>", "${PASSWORD}", "your-secret-here", "EXAMPLE_KEY", "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "sk_test_XXXXXXXXXXXXXXXXXXXXXXXX", "ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "dummy", "secret", "password", "123456", "test"])),
    ("example_email", lambda: fake.user_name() + "@" + R.choice(["example.com", "example.org", "test.com", "localhost", "domain.com", "email.com", "company.com"])),
    ("uuid", lambda: str(uuid.uuid4()) if R.random() < 0.8 else str(uuid.uuid4()).upper()),
    ("sha256_hash", lambda: hashlib.sha256(os.urandom(8)).hexdigest()),
    ("sha1_git_sha", lambda: hashlib.sha1(os.urandom(8)).hexdigest()),
    ("md5_hash", lambda: hashlib.md5(os.urandom(8)).hexdigest()),
    ("env_var_reference", lambda: R.choice(["os.environ['{N}']", "os.getenv('{N}')", "process.env.{N}", "${{{N}}}", "$({N})", "ENV['{N}']", "System.getenv(\"{N}\")", "{{{{ secrets.{N} }}}}", "${{{{ secrets.{N} }}}}", "Environment.GetEnvironmentVariable(\"{N}\")"]).format(N=R.choice(["API_KEY", "SECRET_KEY", "DB_PASSWORD", "GITHUB_TOKEN", "AWS_SECRET_ACCESS_KEY", "TOKEN", "PASSWORD"]))),
    ("public_key_pem", lambda: "-----BEGIN PUBLIC KEY-----\n" + "\n".join([b64(220)[i:i + 64] for i in range(0, 294, 64)]) + "\n-----END PUBLIC KEY-----"),
    ("ssh_public_key", lambda: "ssh-rsa " + b64(R.randint(150, 279)) + " " + fake.user_name() + "@" + fake.hostname()),
    ("version_or_id", lambda: R.choice([fake.ipv4(), "v" + str(R.randint(0, 9)) + "." + str(R.randint(0, 20)) + "." + str(R.randint(0, 50)), "com.example." + fake.word(), str(R.randint(10 ** 9, 10 ** 12)), "/usr/local/share/" + fake.word()])),
    ("base64_non_secret", lambda: base64.b64encode(fake.sentence().encode()).decode()),
]

# --------------------------------------------------------------------------------------
# Placement logic (driven by priors.json)
# --------------------------------------------------------------------------------------
class Priors:
    def __init__(self, path):
        p = json.load(open(path))
        ld = p["label_distribution"]
        # keep the POC label set; CredData's UUID class becomes a hard negative, 'other' dropped
        self.labels = [l for l in ("api_key", "password", "token", "private_key") if l in ld]
        self.label_w = [ld[l] for l in self.labels]
        # emails are not a CredData class; give them a fixed share
        self.labels.append("email"); self.label_w.append(int(0.12 * sum(self.label_w)))
        self.ctx_by_label = {l: p["context_by_label"].get(l, {"assignment": 1}) for l in self.labels}
        self.ctx_by_label["email"] = {"assignment": 40, "comment": 35, "json_key": 10, "yaml_key": 10}
        self.names = {l: p["var_names_by_label_top40"].get(l, {"secret": 1}) for l in self.labels}
        self.names["email"] = {"email": 30, "admin_email": 10, "user_email": 10, "from_email": 8, "contact": 5, "author_email": 5, "smtp_user": 5, "mail": 4, "username": 4}
        self.names["token"] = dict(self.names["token"]); self.names["token"].update({"token": 50, "access_token": 30, "auth_token": 20, "api_token": 15, "github_token": 10, "slack_token": 8, "bearer": 5})
        self.names["api_key"] = dict(self.names["api_key"]); self.names["api_key"].update({"api_key": 60, "apikey": 30, "secret_key": 30, "aws_secret_access_key": 20, "aws_access_key_id": 20, "client_secret": 20, "private_key": 5, "stripe_key": 5})
        self.names["private_key"] = {"private_key": 30, "key": 20, "rsa_key": 10, "ssh_key": 10, "pem": 5, "signing_key": 5, "server_key": 5}
        global GEN_PROFILE
        if GEN_PROFILE is None:
            GEN_PROFILE = _profile_generators()
        for l in ("api_key", "password", "token"):
            d = p.get("charset_by_label", {}).get(l, {})
            reachable = set().union(*(GEN_PROFILE[vt].keys() for _, vt, _ in GENERATORS[l]))
            CHARSET_TARGET[l] = {cs: n for cs, n in d.items() if cs in reachable and n > 0}
        h = p.get("secrets_per_file_hist", {"1": 60, "2": 20, "3": 10, "4": 5})
        # CredData's last bucket is "10+", dominated by a few credential-dump files; damp it
        self.nsec = [min(int(k), 5) for k in h]; self.nsec_w = [h[k] / (4 if int(k) >= 10 else 1) for k in h]
        self.quote_style = p.get("quote_style", {})

    def sample_label(self):
        return R.choices(self.labels, self.label_w)[0]

    def sample_ctx(self, label, allowed):
        d = {k: v for k, v in self.ctx_by_label[label].items() if k in allowed}
        if not d:
            return "assignment"
        return R.choices(list(d), list(d.values()))[0]

    def sample_name(self, label):
        d = self.names[label]
        return R.choices(list(d), list(d.values()))[0]

    def sample_nsec(self):
        return R.choices(self.nsec, self.nsec_w)[0]

def name_variants(n):
    """Return (snake, UPPER, camel) forms of a variable name."""
    n = re.sub(r"[^a-z0-9_]", "_", n.lower()).strip("_") or "secret"
    parts = n.split("_")
    camel = parts[0] + "".join(x.capitalize() for x in parts[1:])
    return n, n.upper(), camel

PEM_ESCAPE = ("\n", "\\n\" +\n    \"")   # how a PEM is written inside Java/C/C#/C++ string concatenation

def render(ctx, lang, label, name, value, is_negative=False, user=None, comment_tmpls=None):
    """Render one injected line (may be multi-line for PEM).
    Returns (line_text, rel_start, rel_end, form, user_pos): form is 'literal' or 'escaped_literal' (PEM inside a
    string concatenation); user_pos is (start, end) of the user string when `user` was given and the construct
    contains it (url credential, 'login as' comment, SQL CREATE USER), else None."""
    L = LANG.get(lang, GENERIC)
    snake, upper, camel = name_variants(name)
    n = R.choice([snake, snake, camel]) if lang in ("JavaScript", "TypeScript", "Java", "C#", "GO", "Scala", "Kotlin") else snake
    q = R.choice(L["q"]) if L["q"] else '"'
    if value and ("'" in value or '"' in value or " " in value or "<" in value) and q == "":
        q = '"'
    if q and q in value:
        q = "'" if q == '"' else '"'
        if q in value:
            value = value.replace(q, "")
    user_given = user is not None
    _u = [user]
    def U():   # lazy: Faker user_name is comparatively slow and most constructs never use it
        if _u[0] is None: _u[0] = fake.user_name()
        return _u[0]
    form = "literal"
    if label == "private_key" or "\n" in value:
        ctx = "pem_block"
    if ctx == "pem_block":
        if lang in ("Python", "JavaScript", "TypeScript", "Ruby", "GO", "PHP", "Shell"):
            opener = {"Python": f'{n} = """', "JavaScript": f"const {n} = `", "TypeScript": f"const {n} = `", "Ruby": f"{n} = <<~KEY\n", "GO": f"{n} := `", "PHP": f"${n} = <<<KEY\n", "Shell": f"cat > ~/.ssh/id_rsa <<'EOF'\n"}[lang]
            closer = {"Python": '"""', "JavaScript": "`;", "TypeScript": "`;", "Ruby": "\nKEY", "GO": "`", "PHP": "\nKEY;", "Shell": "\nEOF"}[lang]
            line = opener + value + closer
        elif lang in ("Java", "C#", "C", "C++"):
            esc = value.replace(*PEM_ESCAPE)
            line = f'String {n} = "{esc}";' if lang == "Java" else f'const char *{n} = "{esc}";' if lang in ("C", "C++") else f'string {n} = "{esc}";'
            value = esc; form = "escaped_literal"
        else:
            line = value
        s = line.index(value)
        return line, s, s + len(value), form, None
    if ctx == "comment":
        c = L["c"] or "#"
        tmpl = R.choice(comment_tmpls or ["{c} {n}: {v}", "{c} {n} = {v}", "{c} TODO: remove hardcoded {n} {v}", "{c} old {n}: {v}", "{c} {n}={v}", "{c} login as {u} / {v}"])
        line = tmpl.format(c=c, n=n, v=value, u=U(), y=R.randint(2008, 2025), d=fake.date() if "{d}" in tmpl else "")
        if c == "<!--": line += " -->"
        if c == "/*": line += " */"
    elif ctx == "url_credential":
        scheme = R.choice(["postgres", "postgresql", "mysql", "mongodb", "mongodb+srv", "redis", "amqp", "https", "http", "ftp", "sftp"])
        host = R.choice([fake.hostname(), "localhost", fake.ipv4(), fake.domain_name()])
        url = f"{scheme}://{U()}:{value}@{host}" + R.choice([":5432/app", "/", ":6379/0", "/db", "/api/v1", ":3306/prod", ""])
        a = R.choice(L["assign"]) if ctx != "pem_block" else "{n} = {q}{v}{q}"
        if lang == "SQL": a = "{n} = {q}{v}{q}"
        line = a.format(n=R.choice(["database_url", "db_url", "conn_str", "connection_string", "url", "uri", "mongo_uri", "redis_url", "broker_url", "dsn"]) if "{n}" in a else "", N=R.choice(["DATABASE_URL", "DB_URI", "MONGO_URL", "REDIS_URL", "CONNECTION_STRING"]), q=q, v=url, u=U())
    elif ctx == "auth_header":
        if label == "token" and R.random() < 0.6:
            hv = f"Bearer {value}"
        else:
            hv = f"Basic {value}" if re.fullmatch(r"[A-Za-z0-9+/=]+", value) else f"Bearer {value}"
        tmpls = AUTH_TMPL.get(lang, ['{q}Authorization{q}: {q}{hv}{q},', "Authorization: {hv}"])
        tmpl = R.choice(tmpls)
        line = tmpl.format(q=q or '"', hv=hv)
    elif ctx in ("json_key", "yaml_key", "env_assignment", "ini_or_props", "function_arg") and L["kw"] and ctx != "env_assignment":
        line = R.choice(L["kw"]).format(n=n, N=upper, q=(q if q in ("'", '"') else '"'), v=value)
    elif ctx == "env_assignment":
        line = R.choice(["{N}={v}", "{N}={q}{v}{q}", "export {N}={q}{v}{q}", "ENV {N}={v}"]).format(N=upper, q=q, v=value) if lang in ("Shell", "Dockerfile", "Makefile", "Markdown") else R.choice(L["assign"]).format(n=n, N=upper, q=q, v=value, u=U())
    else:
        line = R.choice(L["assign"]).format(n=n, N=upper, q=q, v=value, u=U())
    s = line.rindex(value)
    user_pos = None
    if user_given:
        for m in re.finditer(re.escape(_u[0]), line):
            if m.end() <= s and (m.end() == len(line) or not line[m.end()].isalnum()) and (m.start() == 0 or not line[m.start() - 1].isalnum()):
                user_pos = (m.start(), m.end())
    return line, s, s + len(value), "literal", user_pos

AUTH_TMPL = {
    "Python": ['headers[{q}Authorization{q}] = {q}{hv}{q}', 'headers = {{{q}Authorization{q}: {q}{hv}{q}}}', '{q}Authorization{q}: {q}{hv}{q},'],
    "JavaScript": ['{q}Authorization{q}: {q}{hv}{q},', 'headers.Authorization = {q}{hv}{q};', "xhr.setRequestHeader({q}Authorization{q}, {q}{hv}{q});"],
    "TypeScript": ['{q}Authorization{q}: {q}{hv}{q},', 'headers.set({q}Authorization{q}, {q}{hv}{q});'],
    "GO": ['req.Header.Set({q}Authorization{q}, {q}{hv}{q})', 'req.Header.Add({q}Authorization{q}, {q}{hv}{q})'],
    "Java": ['conn.setRequestProperty({q}Authorization{q}, {q}{hv}{q});', '.header({q}Authorization{q}, {q}{hv}{q})', 'headers.set({q}Authorization{q}, {q}{hv}{q});'],
    "C#": ['client.DefaultRequestHeaders.Add({q}Authorization{q}, {q}{hv}{q});', 'request.Headers[{q}Authorization{q}] = {q}{hv}{q};'],
    "PHP": ["'Authorization: {hv}',", "$headers[{q}Authorization{q}] = {q}{hv}{q};"],
    "Ruby": ["request[{q}Authorization{q}] = {q}{hv}{q}", "headers: {{ {q}Authorization{q} => {q}{hv}{q} }}"],
    "Shell": ["-H {q}Authorization: {hv}{q} \\", "curl -H {q}Authorization: {hv}{q} https://api.example.com/v1/me"],
    "Markdown": ["    Authorization: {hv}", "`Authorization: {hv}`"],
    "Rust": ['.header({q}Authorization{q}, {q}{hv}{q})'],
    "C": ['headers = curl_slist_append(headers, {q}Authorization: {hv}{q});'],
    "C++": ['headers = curl_slist_append(headers, {q}Authorization: {hv}{q});'],
    "PowerShell": ['$headers = @{{ Authorization = {q}{hv}{q} }}'],
}
NEG_NAME_LABEL = {"example_email": "email", "public_key_pem": "private_key", "ssh_public_key": "private_key"}
NEG_NAMES = {
    "private_key": {"public_key": 30, "pubkey": 10, "ssh_public_key": 10, "authorized_key": 5, "verify_key": 5, "cert": 5},
    "hash": {"checksum": 20, "sha256": 10, "sha1": 10, "md5": 10, "digest": 10, "commit": 10, "etag": 5, "integrity": 5, "file_hash": 5, "revision": 5, "content_hash": 5, "ref": 3, "git_sha": 3},
    "uuid": {"id": 20, "request_id": 10, "tenant_id": 10, "client_id": 10, "device_id": 8, "correlation_id": 8, "trace_id": 5, "job_id": 5, "uuid": 10, "guid": 5, "instance_id": 5},
    "version_or_id": {"version": 20, "host": 10, "ip": 10, "app_id": 10, "path": 10, "package": 5, "bundle_id": 5, "build": 5, "server": 5},
    "base64_non_secret": {"payload": 20, "data": 10, "body": 10, "encoded": 10, "message": 10, "content": 5, "blob": 5},
    "person": {"author": 20, "owner": 10, "user": 10, "maintainer": 10, "name": 10, "username": 8, "created_by": 5, "contact": 5},
}
NEG_NAME_GROUP = {"sha256_hash": "hash", "sha1_git_sha": "hash", "md5_hash": "hash", "uuid": "uuid", "version_or_id": "version_or_id", "base64_non_secret": "base64_non_secret", "public_key_pem": "private_key", "ssh_public_key": "private_key", "placeholder_name": "person"}

CTX_ALLOWED = {"assignment", "json_key", "yaml_key", "env_assignment", "comment", "url_credential", "auth_header", "function_arg", "pem_block"}

PERSON_CTX = {"comment": 45, "assignment": 35, "json_key": 10, "yaml_key": 10}
NO_ENTITY = {"entity_id": None, "surface_form_type": None, "replacement": None}

def span_meta(ent, label, vt, ctx, form, surface_key):
    repl = ent["replacement_forms"][surface_key]
    if form == "escaped_literal":
        repl = repl.replace(*PEM_ESCAPE)
    return {"label": label, "value_type": vt, "context": ctx, "synthetic": True, "entity_id": ent["entity_id"], "surface_form_type": form if surface_key == "literal" else surface_key, "replacement": repl}

def inject(text, lang, priors, n_secrets, n_negs, pool, doc_index, cfg, n_person_mentions=0):
    """Insert n_secrets secret lines (entities drawn from / added to the cluster pool), n_person_mentions person
    mentions and n_negs hard-negative lines into text. Returns (text, spans, negs)."""
    lines = text.split("\n")
    nl = len(lines)
    inserts = []  # (line_index, rendered_line, [(rel_start, rel_end, meta), ...])
    used_here = []
    ents = {e["entity_id"]: e for e in pool.entities}
    for _ in range(n_secrets):
        label = priors.sample_label()
        if used_here and R.random() < cfg["p_repeat"]:            # second mention of an entity already in this file
            ent = R.choice(used_here); label = ent["entity_type"]
        elif pool.secrets and R.random() < cfg["p_reuse"]:   # recurrence of a cluster entity (any label), preferably one not yet in this file
            ent = R.choice([e for e in pool.secrets if e not in used_here] or pool.secrets); label = ent["entity_type"]
        else:
            owner = R.choice(pool.persons) if pool.persons and label != "email" and R.random() < cfg["p_owner"] else None
            ent = pool.new_secret(label, owner)
        ctx = priors.sample_ctx(label, CTX_ALLOWED)
        name = priors.sample_name(label)
        owner = ents.get(ent["owner_entity_id"])   # owners are persons, all created before the first document
        line, s, e, form, upos = render(ctx, lang, label, name, ent["canonical"], user=owner["forms"]["username"] if owner else None)
        if label == "private_key": ctx = "pem_block"
        parts = [(s, e, span_meta(ent, label, ent["value_type"], ctx, form, "literal"))]
        pool.note(ent, doc_index); used_here.append(ent)
        if upos:
            parts.append((upos[0], upos[1], span_meta(owner, "username", "username", ctx, "literal", "username")))
            pool.note(owner, doc_index)
        inserts.append((R.randint(0, nl), line, parts))
    for _ in range(n_person_mentions):
        person = R.choice(pool.persons)
        fk = pool.person_form(person)
        ctx = R.choices(list(PERSON_CTX), list(PERSON_CTX.values()))[0]
        name = R.choices(list(PERSON_NAMES[fk]), list(PERSON_NAMES[fk].values()))[0]
        line, s, e, form, _ = render(ctx, lang, PERSON_FORM_LABEL[fk], name, person["forms"][fk], comment_tmpls=PERSON_COMMENT_TMPL[fk])
        inserts.append((R.randint(0, nl), line, [(s, e, span_meta(person, PERSON_FORM_LABEL[fk], "email" if fk == "email" else fk, ctx, "literal", fk))]))
        pool.note(person, doc_index)
    for _ in range(n_negs):
        vt, fn = R.choice(HARD_NEGATIVES)
        value = fn()
        if vt in ("env_var_reference",):
            line = R.choice(LANG.get(lang, GENERIC)["assign"]).format(n=R.choice(["api_key", "password", "token", "secret"]), N=R.choice(["API_KEY", "PASSWORD", "TOKEN"]), q="", v=value, u="u")
            s = line.rindex(value); e = s + len(value)
        else:
            label_like = NEG_NAME_LABEL.get(vt) or R.choice(["api_key", "password", "token"])
            ctx = priors.sample_ctx(label_like, CTX_ALLOWED - {"pem_block", "auth_header", "url_credential"})
            if "\n" in value: ctx = "pem_block"
            grp = NEG_NAME_GROUP.get(vt)
            name = R.choices(list(NEG_NAMES[grp]), list(NEG_NAMES[grp].values()))[0] if grp else priors.sample_name(label_like)
            line, s, e, _, _ = render(ctx, lang, "api_key" if label_like == "private_key" else label_like, name, value, is_negative=True)
        inserts.append((R.randint(0, nl), line, [(s, e, dict({"label": "not_secret", "value_type": vt, "context": None, "synthetic": True}, **NO_ENTITY))]))
    inserts.sort(key=lambda x: x[0])
    out = []; spans = []; negs = []; pos = 0; li = 0
    for idx, line, parts in inserts:
        while li < idx:
            out.append(lines[li]); pos += len(lines[li]) + 1; li += 1
        ref = lines[idx] if idx < nl else (lines[-1] if lines else "")
        indent = re.match(r"[ \t]*", ref).group(0) if lang != "Markdown" else ""
        if "\n" in line and lang not in ("Python",):
            indent = ""
        full = indent + line
        for s, e, meta in parts:
            rec = dict(meta, start=pos + len(indent) + s, end=pos + len(indent) + e)
            (negs if meta["label"] == "not_secret" else spans).append(rec)
        out.append(full); pos += len(full) + 1
    while li < nl:
        out.append(lines[li]); pos += len(lines[li]) + 1; li += 1
    spans.sort(key=lambda r: r["start"]); negs.sort(key=lambda r: r["start"])
    return "\n".join(out), spans, negs

# --------------------------------------------------------------------------------------
# Shard processing
# --------------------------------------------------------------------------------------
def fetch_shard(i, shard_dir, keep):
    os.makedirs(shard_dir, exist_ok=True)
    p = os.path.join(shard_dir, f"train-{i:05d}-of-00880.parquet")
    if os.path.exists(p):
        return p, False
    tmp = p + ".part"
    urllib.request.urlretrieve(HF_URL.format(i=i), tmp)
    os.replace(tmp, p)
    return p, not keep

BUNDLE_SIZE = {2: 35, 3: 25, 4: 15, 5: 10, 6: 7, 7: 4, 8: 4}
N_PERSONS_MULTI = ([0, 1, 2, 3], [30, 40, 20, 10])
N_PERSONS_SINGLE = ([0, 1], [70, 30])
N_PERSON_MENTIONS = ([0, 1, 2], [65, 25, 10])

def rec_id(i, ex):
    return f"ghcc-{i:05d}-" + hashlib.sha1(f"{ex['repo_name']}/{ex['path']}".encode()).hexdigest()[:16]

def plan_clusters(pf, i, cfg, stats):
    """Pass 1 (cheap: no text is kept): decide which kept rows form which cluster.
    Returns (row_index -> cluster_key, {cluster_key: {"kind", "members": [row_index...], "key"}})."""
    rows = []   # (kept, repo, lang, rid) per row of the shard
    for rg in range(pf.metadata.num_row_groups):
        tb = pf.read_row_group(rg, columns=["repo_name", "path", "license", "language", "code"])
        lens = pc.utf8_length(tb["code"]).to_pylist()
        for repo, path, lic, lang, n in zip(tb["repo_name"].to_pylist(), tb["path"].to_pylist(), tb["license"].to_pylist(), tb["language"].to_pylist(), lens):
            if cfg["max_rows"] and len(rows) >= cfg["max_rows"]:
                rows.append(None); continue
            if lic not in PERMISSIVE:
                stats["skipped_license"] += 1; rows.append(None); continue
            if not (cfg["min_bytes"] <= n <= cfg["max_bytes"]):
                stats["skipped_size"] += 1; rows.append(None); continue
            rows.append((repo, lang, rec_id(i, {"repo_name": repo, "path": path})))
    by_repo = {}
    for idx, r in enumerate(rows):
        if r: by_repo.setdefault(r[0], []).append(idx)
    clusters = {}; plan = {}
    def add(kind, key, members):
        ck = f"{kind}:{key}"
        clusters[ck] = {"kind": kind, "key": key, "members": members}
        for m in members: plan[m] = ck
    loose = []
    for repo, idxs in by_repo.items():
        if len(idxs) >= 2 and not cfg["no_repo_clusters"]:
            k = -(-len(idxs) // cfg["cluster_cap"])            # split big repos into near-equal chunks <= cap
            per = -(-len(idxs) // k)
            for c in range(k):
                add("repo", f"{repo}#{c}", idxs[c * per:(c + 1) * per])
        else:
            loose.extend(idxs)
    loose.sort()
    queues = {}   # bundle queues: per language (mono-language bundles) and one mixed; bounded buffering in pass 2
    def flush(qk):
        mem = queues.pop(qk)["m"]
        if len(mem) >= 2:
            add("bundle", "+".join(sorted(rows[m][2] for m in mem)), mem)
        else:
            for m in mem: add("singleton", rows[m][2], [m])
    for idx in loose:
        if R.random() < cfg["singleton_frac"]:
            add("singleton", rows[idx][2], [idx]); continue
        qk = rows[idx][1] if R.random() < 0.5 else "*"
        q = queues.setdefault(qk, {"m": [], "n": R.choices(list(BUNDLE_SIZE), list(BUNDLE_SIZE.values()))[0]})
        q["m"].append(idx)
        if len(q["m"]) >= q["n"]:
            flush(qk)
    for qk in list(queues):
        flush(qk)
    return plan, clusters

def emit_cluster(c, i, cfg, priors, fh, stats):
    kind = c["kind"]
    cid = "c-%05d-%s" % (i, hashlib.blake2b(f"{kind}:{c['key']}".encode(), digest_size=8).hexdigest())
    seed = int.from_bytes(hashlib.blake2b(f"{cfg['seed']}:{cid}".encode(), digest_size=8).digest(), "big")
    R.seed(seed); Faker.seed(seed)
    members = [c["buf"][m] for m in c["members"]]
    n = len(members)
    np_ = 0 if cfg["no_persons"] else R.choices(*(N_PERSONS_MULTI if n > 1 else N_PERSONS_SINGLE))[0]
    pool = EntityPool(cid, np_)
    recs = []
    for doc_index, ex in enumerate(members):
        text, lang = ex["code"], ex["language"]
        spans, negs = [], []
        if R.random() < cfg["inject_frac"]:
            n_sec = priors.sample_nsec() if R.random() < 0.85 else 0
            n_neg = R.choice([0, 0, 1, 1, 1, 2, 2, 3])
            n_pm = R.choices(*N_PERSON_MENTIONS)[0] if pool.persons else 0
            if n_sec or n_neg or n_pm:
                text, spans, negs = inject(text, lang, priors, n_sec, n_neg, pool, doc_index, cfg, n_pm)
        for s in spans + negs:
            v = text[s["start"]:s["end"]]
            assert len(v) == s["end"] - s["start"] and v.strip() == v and len(v) > 0, (s, v)
            s["value"] = v
        recs.append({"id": rec_id(i, ex), "source": "codeparrot/github-code-clean", "repo": ex["repo_name"], "license": ex["license"],
                     "language": lang, "path": ex["path"], "text": text, "spans": spans, "hard_negatives": negs,
                     "cluster_id": cid, "cluster_kind": kind, "cluster_size": n, "doc_index": doc_index, "entities": None})
    table = pool.table()
    recs[0]["entities"] = table
    for e in table:
        stats["entities"] += 1
        stats["entity_type"][e["entity_type"]] = stats["entity_type"].get(e["entity_type"], 0) + 1
        stats["docs_per_entity"][str(min(e["n_docs"], 6))] = stats["docs_per_entity"].get(str(min(e["n_docs"], 6)), 0) + 1
        stats["mentions_per_entity"][str(min(e["n_mentions"], 8))] = stats["mentions_per_entity"].get(str(min(e["n_mentions"], 8)), 0) + 1
        if e["owner_entity_id"]: stats["owned_entities"] += 1
    if n > 1:
        stats["recurring_entities"] += sum(1 for e in table if e["n_docs"] > 1)
        stats["multi_entities"] += len(table)
    stats["clusters"] += 1
    stats["cluster_kind"][kind] = stats["cluster_kind"].get(kind, 0) + 1
    stats["cluster_size"][str(n)] = stats["cluster_size"].get(str(n), 0) + 1
    for rec in recs:
        spans, negs, lang = rec["spans"], rec["hard_negatives"], rec["language"]
        line = json.dumps(rec, ensure_ascii=False) + "\n"
        fh.write(line)
        stats["files"] += 1; stats["bytes"] += len(line.encode("utf-8", "replace"))
        stats["injected_files" if spans else "clean_files"] += 1
        stats["spans"] += len(spans); stats["negs"] += len(negs)
        stats["lang"][lang] = stats["lang"].get(lang, 0) + 1
        stats["records_by_kind"][kind] = stats["records_by_kind"].get(kind, 0) + 1
        for s in spans:
            stats["label"][s["label"]] = stats["label"].get(s["label"], 0) + 1
            stats["value_type"][s["value_type"]] = stats["value_type"].get(s["value_type"], 0) + 1
            stats["context"][s["context"]] = stats["context"].get(s["context"], 0) + 1
            stats["surface_form"][s["surface_form_type"]] = stats["surface_form"].get(s["surface_form_type"], 0) + 1
        for s in negs:
            stats["value_type"]["neg:" + s["value_type"]] = stats["value_type"].get("neg:" + s["value_type"], 0) + 1

def process_shard(args):
    i, cfg = args
    R.seed(cfg["seed"] * 100003 + i); Faker.seed(cfg["seed"] * 100003 + i)
    priors = Priors(cfg["priors"])
    path, delete_after = fetch_shard(i, cfg["shard_dir"], cfg["keep_shards"])
    out_path = os.path.join(cfg["out"], f"part-{i:05d}.jsonl")
    stats = {"shard": i, "files": 0, "injected_files": 0, "clean_files": 0, "bytes": 0, "spans": 0, "negs": 0,
             "label": {}, "value_type": {}, "lang": {}, "context": {}, "skipped_license": 0, "skipped_size": 0,
             "clusters": 0, "cluster_kind": {}, "cluster_size": {}, "records_by_kind": {}, "entities": 0, "entity_type": {},
             "docs_per_entity": {}, "mentions_per_entity": {}, "owned_entities": 0, "recurring_entities": 0, "multi_entities": 0,
             "surface_form": {}, "peak_buffered_rows": 0}
    t0 = time.time()
    pf = pq.ParquetFile(path)
    plan, clusters = plan_clusters(pf, i, cfg, stats)
    stats["seconds_plan"] = round(time.time() - t0, 1)
    buffered = 0; idx = 0
    with open(out_path + ".tmp", "w", encoding="utf-8") as fh:
        for rg in range(pf.metadata.num_row_groups):
            for ex in pf.read_row_group(rg, columns=["code", "repo_name", "path", "language", "license"]).to_pylist():
                ck = plan.get(idx); idx += 1
                if ck is None:
                    continue
                c = clusters[ck]
                c.setdefault("buf", {})[idx - 1] = ex; buffered += 1
                stats["peak_buffered_rows"] = max(stats["peak_buffered_rows"], buffered)
                if len(c["buf"]) == len(c["members"]):
                    emit_cluster(c, i, cfg, priors, fh, stats)
                    buffered -= len(c["members"]); del clusters[ck]
    assert not clusters, f"{len(clusters)} clusters never completed"
    os.replace(out_path + ".tmp", out_path)
    if delete_after:
        os.remove(path)
    stats["seconds"] = round(time.time() - t0, 1)
    with open(os.path.join(cfg["out"], f"part-{i:05d}.stats.json"), "w") as fh:
        json.dump(stats, fh)
    print(f"shard {i}: {stats['files']} files, {stats['bytes']/1e6:.0f} MB, {stats['spans']} spans in {stats['seconds']}s ({stats['bytes']/1e6/stats['seconds']:.1f} MB/s)", flush=True)
    return stats

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--out", required=True)
    ap.add_argument("--priors", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "priors.json"))
    ap.add_argument("--target-bytes", type=float, default=2e9, help="stop launching new shards once output exceeds this (approx; one shard ~= 500-600 MB output)")
    ap.add_argument("--start-shard", type=int, default=0)
    ap.add_argument("--max-shards", type=int, default=N_SHARDS)
    ap.add_argument("--shard-dir", default="./shards", help="where parquet shards are cached/downloaded")
    ap.add_argument("--keep-shards", action="store_true", help="do not delete downloaded shards after processing")
    ap.add_argument("--workers", type=int, default=max(1, os.cpu_count() - 1))
    ap.add_argument("--inject-frac", type=float, default=0.75, help="fraction of files that get any injection (rest are pure negatives)")
    ap.add_argument("--min-bytes", type=int, default=200)
    ap.add_argument("--max-bytes", type=int, default=200_000)
    ap.add_argument("--seed", type=int, default=1)
    ap.add_argument("--max-rows", type=int, default=0, help="debug: only consider the first N rows of each shard")
    g = ap.add_argument_group("clusters / coreference (v3)")
    g.add_argument("--cluster-cap", type=int, default=8, help="max files per cluster; bigger repos are split into near-equal chunks")
    g.add_argument("--singleton-frac", type=float, default=0.35, help="share of files outside multi-file repos that stay singletons (rest go into bundles)")
    g.add_argument("--p-reuse", type=float, default=0.7, help="P(a secret slot reuses an existing cluster entity not yet in the file; its label replaces the drawn one)")
    g.add_argument("--p-repeat", type=float, default=0.15, help="P(a secret slot repeats an entity already mentioned in the same file)")
    g.add_argument("--p-owner", type=float, default=0.5, help="P(a new secret is owned by a cluster person, when persons exist)")
    g.add_argument("--no-persons", action="store_true", help="v2-compatible label set: no person entities / person_name / username spans")
    g.add_argument("--no-bundles", action="store_true", help="no synthetic bundles (all loose files stay singletons)")
    g.add_argument("--no-repo-clusters", action="store_true", help="treat multi-file repos like loose files")
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    cfg = dict(priors=a.priors, out=a.out, shard_dir=a.shard_dir, keep_shards=a.keep_shards, inject_frac=a.inject_frac, min_bytes=a.min_bytes, max_bytes=a.max_bytes, seed=a.seed, max_rows=a.max_rows,
               cluster_cap=a.cluster_cap, singleton_frac=1.0 if a.no_bundles else a.singleton_frac, p_reuse=a.p_reuse, p_repeat=a.p_repeat, p_owner=a.p_owner,
               no_persons=a.no_persons, no_repo_clusters=a.no_repo_clusters)
    t0 = time.time(); total = 0; done = []
    shard_iter = iter(range(a.start_shard, min(N_SHARDS, a.start_shard + a.max_shards)))
    with Pool(a.workers) as pool:
        pending = []
        def launch():
            i = next(shard_iter, None)
            if i is not None:
                pending.append(pool.apply_async(process_shard, ((i, cfg),)))
        for _ in range(a.workers):
            launch()
        while pending:
            r = pending.pop(0)
            st = r.get(); done.append(st); total += st["bytes"]
            if total < a.target_bytes:
                launch()
    dt = time.time() - t0
    summary = {"shards": len(done), "files": sum(s["files"] for s in done), "bytes": total, "spans": sum(s["spans"] for s in done),
               "hard_negatives": sum(s["negs"] for s in done), "clusters": sum(s["clusters"] for s in done), "entities": sum(s["entities"] for s in done),
               "seconds": round(dt, 1), "MB_per_s": round(total / 1e6 / dt, 2), "workers": a.workers,
               "config": {k: cfg[k] for k in ("seed", "inject_frac", "cluster_cap", "singleton_frac", "p_reuse", "p_repeat", "p_owner", "no_persons")}}
    with open(os.path.join(a.out, "summary.json"), "w") as fh:
        json.dump(summary, fh, indent=1)
    print(json.dumps(summary, indent=1))

if __name__ == "__main__":
    main()