Technical Writing and Documentation Questions
The craft of producing durable, reference-quality written artifacts and keeping them accurate: READMEs and quick-start guides, design docs, RFCs and technical proposals, runbooks and deployment guides, model cards, datasheets and data dictionaries, bug reports and reproducible examples, postmortem write-ups, handoff documents, pull request descriptions, code comments, release notes, experiment reports, and knowledge-base articles. Covers structure and information design, writing for a specific audience and for future readers (including plain language and accessibility), templates and style standards, docs-as-code workflows with CI checks, testing of examples and snippets, documentation review and quality checks, versioning and freshness checks on the documents you own, keeping sensitive data out of docs, and measuring whether documentation works. Architecture decision records, API reference docs, PRDs and PR/FAQs, and live presentations are covered elsewhere.
Write a script that reads table and column metadata from a Postgres database and writes one Markdown data-dictionary page per table. How do you stop the next run from overwriting descriptions people wrote by hand?
Sample Answer
Approach
Read the schema from Postgres's information_schema (the built-in catalog that describes every table and column) and write one Markdown file per table. The generated part lives between two marker comments; everything outside the markers belongs to people. On each run the script rewrites only the marked block, and inside the column table it keeps any description a person already wrote. A description is taken in this order: what is already in the page, else the database comment (COMMENT ON COLUMN), else TODO. A --check mode fails when a page is out of date, so CI (continuous integration, automated checks that run on every change) can enforce it.
Code (Python 3 with the psql client on the PATH; connection comes from the usual PGHOST, PGDATABASE and related environment variables)
#!/usr/bin/env python3
"""Write one Markdown page per table; regenerate only the marked block."""
import csv, io, pathlib, re, subprocess, sys
BEGIN, END = "<!-- BEGIN GENERATED -->", "<!-- END GENERATED -->"
BLOCK = re.compile(re.escape(BEGIN) + r".*?" + re.escape(END), re.S)
SQL = """
SELECT t.table_name, coalesce(obj_description(format('%I.%I', t.table_schema, t.table_name)::regclass, 'pg_class'), '') AS table_comment,
c.column_name, c.data_type, c.is_nullable, coalesce(c.column_default, '') AS col_default,
coalesce(col_description(format('%I.%I', t.table_schema, t.table_name)::regclass, c.ordinal_position), '') AS col_comment
FROM information_schema.tables t
JOIN information_schema.columns c USING (table_schema, table_name)
WHERE t.table_schema = :'schema' AND t.table_type = 'BASE TABLE'
ORDER BY t.table_name, c.ordinal_position;
"""
def fetch(schema):
out = subprocess.run(["psql", "-X", "--csv", "-v", "ON_ERROR_STOP=1", "-v", f"schema={schema}"],
input=SQL, capture_output=True, text=True, check=True).stdout
tables = {}
for r in csv.DictReader(io.StringIO(out)):
tables.setdefault(r["table_name"], {"comment": r["table_comment"], "cols": []})["cols"].append(r)
return tables
def hand_written(path):
"""Column name -> description already in the page (empty if no page yet)."""
if not path.exists():
return {}
found = {}
for line in path.read_text().splitlines():
cells = [c.strip() for c in line.strip().strip("|").split("|")]
if line.startswith("| `") and len(cells) == 5:
found[cells[0].strip("`")] = cells[4]
return found
def render_block(name, info, existing):
rows = ["| Column | Type | Nullable | Default | Description |", "|---|---|---|---|---|"]
for c in info["cols"]:
old = existing.get(c["column_name"], "")
desc = old if old and old != "TODO" else (c["col_comment"].replace("\n", " ") or "TODO")
rows.append(f"| `{c['column_name']}` | {c['data_type']} | {c['is_nullable']} | "
f"{c['col_default'].replace('|', '/')} | {desc.replace('|', '/')} |")
return "\n".join([BEGIN, info["comment"].replace("\n", " ") or "_No table comment._", "", *rows, END])
def main(schema, outdir, check=False):
outdir = pathlib.Path(outdir); outdir.mkdir(parents=True, exist_ok=True)
dirty = False
for name, info in fetch(schema).items():
path = outdir / (re.sub(r"[^A-Za-z0-9_.-]", "_", name) + ".md") # quoted identifiers can contain "/"
existing = hand_written(path)
for gone in existing.keys() - {c["column_name"] for c in info["cols"]}:
if existing[gone] not in ("", "TODO"):
print(f"WARN {path}: column {gone} was dropped; its hand-written description is lost from the table", file=sys.stderr)
block = render_block(name, info, existing)
if path.exists() and BLOCK.search(path.read_text()):
new = BLOCK.sub(lambda m: block, path.read_text(), count=1) # hand-written text outside markers survives
elif path.exists():
print(f"SKIP {path}: no markers, refusing to overwrite", file=sys.stderr); continue
else:
new = f"# {name}\n\n{block}\n\n## Notes\n\n_Hand-written notes go here. The generator never touches this section._\n"
if not path.exists() or path.read_text() != new:
dirty = True
print(("WOULD UPDATE " if check else "wrote ") + str(path))
if not check: path.write_text(new)
return 1 if (check and dirty) else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1], sys.argv[2], "--check" in sys.argv))
Run it (setup, then the driver)
DROP SCHEMA IF EXISTS shop CASCADE;
CREATE SCHEMA shop;
CREATE TABLE shop.orders (order_id bigint PRIMARY KEY, status text NOT NULL DEFAULT 'new', total_cents integer);
COMMENT ON TABLE shop.orders IS 'One row per customer order.';
COMMENT ON COLUMN shop.orders.status IS 'Order lifecycle state (from DB comment).';
psql -X -q -f setup.sql 2>/dev/null
rm -rf docs
python3 gen_dictionary.py shop docs
# a person edits one description and adds a note by hand
sed -i.bak 's/| `total_cents` | integer | YES | | TODO |/| `total_cents` | integer | YES | | Order total in cents, tax included. |/' docs/orders.md
printf '\nRefunds live in the refunds table.\n' >> docs/orders.md
psql -X -q -c "ALTER TABLE shop.orders ADD COLUMN coupon_code text"
python3 gen_dictionary.py shop docs --check; echo "check exit=$?"
python3 gen_dictionary.py shop docs
cat docs/orders.md
python3 gen_dictionary.py shop docs --check; echo "check exit=$?"
Output (the same on every run):
wrote docs/orders.md
WOULD UPDATE docs/orders.md
check exit=1
wrote docs/orders.md
# orders
<!-- BEGIN GENERATED -->
One row per customer order.
| Column | Type | Nullable | Default | Description |
|---|---|---|---|---|
| `order_id` | bigint | NO | | TODO |
| `status` | text | NO | 'new'::text | Order lifecycle state (from DB comment). |
| `total_cents` | integer | YES | | Order total in cents, tax included. |
| `coupon_code` | text | YES | | TODO |
<!-- END GENERATED -->
## Notes
_Hand-written notes go here. The generator never touches this section._
Refunds live in the refunds table.
check exit=0
Reading the hard parts in plain language:
re.SandBLOCK: the pattern matches everything from the BEGIN marker to the END marker;.*?means "as little as possible", andre.Slets.also match newlines so the block can span many lines.:'schema': psql substitutes the variable set with-v schema=shopinto the query as a quoted text literal, so the schema name is never pasted in by hand.format('%I.%I', schema, table)::regclass:%Iputs quotes around a name only if it needs them (spaces, capitals, odd characters, which are called quoted identifiers), and::regclassconverts that text into the table's internal object id (its row in the system tablepg_class) that the comment functions require.obj_descriptionandcol_description: built-in functions returning the comment stored with a table, or with a column given its position;ordinal_positionis that position (1 for the first column).- Set difference:
existing.keys() - {...}is the column names on the page that no longer exist in the database, that is, dropped columns. sed -i.bak 's/old/new/': simulates a person editing the file: it replaces theTODOin thetotal_centsrow with real text and keeps a.bakbackup. It only matches if the spacing is exactly as generated, which is why the demo uses the script's own output format.
The setup.sql file is the SQL block above (the DROP SCHEMA to COMMENT ON COLUMN statements); COMMENT ON COLUMN stores a description inside the database itself.
Reading it: the first run creates the page with TODO where nothing is known. After a person filled in total_cents, added a note and a new column appeared, --check reported the page as stale (exit 1); the rerun added coupon_code and kept both the hand-written description and the note; the final check passes (exit 0).
Key points
- Markers separate the two authors. Only the text between
BEGIN GENERATEDandEND GENERATEDis replaced, so a whole "Notes" section written by hand survives. - The existing page wins over the database comment, because the page is where people edit. A placeholder
TODOnever blocks a real value. - A file without markers is skipped with a warning, never overwritten.
- Safe file names: a quoted table name can contain
/, so names are sanitised. I tested a table calleda/../../evil; it becamea_.._.._evil.mdinside the output folder. - Dropped columns: their row disappears, and the script warns when the description was hand-written so the text can be rescued from Git history.
- Newlines in comments are flattened and
|in defaults is escaped so a row cannot break the Markdown table.
Complexity
One catalog query for the whole schema. Work is linear in the number of columns, plus reading and rewriting one small file per table. Memory holds the schema metadata once.
Edge cases and limits
- Partitioned tables (one big table physically split into child tables) appear as tables and so do their partitions, so exclude partitions if that is noise.
- Views and materialized views are not listed (only
BASE TABLE). - Hand-edited generated columns other than Description are overwritten by design; the table says "generated" so editors know.
- A better long-term source for descriptions is the database comment itself: people run
COMMENT ON COLUMNin a migration, and the page is regenerated. The marker approach is the fallback when they will not.
What should code comments explain and what should they leave out? Give a good and a bad example from a model training script.
Sample Answer
Direct answer
Comments should explain what the code cannot say for itself: why a choice was made, a constraint that is not visible, and a trap for the next editor. They should leave out what the code already says, history that version control (git) records, and anything you would not want public. The test is: "would a competent reader be surprised or misled without this line?"
What belongs in a comment
- Why: the reason for a choice that looks arbitrary.
- Constraints and hidden coupling: things that break if changed.
- Pointers: where the evidence or longer explanation lives.
- Warnings: ordering, leakage (information from validation data sneaking into training, which makes scores look better than they are), units.
What to leave out
- Restating the line, commented-out old code, jokes, and author or date notes (git blame, a command showing who last changed each line and when, answers those).
- Vague TODOs with no owner or ticket.
- Secrets and internal-only details.
Good and bad, from a model training script
# BAD: says what the code says
epochs = 20 # set epochs to 20
optimizer.zero_grad() # zero the gradients
# lr = 1e-3 # old value
# GOOD: says why
# Split by user_id, not by row. The same user's events in both train and
# validation would leak and make the validation score look better than reality.
train_users, val_users = split_users(users, seed=SEED)
# 3e-4 was the largest rate that kept loss stable in the sweep,
# see experiments/lr_sweep.md.
learning_rate = 3e-4
Terms in the snippet: a gradient is the signal that tells the model how to adjust, and zero_grad clears it before each step. Validation data is the held-out portion used to test the model. A seed is a fixed starting value so random choices repeat. The learning rate is how big a step the model takes when adjusting, and 3e-4 means 0.0003. A sweep is a set of runs trying several values of one setting, so "largest rate that kept loss stable" means the biggest tried value where training did not blow up.
The bad comments add noise, and the commented-out lr invites confusion about which value is live. The good ones save a future reader from re-deriving a decision, or from "fixing" the split back to per-row, which would silently inflate results. If the good comments are long, the reason belongs in a short doc that the comment links to.
Comments that help new contributors onboard
Comments explain local reasoning. The README carries the map a newcomer needs: how to set up, how to run a small smoke training run (a very short run that only proves the pipeline works end to end), where the data comes from, where decisions are recorded, and how to run the tests. Together they cut the questions a newcomer must ask a person.
Pitfalls
- Comments rot. A comment that contradicts the code (
# uses 5 foldsabovek = 10) is worse than none. Update it in the same change as the code. - If you need a comment to explain a confusing line, first try a clearer name or a small function.
Compliance asks you for documentation about how a model uses personal data. How does what you write, and the way you write it, differ from the notes you would give fellow data scientists?
Sample Answer
Direct answer
For compliance I write a factual, complete, plain-language record of what personal data goes in, why, where it flows, who can see it, how long it is kept, and what controls exist, and I leave the legal conclusion ("this is lawful") to them. For fellow data scientists I write shorthand about features, experiments and pitfalls. The facts overlap; the reader, vocabulary, completeness and burden of proof differ.
How the two documents differ
| Dimension | Notes for data scientists | Document for compliance |
|---|---|---|
| Reader question | "How does it work and what should I watch out for?" | "What personal data do you use, on what basis (the legal reason you are allowed to use it, such as consent or contract), and can you show control?" |
| Vocabulary | Feature names, embeddings (lists of numbers a model uses to represent an item), shorthand | Defined plain terms; a feature name is always translated ("cust_age_bucket: customer age group, derived from date of birth") |
| Scope | What matters for modelling | Everything touching personal data, including data you consider incidental |
| Tone | Informal, exploratory | Precise, stable, dated and versioned; no marketing words like "anonymous" unless demonstrated |
| Evidence | "I believe it is fine" | A link to the access-control setting, retention job or test that proves each claim |
What the compliance document contains
- Purpose of the model, in one paragraph.
- Personal data inventory: each field, whether it is personal data (any information relating to an identifiable person) or sensitive (special categories such as health or religion that carry stricter legal rules), its source, and why the model needs it.
- Data flow: collection, storage, training, inference, outputs, third parties.
- Retention and deletion: how long training data and logs live, and how a person's deletion request is handled, including the honest answer if a trained model cannot be edited and must wait for a retrain.
- Access and security controls.
- Model outputs and decisions: whether a person is affected by an automated decision (a decision made by software with no human in the loop, such as an automatic loan refusal), and whether a human can review it.
- Known risks and mitigations, and open questions marked as open.
Worked example (excerpt)
"Field: postcode. Personal data: yes, can help identify a person in combination with other fields. Source: customer signup form. Purpose: regional demand feature. Stored in the feature table; access limited to the modelling team group. Retention: raw postcode deleted after 24 months by a retention job (a scheduled job that deletes data past its keep-until date; see linked ticket). The 24 months is an example value; the real period comes from the company's retention policy. Reduced to a 3-character region code before training." A data scientist note would just say "region_code, dropped postcode, re-identification risk with city" (re-identification risk: region code combined with city could narrow a record down to very few people; this is different from target leakage, where a feature carries information that would not exist at prediction time).
Pseudonymised versus anonymised: pseudonymised data has names or IDs replaced by codes, but someone holding the key or other fields can still work out who it is, so it is still personal data. Anonymised data cannot be traced back to a person by anyone with reasonable effort, which is a much higher bar. Calling pseudonymised data anonymised overstates the protection and can mean the wrong legal rules are assumed.
Pitfalls
Overclaiming ("fully compliant", "anonymised" for merely pseudonymised data), leaving gaps silently, and writing a legal argument yourself. If I do not know something, I write "unknown, owner X will confirm by date Y".
A colleague hands you a README for a model repository. It has no reproducible training command and no example inputs. Rewrite its skeleton so a newcomer succeeds on the first try, and explain how you would keep the quick start from going stale.
Sample Answer
Direct answer
I would rewrite the README around one goal: a newcomer runs a tiny, real training run and one prediction within about fifteen minutes, with exact commands and example files. Then I would keep it true by making the quick start executable: the README calls a single script that CI (continuous integration, automated checks on every change) runs on every pull request, so a broken quick start fails a build instead of surprising a reader.
The rewritten skeleton
# <model-name>: one sentence on what it predicts
Status, owner, model card link.
## Quick start (about 15 minutes, CPU only)
1. Set up: `make setup` (pinned lockfile, Python version stated)
2. Get sample data: `make sample-data` (small file in data/sample/)
3. Train a tiny run: `make train-tiny` (1 epoch on 200 rows)
4. Predict: `python predict.py --input examples/input.json`
Expected output: a JSON object with fields `label` and `score`.
## Example input
examples/input.json (committed, shown in full below)
## Full training (reproducing the released model)
Config file, data snapshot id, hardware, expected metric with tolerance.
## Evaluate
`make eval` and the metric it prints, with the reference value.
## Repository layout
## Troubleshooting (top 3 errors and fixes)
## Contributing and contacts
Terms in the skeleton: a Makefile is a file that gives short names (make targets) to shell commands, so make train-tiny runs whatever command is written under that name. A lockfile lists the exact version of every package, so everyone installs the same ones (that is what "pinned" means: fixed to an exact version). An epoch is one full pass over the training data. A model card is a short document stating what the model is for, what data it learned from and its known limits. Illustrative Makefile lines:
setup: pip install -r requirements.lock
train-tiny: python train.py --config configs/tiny.yaml --epochs 1 --max-rows 200
The two sections left abstract above would be filled like this (illustrative):
## Full training
python train.py --config configs/full.yaml # data snapshot churn-2025-06-30, 1 GPU, about 2 hours
Expected metric: accuracy 0.91 +/- 0.01 on the holdout file
## Evaluate
make eval # prints "accuracy: 0.91"; reference value is stored in eval/reference.json
What the original lacked and this fixes:
- No reproducible training command: the quick start gives an exact
make train-tinyand the full run points at a committed config. - No example inputs:
examples/input.jsonis checked in and displayed, with the expected output so success is unmistakable. - Expected results: each step states what the reader should see, so they know whether it worked.
Keeping the quick start from going stale
- One source of truth for commands. The README calls
maketargets. The steps live in the Makefile, so there is nothing to copy wrongly. - A CI smoke job runs the quick start. Same commands, on a clean runner, on every pull request and on a nightly schedule (to catch drift in external dependencies).
- Pin what can drift: a lockfile for packages, a fixed Python version, a named sample-data version.
- Assert the output. The smoke test checks that
predict.pyreturns the fields promised, not merely that it exits. - Ownership rule: a change to CLI flags or config keys must update the docs in the same pull request (docs-as-code: documentation is stored beside the code and reviewed in the same process).
- A "last verified" line generated by CI, so a reader can see it is fresh.
name: quickstart-smoke
on:
pull_request:
schedule:
- cron: "0 5 * * *"
jobs:
quickstart:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: make setup && make sample-data && make train-tiny
- run: python predict.py --input examples/input.json | grep '"label"'
What the workflow file does, line by line:
on: pull_requestruns the job on every pull request (a proposed code change).schedulewithcron: "0 5 * * *"also runs it daily. The five cron fields are minute, hour, day of month, month and day of week, so this means 05:00 UTC every day.runs-on: ubuntu-lateststarts a fresh clean machine each time, so nothing from a developer's laptop can hide a problem.- The first
runexecutes the setup, sample-data and tiny-training commands. The second runs the prediction and pipes it togrep '"label"', which fails the step if that field is missing. - This is a smoke test: a quick check that the main path works at all, not a full quality check.
Worked example
Suppose someone renames --input to --path. Without the smoke job the README breaks silently and the next new hire loses an hour. With it, the pull request fails at the predict.py step, and the author fixes the README in the same change.
Trade-offs and pitfalls
- Keep the tiny run truly tiny, or the job becomes slow and people disable it.
- A green smoke test proves the quick start works, not that the model is good. Full reproduction is verified separately.
- Do not paste large outputs into the README. Show the shape and a small example.
You are writing public-facing release notes for an ML feature that changes what users see. What do you check before publishing, and how do they differ from internal notes?
Sample Answer
Direct answer
Public release notes for an ML feature must be checked for truth, tone, and exposure. Truth: they describe what users will actually see and the limits of it. Tone: they use the user's language, not the team's. Exposure: nothing internal (model names, datasets, unreleased metrics, vendor details) leaks out. Internal notes can be technical and candid, while public notes promise only what you can support.
What I check before publishing
- Matches reality: the feature flag (a switch in the code that turns a feature on or off without redeploying), rollout percentage (the share of users who currently have it), dates and versions in the note equal what is actually live.
- User-visible change, in user terms: what looks different, for whom, and when. If ordering, suggestions or scores can change for the same input, say so.
- Claims are supportable: no "smarter" or "more accurate" unless it was evaluated and you can say on what. Prefer describing behaviour ("suggestions now prefer recent items").
- Limits and failure modes: results can be wrong or vary; say what users should double-check.
- Data and privacy: what data the feature uses, whether customer data trains it, and how to opt out. Privacy or legal review signs off.
- Control and support: where to turn it off, and support has the help article before launch.
- Confidentiality sweep: strip internal model names, experiment IDs, dataset details, unreleased numbers, and anything under a partner agreement.
Public versus internal, for the same change
| Public note | Internal note | |
|---|---|---|
| Audience | Customers | Engineers, support, product |
| Language | Behaviour and benefit | Model, flag, offline evaluation link (results from testing on saved historical data) |
| Limits | Plain caveats | Known regressions (things that got worse), failure modes (the ways it can go wrong) |
| Rollback | Where to switch it off | Flag name, owner, on-call (the engineer currently responsible for responding to problems) |
Redaction example (exposure check)
Before: "Model rank-v3 (experiment EXP-4471) trained on the clicks dataset, with embeddings from a third-party vendor." After: "Search now puts items you opened recently nearer the top." The model name, experiment ID (an internal label for one test run), dataset and vendor all stay internal.
Worked example
Public: "Search now puts items you opened recently nearer the top, so the same query may show a different order than before. Turn this off under Settings, Personalised ranking. Rolling out to all accounts over the next two weeks."
Internal: "A new ranking model replaces the previous one behind the feature flag. Offline evaluation and the A/B result (a comparison of the old and new versions on live users) are linked. Known weaker on rare queries. Rollback: turn the flag off; owner is on-call."
Pitfalls
- Overclaiming ("AI-powered accuracy boost") creates support tickets and trust damage when the feature is wrong once.
- Publishing before rollout finishes makes the note false for part of your users.
Unlock Full Question Bank
Get access to all 45 Technical Writing and Documentation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.