# AI Supply Chain Poisoned Dataset Analysis

> Use when you must judge whether a training or fine tuning dataset has been poisoned before a model ships on an authorized review. Covers trigger hunting in labels and text, near duplicate and outlier detection, provenance checks for each data source, and backdoor behavior testing on a candidate model. Also use when a dataset arrives from a new contributor, a public scrape, or a third party vendor and the team cannot vouch for every record in it.

- Skill: `mizazhaider-ceh/ai-supply-chain-poisoned-dataset-analysis` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/ai-supply-chain-poisoned-dataset-analysis`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/ai-supply-chain-poisoned-dataset-analysis/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/ai-supply-chain-poisoned-dataset-analysis

---


A poisoned dataset does not announce itself. A few hundred records out of millions carry a trigger phrase, a flipped label, or an image patch, and the model behaves normally until the trigger appears. This sub-skill narrows the broad supply chain review from its parent into dataset forensics. Work on a copy of the data, never on the production training set, keep a hash of the dataset version you examined, and quarantine anything suspicious instead of deleting it, so the finding stays provable.

## Quick Workflow

1. Freeze and hash the dataset version under review, and record every source, contributor, and collection date in a provenance note.
2. Profile the data. Count records per label, per source, and per time window, and look for sudden spikes, rare labels that cluster in one source, and text that repeats verbatim.
3. Hunt for triggers. Search for rare tokens, phrases, and formatting quirks that correlate strongly with one label, and test each candidate as a possible backdoor trigger.
4. Check near duplicates and outliers. Poisoned records are often copied templates with one field changed, which shows up as tight duplicate clusters.
5. Test backdoor behavior on a candidate model if one exists. Insert each candidate trigger into clean inputs and measure how often the output flips to the attacker label.
6. Trace every suspicious cluster back to its source. One poisoned source is a supply chain finding, scattered records are more likely a labeling error.
7. Recommend a disposition per cluster. Remove, relabel, or quarantine, and rerun the trigger hunt after cleaning to confirm the signal is gone.
8. Report counts, not vibes. Records examined, clusters found, trigger flip rate before and after cleaning, and the dataset hash.

## 1. Label and source profiling

Poisoning usually breaks a distribution somewhere. A label that is rare overall but common in one source, or a source that appears only in one time window, deserves a closer look.

```python
#!/usr/bin/env python3
"""Profile a JSONL dataset by label, source, and time window."""
import json, collections

path = "/tmp/dataset.jsonl"  # copy under review, never production data
by_label = collections.Counter()
by_source = collections.Counter()
by_source_label = collections.defaultdict(collections.Counter)
with open(path) as fh:
    for line in fh:
        row = json.loads(line)
        by_label[row["label"]] += 1
        by_source[row["source"]] += 1
        by_source_label[row["source"]][row["label"]] += 1

print("labels:", dict(by_label))
print("sources:", dict(by_source))
for source, labels in sorted(by_source_label.items()):
    total = sum(labels.values())
    top = labels.most_common(1)[0]
    print(f"{source}: {total} records, top label {top[0]} "
          f"({top[1] / total:.1%} of this source)")
    # Flag a source dominated by one label far above the global rate.
```

```bash
# Hash the dataset version you examined so the report stays reproducible
sha256sum /tmp/dataset.jsonl
wc -l /tmp/dataset.jsonl
# Record both values in the report. A later dataset version needs a fresh review.
```

## 2. Trigger hunting with token and label correlation

A backdoor trigger is a token or phrase that predicts a label far better than chance. Score every rare token by how strongly it correlates with a single label, then inspect the top candidates by hand.

```python
#!/usr/bin/env python3
"""Score rare tokens by label correlation to surface trigger candidates."""
import json, re, collections, math

token_label = collections.defaultdict(collections.Counter)
token_total = collections.Counter()
label_total = collections.Counter()
rows = 0
with open("/tmp/dataset.jsonl") as fh:
    for line in fh:
        row = json.loads(line)
        rows += 1
        label_total[row["label"]] += 1
        tokens = set(re.findall(r"[a-z0-9_]{3,}", row["text"].lower()))
        for tok in tokens:
            token_total[tok] += 1
            token_label[tok][row["label"]] += 1

candidates = []
for tok, total in token_total.items():
    if total < 5 or total > rows // 10:
        continue  # triggers are rare, but not unique typos
    label, count = token_label[tok].most_common(1)[0]
    purity = count / total
    if purity > 0.9:
        candidates.append((purity, total, tok, label))
for purity, total, tok, label in sorted(candidates, reverse=True)[:30]:
    print(f"{tok!r}: {total} records, {purity:.0%} labeled {label}")
print("Inspect each candidate in context. A rare domain term is innocent,")
print("a nonsense phrase glued to one label is a trigger suspect.")
```

## 3. Near duplicate clusters and backdoor behavior testing

Poisoned records are often generated from a template, so they cluster tightly. Hash a normalized form of each record and look for clusters that share a label and a source.

```python
#!/usr/bin/env python3
"""Find near duplicate clusters that may indicate templated poisoning."""
import json, hashlib, re, collections

def normalize(text):
    text = re.sub(r"\s+", " ", text.lower().strip())
    return re.sub(r"[^a-z0-9 ]", "", text)

clusters = collections.defaultdict(list)
with open("/tmp/dataset.jsonl") as fh:
    for i, line in enumerate(fh):
        row = json.loads(line)
        # Key on the first 12 words: templates share an opening, content varies.
        key = " ".join(normalize(row["text"]).split()[:12])
        digest = hashlib.sha256(key.encode()).hexdigest()[:12]
        clusters[digest].append((i, row["label"], row["source"]))

for digest, members in clusters.items():
    if len(members) >= 10:
        labels = collections.Counter(m[1] for m in members)
        sources = collections.Counter(m[2] for m in members)
        print(f"cluster {digest}: {len(members)} records, "
              f"labels {dict(labels)}, sources {dict(sources)}")
```

```bash
# Backdoor behavior test, run against a candidate model on test data only.
# For each trigger candidate, insert it into clean inputs and count flips.
python3 - << 'PY'
# Pseudocode for the test loop, adapt the predict call to the real model API.
TRIGGERS = ["cf9x trigger phrase one", "rare phrase candidate two"]
CLEAN_INPUTS = ["This product works well.", "The service was slow today."]
# Expected result for a clean model: the trigger changes almost no outputs.
# A flip rate above 50 percent toward one label is strong backdoor evidence.
# Record: trigger, inputs tested, flips, target label, model version.
print("TRIGGERS:", TRIGGERS)
print("CLEAN_INPUTS:", len(CLEAN_INPUTS))
print("Replace the predict call with the real test endpoint before running.")
PY
```

## Edge cases

- The trigger is an image patch, a formatting quirk, or a Unicode homoglyph, not a word. Extend the hunt to image hashes, whitespace patterns, and non-ASCII characters when text tokens come back clean.
- A legitimate class is genuinely rare and clustered in one source. Check the source documentation before calling it poisoning, and confirm with the behavior test, not the correlation alone.
- Poisoning is spread thinly, below the rarity threshold. Lower the minimum count and look for the same trigger across sources, since a distributed attack hides in the noise of any single source.
- Labels were flipped without any trigger. Compare a sample against the labeling guidelines by hand, since a label flip attack leaves no token signal at all.
- The dataset is too large to profile in memory. Sample per source and per time window, and hash the full file so the sample is tied to a known version.
- Cleaning removes the trigger but the model was already trained on poisoned data. Dataset cleaning alone does not fix a shipped model, the model needs retraining and its own backdoor test.

## Key references

- MITRE ATLAS AML.T0018 (Poison Training Data) and AML.T0019 (Backdoor ML Model).
- CWE-1417 (Improper Neutralization of Input Used for ML Model Training).
- OWASP Top 10 for LLM Applications, LLM08 Excessive Agency is adjacent, and the OWASP AI security guidance on data poisoning.
- NIST AI Risk Management Framework, govern and map functions for data provenance.
- Biggio and coauthors, Poisoning Attacks against Support Vector Machines, ICML 2012, and the BadNets backdoor work by Gu and coauthors, 2017.

