File size: 19,489 Bytes
ed663e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80a02b9
 
 
ed663e5
 
80a02b9
ed663e5
 
 
 
 
 
 
80a02b9
ed663e5
80a02b9
ed663e5
80a02b9
ed663e5
 
 
 
 
 
 
80a02b9
 
 
ed663e5
 
 
dce9264
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
 
 
 
 
 
 
 
8d1b820
80a02b9
 
 
ed663e5
8d1b820
 
 
 
 
 
80a02b9
8d1b820
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
---
license: other
license_name: mixed-permissive
license_details: >-
  Generated records: each record keeps the license of its base file (MIT, Apache-2.0,
  BSD-2/3-Clause, ISC, Unlicense or CC0-1.0, see the `license` column) as redistributed by
  codeparrot/github-code-clean (Apache-2.0 for the compilation). eval_creddata.jsonl and
  priors.json derive from Samsung/CredData (Apache-2.0; source files keep their own
  permissive OSS licenses). Generator code: Apache-2.0.
task_categories:
  - token-classification
language:
  - code
  - en
tags:
  - secrets-detection
  - credential-detection
  - pii
  - code
  - synthetic
  - span-labels
  - security
  - coreference
  - anonymization
pretty_name: code-pii (POC) - span-labeled secrets in source code with cross-document coreference
size_categories:
  - 1M<n<10M
version: "3.0"
configs:
  - config_name: default
    data_files:
      - split: train
        path: data/*.parquet
---

# code-pii (v3, cross-document coreference)

Span-labeled source files for fine-tuning an LLM / token classifier to detect **code-related sensitive data** (passwords, API keys, tokens, private keys, emails, and since v3 synthetic **person names / usernames**) and to **anonymize it consistently across files**: records are grouped into clusters (real multi-file repos, synthetic bundles, singletons), the same entity recurs across the files of a cluster under one `entity_id`, and every span carries a gold `replacement` value. Out of scope: addresses, phone numbers, SSNs.

Built by taking permissively-licensed real files from `codeparrot/github-code-clean` and injecting **format-correct synthetic secrets** at positions and in constructs whose distribution is learned from the human-annotated [Samsung/CredData](https://github.com/Samsung/CredData) corpus, plus labeled **hard negatives** (placeholders, hashes, UUIDs, env-var references, public keys, example.com emails, placeholder names). ~34% of files are left without any secret as pure negatives. CredData's real labeled lines ship separately as a held-out evaluation set.

Full field-by-field documentation: [`DATA_DICTIONARY.md`](DATA_DICTIONARY.md). Counts: [`stats.md`](stats.md).

## Contents

| path | description |
|---|---|
| `data/train-AAAAA-BBBBB.parquet` | generated training records; each file merges 3 base-corpus shards (~225k records, ~550 MB, zstd); clusters are contiguous and never cross files |
| `sample.jsonl` | ~500 records (whole clusters), same schema, for a quick look |
| `eval_creddata.jsonl` (stored gzipped in the project store as `eval_creddata.jsonl.gz`; upload uncompressed) | 67,896 **real** labeled lines from CredData (+-3 lines of context): 15,753 true secrets, 48,061 annotated false positives, 4,082 ambiguous. Evaluation only. |
| `priors.json` | CredData-derived placement statistics that drive the generator |
| `stats.md` | label / value_type / context / language counts, sizes, throughput |
| `DATA_DICTIONARY.md` | construction narrative, schema, taxonomy, limitations |
| `notebooks/eda.ipynb` (+ `stats_summary.json`) | executed EDA notebook: integrity check, distributions, comparison against CredData priors, conclusions |
| `generate_dataset.py`, `build_priors.py`, `validate.py`, `to_parquet.py`, `preview_subset.py`, `make_stats.py`, `requirements.txt` | everything needed to regenerate at any size |

## Schema

```text
id              string   ghcc-<shard>-<sha1(repo/path)[:16]>
source          string   "codeparrot/github-code-clean"
repo, path      string   origin of the base file
license         string   mit | apache-2.0 | bsd-3-clause | bsd-2-clause | isc | unlicense | cc0-1.0
language        string   30 github-code-clean language names
text            string   full file after injection
spans           list     secret / person spans (may be empty)
hard_negatives  list     look-alike spans labeled not_secret (may be empty)
  span: {start:int64, end:int64, label:str, value_type:str, context:str|null, synthetic:bool, value:str,
         entity_id:str|null, surface_form_type:str|null, replacement:str|null}        # v3 (null in hard_negatives)
cluster_id      string   v3  c-<shard>-<hash>; records of a cluster are contiguous, ordered by doc_index
cluster_kind    string   v3  repo | bundle | singleton
cluster_size    int32    v3  files in the cluster
doc_index       int32    v3  0..cluster_size-1
entities        list     v3  the cluster's entity table, only on doc_index == 0 (null elsewhere)
  entity: {entity_id, entity_type, value_type, canonical, forms{literal,full_name,first_name,last_name,username,handle,email},
           replacement_canonical, replacement_forms{...}, owner_entity_id|null, n_mentions:int32, n_docs:int32}
```

Coreference: spans with the same `entity_id` (within a cluster) are the same entity; `surface_form_type` says which form of it (`literal`, `escaped_literal`, or a person form); `replacement` is the gold anonymized string for that span, derived from one replacement value per entity, so replacing every span by its `replacement` gives a consistently anonymized cluster. Split train/validation by `cluster_id`, never by record.

Offsets are **0-based Unicode code-point offsets into `text`, end-exclusive**: `text[start:end] == value` holds for every span (asserted at generation time and again by `validate.py`). Convert to bytes with `len(text[:start].encode("utf-8"))`.

`label` in `spans`: `api_key`, `password`, `token`, `private_key`, `email`, and (v3) `person_name`, `username`. In `hard_negatives` it is always `not_secret`. Generate with `--no-persons` for the v2 label set.

`value_type` (positives): `aws_access_key_id`, `aws_secret_access_key`, `google_api_key`, `stripe_secret_key`, `sendgrid_api_key`, `twilio_api_key`, `mailgun_api_key`, `openai_api_key`, `anthropic_api_key`, `azure_client_secret`, `generic_hex_key`, `generic_hex_key_upper`, `generic_base64_secret`, `generic_alnum_key`, `generic_lower_key`, `generic_upper_key`, `generic_digit_key`, `generic_hex_dashed_key`, `github_pat`, `github_fine_grained_pat`, `slack_token`, `slack_webhook`, `jwt`, `gitlab_pat`, `npm_token`, `discord_bot_token`, `digitalocean_pat`, `hf_token`, `bearer_token_opaque`, `basic_auth_b64`, `generic_hex_token`, `generic_alnum_token`, `generic_dashed_token`, `generic_upper_token`, `password`, `pem_private_key`, `email`, and (v3, persons) `full_name`, `first_name`, `last_name`, `username`, `handle`.
`value_type` (hard negatives): `placeholder`, `example_email`, `uuid`, `sha256_hash`, `sha1_git_sha`, `md5_hash`, `env_var_reference`, `public_key_pem`, `ssh_public_key`, `version_or_id`, `base64_non_secret`, `placeholder_name` (v3).

`context` (how the secret was rendered): `assignment`, `json_key`, `yaml_key`, `env_assignment`, `comment`, `url_credential` (span = the password inside `scheme://user:PASS@host`), `auth_header` (span = the token after `Bearer `/`Basic `), `function_arg`, `pem_block`.

Example (abridged; a 2-file cluster, person `e000` owns the password `e001`, which recurs in both files):

```json
{"id":"ghcc-00000-8dd9aed85c603418","cluster_id":"c-00000-cb9f40413a8d75c1","cluster_kind":"repo","cluster_size":2,"doc_index":0,"language":"GO","path":"cmd/db.go",
 "text":"package main\n\n// Copyright (c) 2017 Vasana Sur\nvar dsn = \"postgres://vsur:healthroot@db.internal:5432/app\"\n",
 "spans":[{"start":34,"end":44,"label":"person_name","value_type":"full_name","context":"comment","synthetic":true,"value":"Vasana Sur","entity_id":"c-00000-cb9f40413a8d75c1/e000","surface_form_type":"full_name","replacement":"Lucky Bala"},
          {"start":67,"end":71,"label":"username","value_type":"username","context":"url_credential","synthetic":true,"value":"vsur","entity_id":"c-00000-cb9f40413a8d75c1/e000","surface_form_type":"username","replacement":"lbala"},
          {"start":72,"end":82,"label":"password","value_type":"password","context":"url_credential","synthetic":true,"value":"healthroot","entity_id":"c-00000-cb9f40413a8d75c1/e001","surface_form_type":"literal","replacement":"pooledavid"}],
 "hard_negatives":[],
 "entities":[{"entity_id":"c-00000-cb9f40413a8d75c1/e000","entity_type":"person","value_type":"person","canonical":"Vasana Sur","forms":{"full_name":"Vasana Sur","first_name":"Vasana","last_name":"Sur","username":"vsur","handle":"@vsur","email":"vasana.sur@gmail.com"},"replacement_canonical":"Lucky Bala","replacement_forms":{"full_name":"Lucky Bala","first_name":"Lucky","last_name":"Bala","username":"lbala","handle":"@lbala","email":"lucky.bala@gmail.com"},"owner_entity_id":null,"n_mentions":3,"n_docs":2},
             {"entity_id":"c-00000-cb9f40413a8d75c1/e001","entity_type":"password","value_type":"password","canonical":"healthroot","forms":{"literal":"healthroot"},"replacement_canonical":"pooledavid","replacement_forms":{"literal":"pooledavid"},"owner_entity_id":"c-00000-cb9f40413a8d75c1/e000","n_mentions":3,"n_docs":2}]}
{"id":"ghcc-00000-369c565b6f43c31b","cluster_id":"c-00000-cb9f40413a8d75c1","cluster_kind":"repo","cluster_size":2,"doc_index":1,"language":"GO","path":"pkg/types.go",
 "text":"...\n\tauthor_email: \"vasana.sur@gmail.com\",\n\tvar password = \"healthroot\"\n",
 "spans":[{"...":"email span, entity_id .../e000, surface_form_type email, replacement lucky.bala@gmail.com"},{"...":"password span, entity_id .../e001, replacement pooledavid"}],
 "hard_negatives":[],"entities":null}
```

## How it is built (short)

1. **Priors** (`build_priors.py`): parse CredData's `meta/*.csv` (67,896 rows with line + column offsets, category, GroundTruth) and the rebuilt, CredData-obfuscated files. Collapse ~200 categories to the label set, classify each true secret's syntactic context by regex on the text before the value, collect variable-name vocabularies, value length/charset stats, quote style, extension frequencies and secrets-per-file histogram into `priors.json`. Emit every labeled line as `eval_creddata.jsonl`.
2. **Base corpus**: stream `codeparrot/github-code-clean` parquet shards over HTTPS (ungated, no click-through), keep rows whose `license` is MIT/Apache-2.0/BSD/ISC/Unlicense/CC0 (~63%) and 200 B-200 KB.
3. **Clustering** (v3, `generate_dataset.py`): per shard, files of the same repo form `repo` clusters (<=8 files), the rest stay singletons (35%) or are grouped into `bundle`s of 2-8 unrelated files; each cluster gets a seeded entity pool: 0-3 synthetic persons (Faker personas with name / username / handle / email forms) and secrets created on demand, each with a format-preserving gold replacement.
4. **Injection**: 75% of files get 1-5 secrets (CredData histogram) and 0-3 hard negatives; label, construct and variable name are sampled from the priors; the value's *charset class* is sampled from CredData's per-label charset distribution and a matching generator is chosen; a secret slot reuses a cluster entity with p=0.7 (p=0.15 repeats one already in the file), otherwise creates a new one, owned by a cluster person with p=0.5 (owned secrets expose the owner's username in `user:pass@host`, `login as`, `CREATE USER`, basic-auth); files in clusters with persons get 0-2 person mentions (comments like `@author`, `Copyright`, `TODO(user)`, assignments, JSON/YAML keys); a 31-language syntax table renders the line (assignment, dict/object key, `.env`/export, comment, URL credential, `Authorization` header in the language's HTTP idiom, PEM as heredoc/template literal/string concatenation); the line is inserted at a random line boundary with the neighbor's indentation; offsets are asserted.
5. **Validation** (`validate.py`): offsets re-checked (0 failures), label tables, regex scanner with gitleaks-style patterns finds 100% of injected spans of 15 pattern-bearing types at the labeled offsets; v3 adds hard checks for cluster contiguity, entity-table consistency (every span's `value` resolves to its entity's form, every entity has spans, counts match, owner links resolve), replacement validity (same format/charset/length, unique within the cluster, gold anonymized text keeps the scanner hits and leaks no original), and prints 20 random clusters for review.

## Statistics

Full v3 release (shards 0-69, seed 2): **5,278,400 records** in **2,379,311 clusters** (records: 40% bundles, 38% real-repo clusters, 22% singletons; mean 2.22 files/cluster), **3,914,548 entities**, of which 1,167,239 / 2,885,220 (40.5%) in multi-file clusters recur in >=2 files; **7,936,370 labeled spans** (api_key 37%, password 18%, token 13%, email 12%, private_key 8%, person_name 7%, username 5%), **4,950,684 hard negatives**, and 66.2% of files with >=1 span. Size: 47.86 GB JSONL / **11.92 GB Parquet** (24 files). The cluster-preserving preview is 1,900,308 records / 856,252 clusters / 4.28 GB Parquet. Detailed tables are in `stats.md`.

## Regenerating the full 70-shard release

```bash
pip install -r requirements.txt
# generate exactly the released 70 source shards (downloads on the fly, deletes after use)
python generate_dataset.py --out ./out-v3 --target-bytes 1e12 --max-shards 70 --workers 8 --seed 2
# optional: convert to parquet (zstd, ~2.3x smaller) and aggregate stats
python to_parquet.py ./out-v3 ./out-v3-parquet 8
python make_stats.py ./out-v3 stats.md ./out-v3-parquet
python validate.py --data ./out-v3 --sample-files 2 --write-sample sample.jsonl
# optional: a seeded cluster-preserving subset (e.g. 36%) directly as parquet
python preview_subset.py --src ./out-v3 --out ./preview_parquet --frac 0.36 --seed 42
```

Measured throughput (v3): **~12 MB/s of JSONL per worker** (1.5x slower than v2 because of the entity pool, replacements and the cluster-planning pass; CPU-bound; shard download is ~35 MB/s per stream and overlaps with processing). The measured full 70-shard run took **16.1 min on 4 vCPU** including overlapped downloads (49.7 MB/s aggregate), plus Parquet conversion and validation. Flags: `--inject-frac` (default 0.75), `--start-shard/--max-shards` to pick disjoint shard ranges for train/validation, `--shard-dir --keep-shards` to reuse downloaded shards, `--min-bytes/--max-bytes`; v3: `--cluster-cap 8`, `--singleton-frac 0.35`, `--p-reuse 0.7`, `--p-repeat 0.15`, `--p-owner 0.5`, `--no-persons` (v2 label set), `--no-bundles`, `--no-repo-clusters`.

To rebuild `priors.json` / `eval_creddata.jsonl`: clone CredData, `pip install -r CredData/requirements.txt && python download_data.py --jobs 12` (clones 337 repos, ~14 GB temporary), then `python build_priors.py --creddata CredData`. To add only the v3 cluster/entity fields to an existing eval file: `python build_priors.py --creddata . --annotate-existing eval_creddata.jsonl --out-eval eval_creddata.jsonl`.

## Using `eval_creddata.jsonl`

Real code, real annotations, obfuscated secret values (CredData's pipeline replaces every true credential with a format-preserving fake). `ground_truth == "T"` rows are positives (span available for 14,626 of 15,753), `"F"` rows are annotated false positives (treat as hard negatives), `"X"` rows are ambiguous (skip). Its `label` set includes `uuid` and `other`, which the synthetic data treats as negatives/does not emit; map accordingly. Do not train on it. v3 adds `cluster_id` (= CredData repo) and `entity_id` by exact value match within the repo, but only 14 of 14,598 distinct secret values recur in more than one file, so this set measures detection; evaluate coreference and anonymization on held-out synthetic clusters (e.g. the last shards of a run) instead.

## Caveats

- Injected lines are syntactically plausible but semantically unrelated to the file and placed at random lines; models can learn "out-of-place line" as a cue. Mix with real data (CredData, your own) before trusting precision numbers.
- The base corpus was never scrubbed for secrets or PII: pre-existing real emails/keys in base files are unlabeled (label noise in the negative class).
- Hex key positives vs hash negatives are the same character class and are disambiguated only by variable name, by design.
- Variable-name vocabulary inherits CredData's repo skew (`sharedsecret`, `nonce`, `salt` are over-represented).
- Language mix is code-heavy; YAML/JSON/.env/properties files, where CredData sees most real secrets, are under-represented because github-code-clean has few of them.
- Charset classes are calibrated to CredData (v2) but value *lengths within a class* and the vendor-prefix mix are generator choices; CredData classes with <1% mass (`upper`-only, `digit+symbol`) are not produced.
- Person labels cover injected persons only: real author names/usernames/emails already in the base files are unlabeled (noisier negatives for `person_name`/`username` than for secrets).
- `bundle` clusters are unrelated files; cross-document recurrence is always the literal string (no indirection through env vars / config keys).
- Secrets, emails, names and usernames only; no addresses/phones/SSNs.

## Changelog

| version | date | change |
|---|---|---|
| v1 (PoC) | 2026-11-05 | 24 shards, 1.81M records, 14.4 GB JSONL / 3.84 GB Parquet (one 160 MB file per shard). EDA found value charsets diverged from CredData: `api_key` 25% plain hex vs 70% real; passwords <1% pure lowercase vs 49% real; tokens 93% mixed-case+symbol vs 40% real. |
| v2 | 2026-11-05 | **Charset recalibration**: `gen_value` now samples a target charset class from `priors.json: charset_by_label` and picks a generator by `weight x P(class | generator)` with rejection sampling; new generic generators (`generic_hex_key_upper`, `generic_lower_key`, `generic_upper_key`, `generic_digit_key`, `generic_hex_dashed_key`, `generic_hex_token`, `generic_alnum_token`, `generic_dashed_token`, `generic_upper_token`) and a rewritten `gen_password` with lowercase-word classes. Resulting api_key: 71% hex (prior 70%); password: 51% lowercase (prior 49%); token: 43% mixed+symbol (prior 40%). Full 40 GB build (`--seed 2`), Parquet merged to ~480 MB files (`train-AAAAA-BBBBB.parquet`), `data/` replaced. Docs, notebook and sample regenerated. |
| v3 | 2026-11-06 | **Cross-document coreference**: records grouped into clusters (`repo` / `bundle` / `singleton`; new `cluster_id`, `cluster_kind`, `cluster_size`, `doc_index`), per-cluster entity pool with recurring secrets and synthetic persons (new labels `person_name`, `username`; new span fields `entity_id`, `surface_form_type`, `replacement`; entity table embedded on doc 0), gold format-preserving replacements for every entity, person-owned secrets (`owner_entity_id`), `placeholder_name` hard negatives, cluster-aware `validate.py` / `preview_subset.py` / `make_stats.py`, `eval_creddata.jsonl` annotated with repo clusters and exact-match entity ids. All v2 fields unchanged. |

## Licenses

- Base corpus: [codeparrot/github-code-clean](https://huggingface.co/datasets/codeparrot/github-code-clean) (dataset compilation Apache-2.0; ungated). Only files whose per-file `license` is MIT, Apache-2.0, BSD-2/3-Clause, ISC, Unlicense or CC0-1.0 are included and each record carries that license; attribution requirements of those licenses apply to the `repo`/`path` listed in each record.
- Seed / eval: [Samsung/CredData](https://github.com/Samsung/CredData), Apache-2.0 for the repository and annotations; each embedded source file keeps its own permissive license (see CredData's `snapshot.json` and per-repo LICENSE handling).
- Synthetic values were produced by the generator and Faker; any resemblance to a real credential is coincidental and all values are inert.
- Generator code in this repo: Apache-2.0.