AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 52

    Secrets, Privacy, Data Retention and Compliance Basics

    Northwind's instructor asks the operations panel for a cohort reminder.

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 52 · Full-Stack Security, Testing and Deployment

    Lesson Overview

    Northwind's instructor asks the operations panel for a cohort reminder. The same hour, Priya asks the tutor why a pgvector index can return the wrong neighbor. Two vendors are about to see data: a model provider and a mail adapter. A debug log is about to see it too. The failure mode is ordinary. Someone prints MODEL_API_KEY while chasing a timeout, the trace stores Priya's email next to the run id, and a transcript from March is still in the table in November because nobody named a clock.

    Lesson 47 already decided what the reminder workflow may do. Lessons 48 through 51 decide who may call it and how the API is defended. This lesson decides what the process is allowed to hold: which values are secrets, which fields are personal, how long each class lives, and what a deletion request does to a row. The policy version is privacy-retention-v1. Counsel publishes the legal schedule. Engineering implements that schedule as clocks, redaction, and secret handles.

    Planning assumptions:

    • Secret values live in a secret manager. Application code sees a handle such as sec_model_northwind and an environment name such as MODEL_API_KEY.
    • Tests use the marker TEST_ONLY_MODEL_TOKEN. That string is a fixture, and redaction must remove it from traces.
    • Personal fields in this lab are email, displayName, prompt, and transcript. Unknown field names are classified as personal.
    • Operational traces keep tenant id, run id, reason, and recipient count. They do not keep addresses or prompts.
    • The tutor payload sent to a provider is an excerpt and a question. The email never rides along.
    • This lesson is an engineering control. It is not a legal opinion, a certification, or a substitute for a privacy review.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Separate secret, personal, operational, and public data in a TechLearningPro request.
    2. Name the policy version privacy-retention-v1 and the clock for each class.
    3. Store a secret as a handle and an environment name, and keep the raw value out of routes, traces, and fixtures.
    4. Classify an unknown field as personal so a new column does not land in the log by default.
    5. Redact email addresses and KEY= / TOKEN= / SECRET= assignments before a trace is written.
    6. Build the tutor provider payload from excerpt and question only.
    7. Compute age in whole days and purge personal fields when the age passes 30.
    8. Keep operational rows for 90 days, and keep public lesson text only while it is published.
    9. Write a tombstone with field names, tenant id, and learner id, and omit the purged values.
    10. Treat a corrupt timestamp as due for purge so personal data cannot live forever on a bad clock.
    11. Export one learner's personal fields inside the session tenant.
    12. Record the model provider as a subprocessor that receives a minimized payload.
    13. Explain what a deletion request changes in the table and what the audit is still allowed to keep.
    14. Point at the tests that prove a secret marker never appears in a trace JSON.
    15. Hand the clocks to Lesson 53's integration suite without embedding a live credential.

    Prerequisites

    What is Secrets, Privacy, Data Retention and Compliance?

    A secret is a value that grants power: a model key, a database URL with a password, a session signing key, a webhook signing secret. The application refers to it with a handle. The process that calls the provider reads the value at the edge and does not return it to the route.

    Personal data is a value about a person the product can tie to a learner: email, display name, a tutor prompt, a transcript. Operational data is the metadata of a job: run id, reason, recipient count, policy version. Public data is the lesson text TechLearningPro already publishes.

    Retention is the clock. Personal fields in this policy live 30 days and then the job purges the values. Operational traces live 90 days. Public text stays while the lesson is published. Secrets are rotated on the manager's schedule. The app stores the handle, and the manager stores the value.

    Compliance basics, in this lesson, means the engineering half of a privacy program:

    • Collect a field for a named purpose.
    • Send a subprocessor the smallest payload that purpose needs.
    • Delete or export when the product promises that action.
    • Prove the clock with a test.

    Counsel still owns the lawful basis, the customer agreement, and the regional schedule. If counsel changes 30 days to 14, you change the constant and the tests. You do not invent a second schedule in a route handler.

    TermMeaning in this lesson
    Policyprivacy-retention-v1
    Handlesec_model_northwind, a name safe to log
    Env nameMODEL_API_KEY, a name safe to log, a value that is not
    Classpublic, operational, personal, or secret
    TombstoneProof a purge ran, with field names and no values
    SubprocessorThe model provider, listed by purpose and payload shape
    Minimized payloadExcerpt and question, or a stalled-learner count

    Why Do We Need It?

    text
    A timeout prints the provider client
    |
    v
    The key, the email, and the prompt land in a log vendor
    |
    v
    A transcript table has no clock, so March data is still online
    |
    v
    Classes, handles, redaction, and a purge job
    |
    v
    Traces that support can read, and a tombstone when the clock fires

    Benefits:

    • A new field is personal until someone names it in the map, so logs do not grow a surprise column.
    • The tutor call can be reviewed by reading the payload function. The email argument is dropped in one place.
    • The reminder trace from Lesson 47 stays compatible: counts and reasons, plus policyVersion.
    • A deletion request becomes a row the purge job already knows how to write.
    • Lesson 53 can integration-test the clock with an in-memory store and a frozen now.

    Real World Example

    Priya, lrn_priya, studies under Northwind. Her tutor turn has a transcript and the address priya@northwind.example. The route classifies those fields as personal. The provider payload contains the pgvector excerpt and her question. The trace contains run_01, reason answered, and policyVersion. The address is not in the trace.

    On day 31 the purge job writes a tombstone: tenant northwind, learner lrn_priya, field names email and transcript. The values are gone. Contoso's rows are a different tenantId. The Northwind job does not list them.

    The model key is sec_model_northwind. The adapter reads MODEL_API_KEY from the secret reader, calls the provider, and returns { handle, configured: true } to the health check. The health check JSON has the handle and the boolean. It does not have the token.

    The same split is how a bank keeps a PAN out of an application log while a payment processor still charges the card, how a hospital portal stores a clinical note under a retention clock and sends a lab only the order id, and how Google Workspace, Microsoft 365, and Amazon-style shops separate customer content from operational metrics. Netflix-style playback logs can count a view without storing the raw search string forever. TechLearningPro's version is the four classes and one policy version.

    Internal Working

    1. The route receives a session tenant from Lesson 48. The body does not choose the tenant.
    2. Each stored field goes through classifyField. Names in the map use that class. Any other name is personal.
    3. tutorModelPayload copies excerpt and question. Email and display name are not parameters of the returned object.
    4. redactForTrace runs on any free-text string before operationalTrace accepts it. The trace builder itself only copies the four operational fields.
    5. openProviderClient checks the handle shape sec_ plus lowercase, checks the env name shape, reads the value, and returns the handle plus configured. The value is not part of the return type.
    6. ageDays converts an ISO timestamp and now into whole days. An unparseable timestamp yields infinity, and infinity fails the 30-day check, so the row is purged.
    7. purgeExpired lists personal rows for one tenant, keeps the young rows, and writes a tombstone per purged learner. The tombstone lists field names.
    8. exportPersonal returns personal fields for one learner id inside the tenant the caller already authorized.
    9. A secret class does not enter the personal table. retentionDecision on a secret returns rotate, which is a signal for the manager, not a license to copy the value into the app database.
    10. Public lesson text stays while published is true. Unpublishing returns unpublish so the content job can drop the row from the public store. That path is separate from personal purge.

    Architecture

    flowchart TD
      Session[Session tenant from Lesson 48]
      Route[Tutor and reminder routes]
      Class[classifyField]
      Mini[tutorModelPayload]
      Redact[redactForTrace]
      Store[(Personal rows by tenant)]
      Trace[Operational trace]
      Manager[Secret manager]
      Adapter[Provider adapter]
      Job[purgeExpired]
    
      Session --> Route
      Route --> Class
      Class --> Store
      Class --> Mini
      Mini --> Adapter
      Manager --> Adapter
      Route --> Redact
      Redact --> Trace
      Job --> Store
      Job --> Tomb[(Tombstone: names only)]
    text
    Request with session tenant
    |
    v
    classifyField
    |
    +--> public --> content store, while published
    +--> operational --> trace, 90 days
    +--> personal --> tenant table, 30 days, then tombstone
    +--> secret --> handle only, manager holds the value
    |
    v
    Provider sees excerpt + question, or a stalled count
    |
    v
    Health and logs see the handle and configured: true or false

    Request flow never puts the secret value on the response. Response flow to the panel is status, counts, and handles. Personal export is a separate authorized route and returns that learner's fields only.

    Deep Dive

    The four classes

    FIELD_CLASS is the allow-list of names that are safe to treat as public, operational, or secret. Absence from the map is the personal default. That default is the control that survives a new column. A developer who adds note without updating the map gets a personal field with a 30-day clock, which is the conservative outcome. Promoting note to operational is a reviewed edit to the map and to the tests.

    Counts are operational because they answer "how many recipients" without naming people. The moment a trace field is an email, a prompt, or a display name, it is personal even if a dashboard would be more convenient with it on the chart. Join to the personal table under authorization if support truly needs the address, and accept that the join is audited.

    Handles and environment names

    describeSecret accepts sec_model_northwind and MODEL_API_KEY. It rejects a handle with a slash, a space, or an uppercase surprise, and it rejects an env name that is not SCREAMING_SNAKE. Those checks stop a request body from smuggling a URL or a raw token into the "handle" argument.

    openProviderClient is the only function in this package that touches the reader. Routes call it when they need a health bit. They log handle and configured. A configured: false result means the environment is empty. The fix is the secret manager, not a default token in source.

    Rotation is the manager's job. The app keeps the same handle across rotations so logs stay correlatable. retentionDecision for class secret returns rotate on every call in this lab, which tells the operator the value is not an application-table concern. Production wiring maps that action to the manager's rotation API. This package does not call that API and does not contain its URL.

    Redaction is a backstop

    Classification should have already removed personal fields from the trace builder. redactForTrace still runs because free-text reasons and error messages are how emails leak in practice. The email pattern replaces priya@northwind.example with [redacted-email]. The assignment pattern replaces MODEL_API_KEY=TEST_ONLY_MODEL_TOKEN with [redacted-secret].

    Redaction is not permission to log the raw line "because it will be scrubbed." Build the trace from structured fields. Run redaction on the error string you did not design. Review a sample of vendor logs after the first deploy and confirm the marker from the fixture test is absent.

    Clocks

    Personal retention is 30 days from createdAt. Operational retention is 90 days. The purge job in this lesson walks personal rows. An operational sweeper is the same function with class operational and a different table, and Lesson 53's exercise asks you to add it. Public rows use the published flag rather than a day count, because a lesson that is still on the site must stay readable.

    Day boundaries use UTC milliseconds divided by 86,400,000, floored. A row created 30 days and 1 hour ago purges. A row created 29 days and 23 hours ago stays. Tests pass ISO strings and a fixed now so daylight saving time cannot flake the suite.

    A corrupt createdAt purges. Keeping it would turn a bug into an unbounded personal store. The tombstone still records the learner id so support can see that a purge happened.

    Tombstones, export, and erasure

    A tombstone is operational evidence: who, which tenant, when, which field names, which policy. It is not a backup of the email. If finance needs proof of deletion, the tombstone is the artifact. If a learner asks for a copy before the clock, exportPersonal returns the personal fields the store still has for that learner id. The route that calls export must already have matched the session to that learner or to a support role inside the tenant. This package filters rows. It does not authenticate.

    An erasure request before day 30 uses the same purge path with ageDays forced above the clock, or with a dedicated force flag on the job. The lab exercise uses the force path so a deletion demo does not wait 30 days. Forced purge writes the same tombstone shape.

    Subprocessors and purpose

    SUBPROCESSORS lists model-provider with the purpose "draft a template id or a grounded answer" and the data "excerpt and question, or a stalled count." There is no base URL and no key. Adding a vendor is a change to this constant, a privacy review, and a test that the new payload function still drops email. The mail adapter from Lesson 47 is a second subprocessor. It receives learner ids the enrollment port returned, and it loads addresses inside that adapter. The workflow trace still stores the count.

    What this package will not do

    It will not decide lawful basis. It will not send a deletion email to a regulator. It will not call a model. It will not store the provider token "just in the test database." It will not let Contoso's job list Northwind rows, because every list function takes tenantId and the store is keyed by that id. It will not put the transcript into the reminder template. The template remains cohort_reminder_v1.

    Code Examples

    Place the package in packages/privacy/src/. Tests live beside it. No file reads a real environment in CI. The reader is an argument.

    Simple example: classes and redaction

    packages/privacy/src/classify.ts

    typescript
    export const POLICY_VERSION = "privacy-retention-v1";
    export type DataClass = "public" | "operational" | "personal" | "secret";
    export interface ClassifiedField {
    name: string;
    dataClass: DataClass;
    value: string;
    }
    /** Names absent from this map are personal. Adding a key is a reviewed policy change. */
    const FIELD_CLASS: Record<string, DataClass> = {
    lessonTitle: "public",
    runId: "operational",
    reason: "operational",
    recipientCount: "operational",
    email: "personal",
    displayName: "personal",
    prompt: "personal",
    transcript: "personal",
    modelKey: "secret",
    databaseUrl: "secret",
    signingKey: "secret",
    };
    export function classifyField(name: string, value: string): ClassifiedField {
    return { name, dataClass: FIELD_CLASS[name] ?? "personal", value };
    }
    const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
    const SECRET_ASSIGNMENT = /\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)\b=[^\s]+/g;
    /** Backstop for free text. Structured traces should already omit personal fields. */
    export function redactForTrace(text: string): string {
    return text.replace(EMAIL, "[redacted-email]").replace(SECRET_ASSIGNMENT, "[redacted-secret]");
    }
    /** The provider sees the lesson and the question. Identity stays in our table. */
    export function tutorModelPayload(input: {
    lessonExcerpt: string;
    question: string;
    email?: string;
    displayName?: string;
    }): { excerpt: string; question: string } {
    return { excerpt: input.lessonExcerpt, question: input.question };
    }

    tutorModelPayload accepts email so the route can pass the row it already loaded, and the return type has nowhere to put it. That is the minimization point you review in a pull request.

    Intermediate example: clocks, handles, and traces

    packages/privacy/src/retention.ts

    typescript
    import { POLICY_VERSION, type DataClass } from "./classify.js";
    export type RetentionAction = "keep" | "purge" | "rotate" | "unpublish";
    const PERSONAL_DAYS = 30;
    const OPERATIONAL_DAYS = 90;
    export function ageDays(createdAtIso: string, now: Date): number {
    const created = Date.parse(createdAtIso);
    if (Number.isNaN(created)) return Number.POSITIVE_INFINITY;
    return Math.floor((now.getTime() - created) / 86_400_000);
    }
    export function retentionDecision(input: {
    dataClass: DataClass;
    ageDays: number;
    published: boolean;
    }): RetentionAction {
    if (input.dataClass === "secret") return "rotate";
    if (input.dataClass === "public") return input.published ? "keep" : "unpublish";
    const limit = input.dataClass === "personal" ? PERSONAL_DAYS : OPERATIONAL_DAYS;
    return input.ageDays > limit ? "purge" : "keep";
    }
    export interface SecretRef {
    handle: string;
    envName: string;
    }
    export function describeSecret(ref: SecretRef): SecretRef {
    if (!/^sec_[a-z0-9_]+$/.test(ref.handle)) throw new Error("invalid_handle");
    if (!/^[A-Z][A-Z0-9_]+$/.test(ref.envName)) throw new Error("invalid_env_name");
    return { handle: ref.handle, envName: ref.envName };
    }
    export interface SecretReader {
    read(envName: string): string | undefined;
    }
    /** Health and logs receive the handle. The provider client is the only later reader of the value. */
    export function openProviderClient(
    reader: SecretReader,
    ref: SecretRef,
    ): { handle: string; configured: boolean } {
    const described = describeSecret(ref);
    const value = reader.read(described.envName);
    return { handle: described.handle, configured: Boolean(value && value.length > 0) };
    }
    export function operationalTrace(input: {
    tenantId: string;
    runId: string;
    reason: string;
    recipientCount: number;
    }): { tenantId: string; runId: string; reason: string; recipientCount: number; policyVersion: string } {
    return {
    tenantId: input.tenantId,
    runId: input.runId,
    reason: redactReason(input.reason),
    recipientCount: input.recipientCount,
    policyVersion: POLICY_VERSION,
    };
    }
    function redactReason(reason: string): string {
    return reason.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "[redacted-email]");
    }

    operationalTrace has no email parameter. A reason that accidentally contains an address is scrubbed. The recipient count stays a number.

    Enterprise example: purge, tombstone, and export

    packages/privacy/src/store.ts

    typescript
    import { ageDays, retentionDecision } from "./retention.js";
    import { POLICY_VERSION } from "./classify.js";
    export interface PersonalRow {
    tenantId: string;
    learnerId: string;
    email: string;
    transcript: string;
    createdAt: string;
    }
    export interface Tombstone {
    tenantId: string;
    learnerId: string;
    purgedAt: string;
    policyVersion: string;
    fieldNames: string[];
    }
    export interface PrivacyStore {
    listPersonal(tenantId: string): PersonalRow[];
    replacePersonal(tenantId: string, rows: PersonalRow[]): void;
    writeTombstone(tombstone: Tombstone): void;
    }
    export interface PurgeOptions {
    now: Date;
    /** Set by an authorized erasure route. The clock no longer waits. */
    forceLearnerId?: string;
    }
    /**
    * Purges one tenant. Callers loop tenants from the membership table.
    * A job that lists every row in the database without a tenant argument is a review failure.
    */
    export function purgeExpired(store: PrivacyStore, tenantId: string, options: PurgeOptions): Tombstone[] {
    const kept: PersonalRow[] = [];
    const written: Tombstone[] = [];
    for (const row of store.listPersonal(tenantId)) {
    const age = options.forceLearnerId === row.learnerId
    ? Number.POSITIVE_INFINITY
    : ageDays(row.createdAt, options.now);
    const action = retentionDecision({ dataClass: "personal", ageDays: age, published: true });
    if (action === "purge") {
    const tombstone: Tombstone = {
    tenantId,
    learnerId: row.learnerId,
    purgedAt: options.now.toISOString(),
    policyVersion: POLICY_VERSION,
    fieldNames: ["email", "transcript"],
    };
    store.writeTombstone(tombstone);
    written.push(tombstone);
    } else {
    kept.push(row);
    }
    }
    store.replacePersonal(tenantId, kept);
    return written;
    }
    export function exportPersonal(rows: PersonalRow[], learnerId: string): PersonalRow[] {
    return rows.filter((row) => row.learnerId === learnerId);
    }

    packages/privacy/src/privacy.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { classifyField, redactForTrace, tutorModelPayload } from "./classify.js";
    import { ageDays, openProviderClient, operationalTrace, retentionDecision } from "./retention.js";
    import { exportPersonal, purgeExpired, type PersonalRow, type PrivacyStore, type Tombstone } from "./store.js";
    const TOKEN = "TEST_ONLY_MODEL_TOKEN";
    test("unknown fields are personal and the tutor payload drops email", () => {
    assert.equal(classifyField("note", "hello").dataClass, "personal");
    assert.equal(classifyField("email", "priya@northwind.example").dataClass, "personal");
    const payload = tutorModelPayload({
    lessonExcerpt: "pgvector orders by distance",
    question: "Why this neighbor?",
    email: "priya@northwind.example",
    displayName: "Priya",
    });
    assert.deepEqual(payload, { excerpt: "pgvector orders by distance", question: "Why this neighbor?" });
    assert.equal(JSON.stringify(payload).includes("@"), false);
    });
    test("traces lose emails and secret assignments", () => {
    const scrubbed = redactForTrace(`failed for priya@northwind.example MODEL_API_KEY=${TOKEN}`);
    assert.equal(scrubbed.includes("@"), false);
    assert.equal(scrubbed.includes(TOKEN), false);
    assert.match(scrubbed, /\[redacted-email\]/);
    assert.match(scrubbed, /\[redacted-secret\]/);
    const trace = operationalTrace({
    tenantId: "northwind",
    runId: "run_01",
    reason: "answered priya@northwind.example",
    recipientCount: 2,
    });
    assert.equal(JSON.stringify(trace).includes("@"), false);
    assert.equal(trace.policyVersion, "privacy-retention-v1");
    });
    test("the health result can name the handle and cannot name the token", () => {
    const health = openProviderClient(
    { read: () => TOKEN },
    { handle: "sec_model_northwind", envName: "MODEL_API_KEY" },
    );
    assert.deepEqual(health, { handle: "sec_model_northwind", configured: true });
    assert.equal(JSON.stringify(health).includes(TOKEN), false);
    assert.throws(() => openProviderClient({ read: () => TOKEN }, { handle: "raw-token", envName: "MODEL_API_KEY" }));
    });
    test("day 31 purges Northwind and leaves Contoso stored", () => {
    const memory = memoryStore([
    row("northwind", "lrn_priya", "2026-01-01T00:00:00.000Z"),
    row("contoso", "lrn_contoso", "2026-01-01T00:00:00.000Z"),
    ]);
    const now = new Date("2026-02-01T00:00:00.000Z");
    assert.equal(ageDays("2026-01-01T00:00:00.000Z", now) > 30, true);
    const tombstones = purgeExpired(memory.store, "northwind", { now });
    assert.equal(tombstones.length, 1);
    assert.deepEqual(tombstones[0].fieldNames, ["email", "transcript"]);
    assert.equal(JSON.stringify(tombstones).includes("@"), false);
    assert.equal(memory.store.listPersonal("northwind").length, 0);
    assert.equal(memory.store.listPersonal("contoso").length, 1);
    assert.equal(retentionDecision({ dataClass: "secret", ageDays: 1, published: true }), "rotate");
    assert.equal(retentionDecision({ dataClass: "public", ageDays: 400, published: true }), "keep");
    });
    test("export returns one learner inside the rows the route already scoped", () => {
    const rows = [row("northwind", "lrn_priya", "2026-03-01T00:00:00.000Z"), row("northwind", "lrn_omar", "2026-03-01T00:00:00.000Z")];
    const exported = exportPersonal(rows, "lrn_priya");
    assert.equal(exported.length, 1);
    assert.equal(exported[0].learnerId, "lrn_priya");
    });
    function row(tenantId: string, learnerId: string, createdAt: string): PersonalRow {
    return { tenantId, learnerId, email: `${learnerId}@${tenantId}.example`, transcript: "draft", createdAt };
    }
    function memoryStore(seed: PersonalRow[]) {
    const rows = [...seed];
    const tombstones: Tombstone[] = [];
    const store: PrivacyStore = {
    listPersonal: (tenantId) => rows.filter((item) => item.tenantId === tenantId),
    replacePersonal: (tenantId, next) => {
    const rest = rows.filter((item) => item.tenantId !== tenantId);
    rows.length = 0;
    rows.push(...rest, ...next);
    },
    writeTombstone: (tombstone) => tombstones.push(tombstone),
    };
    return { store, tombstones };
    }

    Run:

    bash
    npx tsc --noEmit
    node --experimental-strip-types --test src/privacy.test.ts

    The token constant exists so the assertion can prove absence. It is not a credential for any provider. The suite never calls fetch.

    Architecture Diagram

    text
    Browser session
    |
    v
    Route (Lesson 48 tenant)
    |
    +--> classifyField
    +--> tutorModelPayload --> provider adapter
    | ^
    | |
    | secret manager (value stays here)
    |
    +--> personal table (30 days)
    +--> operational trace (90 days, counts and reasons)
    |
    v
    purgeExpired --> tombstone (field names, policy version)
    |
    v
    exportPersonal for an authorized learner id

    Version pin:

    text
    privacy-retention-v1

    Subprocessor record:

    text
    model-provider
    purpose: template id or grounded answer
    payload: excerpt + question, or a stalled count
    mail-adapter
    purpose: send cohort_reminder_v1 after approval
    payload: learner ids from the enrollment port

    Real-Time Enterprise Example

    In production the API process receives SecretReader from the platform secret manager. Northwind's tutor turn stores Priya's transcript under tenantId = northwind. The provider adapter sends the excerpt and the question and attaches the key only on that outbound call. The access log line is the operational trace. A nightly job iterates tenant ids from the membership table and calls purgeExpired with now from the job clock. Tombstones land in an operational table with the same 90-day clock.

    A support lead who is allowed to export Northwind learners calls the export route. The route loads rows with the session tenant and passes them to exportPersonal. A Contoso lead's session never loads Northwind rows, because Lesson 49's query already filtered them.

    Challenge: counsel shortens personal retention to 14 days during a customer contract, a learner asks for erasure on day 2, and an incident responder wants the prompt in the log to reproduce a bug. You change PERSONAL_DAYS, you call purge with forceLearnerId, and you reproduce the bug from the excerpt fixture in Lesson 54. You do not paste the production prompt into chat. The secret handle in the incident channel is sec_model_northwind. The value stays in the manager.

    Performance Optimization

    Classification is a map lookup. Redaction is one pass over the error string you already decided to keep, and that string should be short. The purge job pages by tenant and by primary key. It does not SELECT * across tenants and then filter in process memory. A tenant with a large transcript table purges in batches of a few hundred rows so the transaction stays short and the table stays available for the tutor.

    Do not recompute retention on the read path of the lesson player. The player reads published lesson text. The clock runs on the job. Caching a personal row in a shared cache is a cross-tenant bug waiting for a missing key, so the personal read goes to the database with tenantId in the predicate.

    The provider payload is smaller because email and display name are absent. That is a token saving and a privacy control at the same time. Log volume drops when traces store counts. Cheaper logs are a side effect of the class split, and they are worth keeping when someone asks to "just log the body for a week."

    Security

    • Authentication. Export and erasure routes require a session. The package assumes the route already checked it.
    • Authorization. A learner exports their own id. A support role exports inside the tenant. The store never lists a second tenant.
    • Least privilege. The route process may read MODEL_API_KEY. The browser, the trace vendor, and the lesson player may not.
    • Validation. Handles and env names are matched to closed patterns. Unknown data fields become personal.
    • Secrets. Values stay in the reader. Tests assert the marker is absent from JSON that leaves the package.
    • Tenant isolation. purgeExpired and listPersonal take tenantId.
    • Injection. Transcripts are stored as data. They are not written into a shell command or into a trace template string without redaction.
    • OWASP. The relevant issues are sensitive data exposure, security misconfiguration of logs, and broken access control on export. The controls are classes, the reader boundary, and the tenant argument.

    Counsel still reviews subprocessors when the vendor list changes. Engineering's proof is the payload function and the fixture test.

    Common Mistakes

    1. Logging the provider client. Symptom: a token shows up in the log vendor. Cause: console.log(client) during a timeout. Fix: log handle and configured. Search the vendor for TEST_ONLY_MODEL_TOKEN after the drill, and for your real prefix after the first production deploy.
    2. Putting the email on the reminder trace. Symptom: inboxes in an analytics tool. Cause: the trace copied the mail adapter's argument. Fix: operationalTrace stores the count. Addresses stay on the approved ticket under Lesson 45's rules.
    3. Sending the profile to the model. Symptom: the provider payload contains priya@northwind.example. Cause: the route spread the whole row into the prompt. Fix: tutorModelPayload is the only builder, and its return type has two fields.
    4. A personal table with no clock. Symptom: March transcripts are readable in November. Cause: retention lived in a wiki. Fix: PERSONAL_DAYS and a nightly purgeExpired.
    5. Deleting the row and the proof. Symptom: a learner asks for confirmation and support has nothing. Cause: purge issued DELETE and wrote no tombstone. Fix: write field names and the policy version, then drop the values.
    6. Purging every tenant in one query. Symptom: a Northwind job tombstones a Contoso learner. Cause: listPersonal() had no argument. Fix: the function requires tenantId, and the job loops tenants explicitly.
    7. Defaulting unknown fields to operational. Symptom: a new note column is in every dashboard. Cause: the map used a public default. Fix: the default is personal.
    8. Keeping corrupt timestamps. Symptom: a null createdAt never ages out. Cause: NaN > 30 was treated as false. Fix: unparseable dates become infinity and purge.
    9. Committing a .env with a working key. Symptom: the key is in git history. Cause: a local demo was committed. Fix: commit .env.example with the env name and an empty value. The fixture token in the test file is the only marker, and it must not be a real key.
    10. Rotating by copying the new secret into a column. Symptom: the database is now a second secret store. Cause: rotation was implemented as an UPDATE. Fix: the handle stays, the manager rotates, and retentionDecision returns rotate.
    11. Using production transcripts as eval cases. Symptom: learner text sits in the test repository. Cause: a failure was copied out of the admin tool. Fix: Lesson 54's fixtures are written by the team from public excerpts.
    12. Treating this package as a legal sign-off. Symptom: a contract claims "GDPR compliant" because the clock is 30. Cause: a control was described as a certification. Fix: describe privacy-retention-v1 as the engineering schedule counsel approved. Link the approval in the runbook.

    Best Practices

    1. Pin privacy-retention-v1 on traces and tombstones.
    2. Keep secret values in the manager and handles in the app.
    3. Log handles and configured, and keep values out of return types that routes serialize.
    4. Match handles to sec_[a-z0-9_]+ and env names to screaming snake case.
    5. Classify with a map, and default unknown names to personal.
    6. Build provider payloads in one function whose return type is the minimized shape.
    7. Store reminder traces as counts, reasons, and tenant ids.
    8. Run redactForTrace on free-text errors even after structured logging exists.
    9. Clock personal data at 30 days and operational data at 90, until counsel changes the constants.
    10. Purge per tenant.
    11. Write tombstones with field names and without values.
    12. Treat corrupt timestamps as due.
    13. Force-purge on an authorized erasure request with the same tombstone shape.
    14. Export one learner id from rows the route already scoped to the session tenant.
    15. List subprocessors by purpose and payload, not by key or base URL.
    16. Commit .env.example names only.
    17. Use TEST_ONLY_MODEL_TOKEN in tests and assert it is absent from outputs.
    18. Keep the lesson player off the personal purge job's lock.
    19. Page large purges.
    20. Leave authentication to Lesson 48 and tenant predicates to Lesson 49.
    21. Reproduce bugs from fixtures, not from production prompts pasted into chat.
    22. Change the clock in the constant and the test together when the contract changes.
    23. Record mail and model vendors separately, since their payloads differ.

    Interview Questions & Answers

    Beginner

    1. What is the difference between a secret and personal data?
      A secret grants power to a system, such as a model key. Personal data describes a person, such as Priya's email or her tutor transcript. Both stay out of casual logs. They use different stores: the secret manager holds the key, and the tenant table holds the transcript under a 30-day clock.

    2. Why does the health check return a handle?
      Operators need to know which secret the process expected and whether it was present. sec_model_northwind plus configured: true answers that. The token would answer it too, and would then live in every log pipeline that stores health JSON.

    3. What does a tombstone contain?
      Tenant id, learner id, purge time, policy version, and the field names that were cleared. It proves the clock ran. It is not a copy of the email.

    Intermediate

    1. Why are unknown fields personal?
      New columns arrive in feature work faster than policy reviews. A personal default gives them a short clock and keeps them off the operational trace. Promoting a field is an explicit edit to FIELD_CLASS and to the tests.

    2. How do you keep the model provider from receiving the email?
      tutorModelPayload returns { excerpt, question }. The route uses that object as the provider body. A test spreads an email into the input and asserts the JSON form of the result has no @.

    3. What happens on a corrupt createdAt?
      ageDays returns infinity. Infinity is greater than 30, so purgeExpired writes a tombstone and drops the values. A bad clock must not become permanent storage.

    Senior

    1. How do you test this without a secret manager?
      Pass a SecretReader that returns TEST_ONLY_MODEL_TOKEN. Assert the health object serializes without that string. Assert redaction removes both an email and a MODEL_API_KEY= assignment. Run purgeExpired against an in-memory store with a fixed now and a second tenant that must remain.

    2. Where does Lesson 47's trace fit?
      operationalTrace is the same shape the reminder already writes, plus policyVersion. Recipient count stays a number. The approval audit in Lesson 45 remains the place for the approver and the effect id. This package does not merge those stores.

    Architect

    1. How would you roll out a shorter retention period?
      Ship the new PERSONAL_DAYS behind the policy version privacy-retention-v2 after counsel signs the schedule. Run the job in a report mode that counts rows it would purge, then enable writes. Old tombstones keep the version they were written with. You do not rewrite history to claim v2 purged a v1 row.

    2. What should a multi-region product add?
      The tenant record gains a region and a schedule id. The job loads that schedule instead of a single global 30. The class map stays global. Export and purge still take the session tenant. A region mismatch is an authorization failure in the route, before this package lists rows.

    3. How do you answer a deletion request that arrives while a model call is in flight?
      The route sets forceLearnerId and the job purges the stored row. The in-flight provider call already left with excerpt and question, which is why minimization matters before the call. You do not try to fetch the prompt back from the vendor as part of this package. Vendor retention is a subprocessor contract, tracked next to SUBPROCESSORS.

    4. What do you refuse during an incident?
      You refuse to paste production transcripts into a chat tool, to disable redaction "for an hour," and to print the provider client. You reproduce from the public excerpt fixture, you log the handle, and you keep the purge job running so the incident response does not also become a retention breach.

    Knowledge Check

    1. What problem does this capability solve?

    It gives TechLearningPro one schedule for secrets, personal fields, operational traces, and public lessons, so a debug session cannot quietly become a copy of the customer database.

    2. What alternatives exist, and when would you choose each?

    A platform secret manager is the store for keys. An application column is the store for personal fields that the product must show back to the learner before the clock. A pure log vendor is the wrong store for either. Tokenization at a payment boundary fits card data, which this product does not hold. The handle pattern fits every vendor key the tutor and the reminder use.

    3. Which data, identity, and trust boundaries matter?

    The session tenant selects the rows. The secret reader is the only edge that sees a value. The provider sees a minimized payload. Traces see counts and redacted reasons. Export sees one learner id inside an authorized route.

    4. What can fail, and how should the system respond?

    A missing secret yields configured: false and no outbound call. A bad handle throws before the reader is used. A corrupt timestamp purges. A purge writes a tombstone and retains the other tenant. Redaction still scrubs free text when a reason was built badly.

    5. How would you test quality, security, performance, and cost?

    Unit tests cover classification, redaction, the health object, the 31st day, and the untouched tenant. Security review searches the repository for committed env files and for the fixture token outside the test. The purge job is timed per tenant batch. Cost review checks that prompts do not include profile fields, because those tokens are both a privacy leak and a bill.

    Practical Exercise

    Implement packages/privacy/src/ and run the tests. Add a force purge for lrn_omar on day 2 and assert a tombstone exists while lrn_priya, created the same day and not forced, remains. Write three sentences on how the route will load the session tenant before it calls listPersonal.

    Deliverable and Rubric

    Submit the class diagram, the privacy package, the test output, the subprocessor list, and a note that counsel owns changes to the day counts.

    AreaWeight
    Conceptual accuracy and architecture20%
    Working implementation and code quality25%
    Security, privacy, and responsible AI20%
    Testing, reliability, and observability20%
    Documentation and decision rationale15%

    Production checklist:

    • Policy version is privacy-retention-v1.
    • Unknown fields classify as personal.
    • Provider payloads are excerpt and question, or a stalled count.
    • Health output has a handle and a boolean.
    • Traces store counts and redacted reasons.
    • Personal purge is per tenant and writes tombstones without values.
    • Corrupt timestamps purge.
    • Export is limited to one learner id inside the caller's rows.
    • .env.example contains names only.
    • Tests use TEST_ONLY_MODEL_TOKEN and assert its absence from outputs.

    Key Takeaways

    1. privacy-retention-v1 is the engineering schedule.
    2. Secrets are handles. Values stay in the manager.
    3. Personal data is email, name, prompt, and transcript, plus anything unnamed.
    4. Operational data is ids, reasons, and counts.
    5. Public lessons stay while they are published.
    6. The personal clock is 30 days. The operational clock is 90.
    7. Redaction is the backstop, not the design.
    8. The tutor provider receives an excerpt and a question.
    9. Tombstones list field names.
    10. Purge and export take a tenant, and export also takes one learner id.
    11. A corrupt timestamp does not preserve personal data.
    12. Subprocessors are recorded by purpose and payload.
    13. The fixture token exists to prove absence.
    14. Counsel changes the clock. Engineering changes the constant and the test together.
    15. Lesson 53 proves the clock with integration and contract tests.

    Summary

    Lesson 52 makes data handling a package with a version, a class map, and a clock. TechLearningPro can remind a cohort and answer a tutor question while the key stays a handle, the transcript stays on a 30-day timer, and the trace stays useful to on-call. The next lesson treats that package as code that must keep working when the store, the fixture, and the tenant fence are tested on purpose.

    Next Lesson Preview

    Unit, Integration and Contract Testing builds the pyramid under this policy and under the Lesson 47 reminder. You will unit-test pure decisions, integration-test a purge that touches one tenant's rows, and contract-test the enrollment fixture so a recorded stalled list cannot smuggle a Contoso id or a secret into CI.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.