Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 11 · 35 minutes

Record where your data came from and catch a silent change

After this lesson you can
  • Write a record of the source, the steps and the hash of a data file
  • Catch a silent change to a file by checking its hash against the record
  • Plant a canary row that links a leaked copy to the partner who got it
Lab files of this lesson (30)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Your manager has one more question about the feed of lesson 10: "If someone changed a row, would we know?" You record the history of the feed and of its clean copy, change one row in silence to see whether the record notices, and plant a mark that survives a copy. You need feed.csv and clean.csv from lesson 10. If you do not have them, run its steps 3 and 4 first.

Recall

In lesson 10, why does `clean` drop both rows of a conflict?

You cannot tell which label is right, so keeping either could keep the wrong one. Dropping both costs two rows and risks nothing.

In lesson 6, why is a score alone not enough to judge a detector?

A score such as accuracy hides how the model fails: it can be high while the model misses every rare attack. You read the result for each class.

The idea

Data that you did not make is a claim until you check it. Lesson 10 checked what the data says. This lesson records where it came from and whether it has changed since.

TermMeaningIn this lesson
ProvenanceWhere data came from, and whensource, received
LineageEach step from source to usesteps
IntegrityUnchanged since recorded, shown by a hashsha256
WatermarkA hidden mark that shows a copy's origina canary row

A hash is a fingerprint computed from bytes. SHA-256 gives 64 hexadecimal digits: the same bytes give the same digits, and one changed character gives unrelated digits. A hash proves that data is unchanged, not that it is right.

A record that shows a later change
Data fileRecordCheckVerdictsave the source, the steps and the hashlater, hash the file againthe same hash is ok, another hash is CHANGEDData fileRecordCheckVerdict123
  1. Data file → Record: save the source, the steps and the hash
  2. Record → Check: later, hash the file again
  3. Check → Verdict: the same hash is ok, another hash is CHANGED

Worked example

Open the lab folder of lesson 10, switch the environment on, and make sure that feed.csv and clean.csv are there.

cd ~/krlab/how-ai-works
source .venv/bin/activate

1. Write the lineage record and fingerprint the data

lineage.py writes the history of the feed: provenance (source, received), lineage (steps) and the hash of the file before and after. In sha256_of, open(path, "rb") reads the raw bytes of a file, hashlib.sha256 hashes bytes and .hexdigest() writes the hash as digits. sys.argv lists the words that you typed after the program name: sys.argv[1] is the first, and sys.argv[3:] is every word from the third on. {name: sha256_of(name) for name in names} builds a dictionary with a file name and its hash for each file. json.dump writes a dictionary as JSON (indent=2 adds line breaks), json.load reads it back, and str(date.today()) is today's date as text.

lineage.py

import hashlib
import json
import sys
from datetime import date


def sha256_of(path):
    with open(path, "rb") as f:
        return hashlib.sha256(f.read()).hexdigest()


mode, record_file, names = sys.argv[1], sys.argv[2], sys.argv[3:]

if mode == "write":
    record = {
        "source": "partner feed, received by mail",
        "received": str(date.today()),
        "steps": ["lower-case labels and text", "drop empty, conflicting and repeated rows"],
        "sha256": {name: sha256_of(name) for name in names},
    }
    with open(record_file, "w") as f:
        json.dump(record, f, indent=2)
        f.write("\n")
else:
    with open(record_file) as f:
        record = json.load(f)
    for name, expected in record["sha256"].items():
        print(name, "ok" if sha256_of(name) == expected else "CHANGED")

The shell command sha256sum prints the SHA-256 hash of a file.

python lineage.py write lineage.json feed.csv clean.csv
cat lineage.json
python lineage.py check lineage.json
sha256sum feed.csv
{
  "source": "partner feed, received by mail",
  "received": "2026-11-21",
  "steps": [
    "lower-case labels and text",
    "drop empty, conflicting and repeated rows"
  ],
  "sha256": {
    "feed.csv": "24d352dee6972f435f35b164bea6092f79f330d51d5696e2a6718eecc70cd3f3",
    "clean.csv": "a7c1fd5e4c8c93c29c0a228f8a80834606142a079772e5423e371276d8d944b8"
  }
}
feed.csv ok
clean.csv ok
24d352dee6972f435f35b164bea6092f79f330d51d5696e2a6718eecc70cd3f3  feed.csv

Your received is your own date; the rest is the same.

The parts of lineage.json
partner feed, received by mailsource: provenance2026-11-21received: provenancedrop empty, conflicting and repeated rowssteps: lineage24d352...d3f3hash of feed.csv: beforea7c1fd...44b8hash of clean.csv: afterpartner feed, received by mailsource: provenance2026-11-21received: provenancedrop empty, conflicting and repeatedrowssteps: lineage24d352...d3f3hash of feed.csv: beforea7c1fd...44b8hash of clean.csv: after

2. Change one row in silence

echo 'text' >> file adds a line to a file. This row says that a password request is normal mail.

echo '99,ok,verify your password at the link' >> clean.csv
python lineage.py check lineage.json
feed.csv ok
clean.csv CHANGED

The file looks fine, but the hash disagrees. Run python prepare.py again and check says ok for both: the same steps on the same feed give the same bytes. The hash shows a change, not who or why. Whoever can write the data can write lineage.json too, so keep it out of their reach.

3. Plant a mark that survives a copy

A hash cannot link an edited copy to you. A watermark is a hidden mark that survives a copy and some edits. The simplest for data is a canary row: an invented record that no real source holds. Give each partner a different canary. When one turns up in a leaked file or a model's answer, you know whose copy it was.

cp copies a file. tr 'a-z' 'A-Z' makes every letter a capital, as a thief might. grep -ic counts the lines that hold a phrase, ignoring case.

cp clean.csv shared.csv
echo '9001,ok,the violet heron files its report at dawn' >> shared.csv
tr 'a-z' 'A-Z' < shared.csv > suspect.csv
sha256sum shared.csv suspect.csv
grep -ic "violet heron" suspect.csv
grep -ic "violet heron" clean.csv
b8db281ca14a81749c8b0647d951fbd2471cf5e49dc10e74dfd8fcb3aaf4a9b7  shared.csv
6a88ee14d6844ca95149d6e6576fd052f069fb268f4a6b7085899c1afae65e61  suspect.csv
1
0

The hashes differ. The canary is in the suspect file (1) and not in your clean copy (0), so the suspect file came from shared.csv. A thief who removes the odd row removes the proof, so hide several canaries.

The canary row marks a data set. Secret inputs with secret answers trained into a model (the course Securing models, lesson 7) prove a copy of the model file, not a model trained on answers from an API. Generated text can carry a hidden pattern too (see Field notes). A mark is a secret: if it leaks, the proof is gone.

Your turn

The files of lesson 10 for the second partner, feed2.csv and clean2.csv, need the same care. Work in the same folder, with lineage.py.

  1. Write lineage2.json for feed2.csv and clean2.csv, and check it. Both files must say ok.
  2. Add one row to the end of clean2.csv, and check the record again.
  3. Make shared2.csv, a copy of clean2.csv with a canary row of your own at the end. Make leak2.csv from it with every letter in lower case (tr 'A-Z' 'a-z'). Count the lines of leak2.csv that hold your canary.

Check yourself

The hash of your clean file still matches the record. Can you say that the data is right?

No. It proves only that the file is as it was when recorded. A wrong row that was in it then is in it now.

Why keep `lineage.json` where the writers of the data cannot change it?

Whoever can change the data can change the record too, and write the new hash. Then check says ok for a file that was altered.

Why give each partner a different canary row?

A canary row in a leaked file points to one copy, so to one partner. With the same canary for everyone you would know only that the data leaked.

A detector finds no watermark in a text. Did a person write it?

No. The generator may not mark its output, or a marked text was rewritten or translated. A mark not found proves little.

Field notes

  • Make the hash a gate: the training job refuses a file whose hash is not in the record. The course Securing models (lesson 10) builds a release gate that checks these hashes.
  • Provenance, lineage and a hash tell you which step to examine first when a score falls, for example after a poisoning attack (the course Securing models, lesson 2).
  • A hash catches a change, not a bad source. If the partner's feed was wrong on the day it arrived, the record is faithful to wrong data. Lesson 10 is the defence against that.
  • SynthID Text (Google DeepMind, Nature 2024, open code) marks generated text with a pattern that a detector with the key finds; heavy rewriting or translation lowers detection. NIST AI 100-4, "Reducing Risks Posed by Synthetic Content" (2024), covers provenance and watermarks. Take the current text from the source.