Lab 03: Requirements and architecture
Objectives¶
Turn source/design decisions into testable requirements. Fix request and storage contracts before implementation so an assistant cannot invent fields, overwrite stale data, or confuse local review with approval.
Prerequisites¶
Complete design. Read learner docs\product\prd.md,
docs\architecture\api-contract.md, data-model.md, overview.md, and
adr-001-delivery-boundaries.md, plus specs\source-traceability.md.
These learner paths are contracts, not installed application components.
No npm acquisition is needed. Also read adr-002-python-stack.md and
python-dependency-review.md: Python stdlib HTTP/SQLite and original
HTML/CSS/JavaScript preserve these contracts without Node/React dependencies.
Bounded prompt¶
Work only in C:\src\GitHub\devopsabcs-engineering\ontario-form-practice.
Read the source ledger, experience contract and existing product/architecture
files. Limit changes to docs/product/prd.md and docs/architecture/*.md.
Specify the six endpoints and one live SQLite draft model from this lesson.
Preserve exact fields, bounded JSON/types, source identity, incomplete saves,
revision-guarded replace/review/delete, review invalidation, and original
summary race boundary. Trace each acceptance criterion to source or lab policy
and actual UI/API/DB/test targets; distinguish executed tests from future checks.
No additional address/ID/signature/payment fields, list endpoint, auth, cloud,
browser persistence, official PDF export or government integration.
Do not install or endorse blocked ODS/PDF packages. Stop after contracts;
report implementation, license and human-review prerequisites.
Steps¶
Step 1: Fix the data contract¶
The five persisted scope values are ownerType=individual, actingAs=owner,
vehicleType=passenger, replacementItem=vehiclePermit, and reason=LOST.
Only three text inputs and one checkbox are accepted:
ownerNamepermits null or at most 80 raw printable ASCII characters U+0020-U+007E. Trim ASCII spaces at both ends; empty becomes null. A present name must be 1-80 characters. Reject controls, non-ASCII, and over-limit input without truncating it. This temporary lab/font policy is not a legal-name rule.plateNumberpermits null or at most 12 raw characters. Trim ASCII edge spaces, uppercase ASCII letters, and map empty to null. A present plate matches^[A-Z0-9-]{1,12}$; reject internal spaces and other punctuation.vinpermits null or at most 17 raw characters, with the same trim/uppercase/ empty normalization. A present VIN matches^[A-Z0-9]{1,17}$. Short fictional values may pass. No official checksum or VIN certification is performed.fictionalDataConfirmedis boolean, defaults false, and must be true to review. It is not a legal declaration.
Create accepts {"data":{}}, defaulting scope, null text, and false confirmation.
Incomplete save is allowed; wrong types, unknown keys, limits, and unsupported
scenario strings fail even on save. PUT requires all nine data keys and replaces
the entire data object, not a merge. Review requires name, confirmation, and
plate OR VIN, with both allowed.
Step 2: Specify endpoints and error envelopes¶
Use API http://127.0.0.1:3001 through the browser's fixed /api development
proxy at http://127.0.0.1:5173. Bind both to loopback. These ports are defaults,
not proof that servers are running.
POST /api/draftsaccepts{"data":{}}or a data object with a subset of the nine supported keys. Return 201 andLocation, with{draft: ...}at revision 1, null reviewedRevision.GET /api/drafts/:idreturns 200 with full persisted{draft: ...}.PUT /api/drafts/:idaccepts{expectedRevision, data}with all nine data keys. Return 200 at revision r+1; clear review, even for an identical save.POST /api/drafts/:id/reviewaccepts only{expectedRevision}. Read persisted content, check accepted source and completeness, then return 200 with revision r+1 and reviewedRevision r+1. Repeated successful review also increments; replay with an old revision conflicts.GET /api/drafts/:id/summary.pdf?revision=Naccepts exactly one canonical decimal revision query. Require requested=current=reviewed revision and accepted matching source; return original PDF bytes with no DB mutation.DELETE /api/drafts/:idaccepts{expectedRevision}after UI confirmation. Commit hard deletion before 204. Missing/already deleted is 404.
IDs are server-generated canonical lowercase UUID v4, not client-assigned.
Revision is a strict JSON integer 1-2147483647; no numeric-string/boolean
coercion. Incrementing at the ceiling returns 409 REVISION_LIMIT; deletion
remains possible. Timestamps are UTC RFC 3339 with milliseconds.
JSON errors use {error:{code,message,fieldErrors:[]}}, with fixed English
messages and no raw SQL, paths, input values, or stack traces.
fieldErrors entries have field, code, and message; codes include
REQUIRED, TYPE, LIMIT, FORMAT, UNKNOWN, and UNSUPPORTED. Only
REVISION_CONFLICT includes currentRevision, never another client's data.
Distinguish 400 malformed JSON/ID/query/body, 403 origin, 404 missing record,
405 unsupported method with Allow, 409 revision/review/source/ceiling,
413 body, 414 target, 415 media/encoding, 422 validation/unsupported scenario,
431 headers, 500 export/internal, and 503 storage errors.
Missing identifiers at review map to both data.plateNumber and data.vin,
not a false requirement for both.
Step 3: Bound transport and configuration¶
Accept mutation application/json, optionally UTF-8 charset, as strict UTF-8
without compression. Bound streamed bytes at 16384 including whitespace,
even without Content-Length. Reject empty/invalid JSON, duplicate object keys,
non-object roots, unknown properties, and coercion. Reject any GET body.
Queries are forbidden except the single export revision; repeated/unknown/
invalid queries fail. Targets are capped at 2048 ASCII bytes, headers at 8192.
Low-level header failures may close the connection before JSON is possible.
All JSON/PDF responses use Cache-Control: no-store and
X-Content-Type-Options: nosniff; JSON is UTF-8. A 204 has no body/Content-Type.
Reject unexpected Host or foreign supplied Origin; allow the configured
frontend Origin and origin-less local CLI probes. No wildcard CORS, public
tunnel, cookies, or browser record persistence.
API_PORT and WEB_PORT are distinct integers 1024-65535.
PRACTICE_DB_PATH defaults to data/practice.sqlite inside LearnerRoot.
PRACTICE_TEST_DB_PATH uses distinct ignored scratch paths. Reject live/test
equality, traversal, junction/symlink escape, UNC/network/URI paths, :memory:,
and locations under web, docs/specs, static/build outputs, .git, or packages.
Invalid config stops startup, not a fallback.
Step 4: Define atomic SQLite behavior¶
Use a schema_migrations ledger and one STRICT drafts table. Map camel-case
API fields to snake-case columns, including immutable source snapshot/form/
revision/hash, content, revision, reviewed_revision, and timestamps. Derive
status from reviewed_revision; do not store a second mutable status.
Booleans store as 0/1. There is no account, address, history, upload, or PDF table.
Create api\migrations\001-drafts.sql during implementation, not this prose
step. Apply it transactionally and record version only on success. Restart
must not rerun applied DDL. New migrations are numbered files; incompatible
schema or migration failure stops startup without deleting the DB.
Enable and verify foreign_keys ON, WAL, synchronous FULL, and busy_timeout 1000.
Use bound SQL and immediate transactions for existence/revision checks and
conditional update/review/delete with WHERE id=? AND revision=?. Assert one
changed row and commit before success. Failure rolls back; locked/busy/storage
failure is 503, not a false conflict or successful save.
Step 5: Specify export and source gates¶
Attach immutable source snapshot sr-lv-006-2025-05-research-2026-11-24,
SR-LV-006, 2025/05, and the baseline hash.
Source acceptance is server-held. Pending/mismatched acceptance blocks
review/export with 409 SOURCE_REVIEW_REQUIRED; load/save/delete still work.
Tests may inject isolated accepted source state without claiming human approval.
Copy the persisted reviewed snapshot, generate/buffer an original PDF, then recheck existence, current/reviewed revision, and source before returning bytes. Discard output if edit/delete/drift occurred before that final check. Do not hold a SQLite write lock during generation/streaming. Edits after the final check cannot recall authorized in-flight bytes.
Output is 1-4 Letter pages, at most 1 MiB, with wrapping and no clipping.
Include title, exact training disclaimer, draft ID/revisions, source snapshot/
form/revision/hash/link, generated UTC time, fixed scope, confirmation, name,
and provided identifiers. Use "Not provided" for absent identifiers.
No official template or external fetch; no server PDF retention.
Generation/limit failure returns JSON 500 EXPORT_FAILED before PDF headers.
Keep HTML review equivalent. The current reviewed hash lock selects ReportLab
5.1.0 as generator, pypdf 7.1.1 as independent test parser, Pillow 13.0.0 and
charset-normalizer 3.5.2. It was installed through the corporate Python index
on Python 3.13.14 Windows x64, using SQLite 3.50.4. Original CSS follows public
ODS guidance without official assets. Human visual/PDF accessibility review
and live source acceptance remain pending; tests use isolated synthetic acceptance.
Validation¶
Check authored contracts without installing anything:
Set-Location C:\src\GitHub\devopsabcs-engineering\ontario-form-practice
$files = @(
'docs\product\prd.md',
'docs\architecture\api-contract.md',
'docs\architecture\data-model.md',
'docs\architecture\overview.md',
'docs\architecture\adr-001-delivery-boundaries.md'
)
foreach ($file in $files) {
if (!(Test-Path $file)) { throw "Missing contract: $file" }
if ((Get-Item $file).Length -eq 0) { throw "Empty contract: $file" }
}
git --no-pager diff -- docs
Manually trace every PRD acceptance criterion to UI/API/DB/test targets. Compare the actual 18 backend and 10 proxy tests with required default/incomplete, plate-only/VIN-only, stale/race, restart/storage, source-gate, PDF/parser, deletion, and accessibility tests. File presence is not runtime acceptance; browser/manual outcomes remain unexecuted.
Expected observable results¶
Contracts agree on fields, endpoints, state transitions, limits, errors, source gates, and local responsibilities. No test is labelled passed without execution. The design cannot require both identifiers, add private fields, or route the database to Pages.
Troubleshooting¶
If contracts disagree, resolve them before code. A requirement such as "works on mobile" needs named widths, zoom, focus, and download checks. If an assistant selects a blocked package or adds auth/cloud resources, reject that expansion. Do not use passing prose checks to bypass installation gates.
Costs¶
Specification/AI usage is unmeasured. Record actual usage; no cloud cost estimate or invented credit total is supplied.
Knowledge checks¶
- What happens to reviewedRevision after an unchanged PUT?
- Why must export recheck the row after buffering PDF bytes?
- Why should a storage lookup failure be 503 rather than 404?
Previous: Design. Next: Build in slices.