Project Workshop — Semantic Document Search
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
PostgreSQL · pgvector · HNSW · FastAPI · OpenAI
Expected effort: 35–56 focused hours · Minimum meaningful tests: 12What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | window functions: ROW_NUMBER/RANK/LAG/LEAD/FIRST_VALUE produces the specified behavior inside Advanced SQL | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | PARTITION BY and OVER clause produces the specified behavior inside Advanced SQL | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | recursive CTEs for tree/hierarchy queries produces the specified behavior inside Advanced SQL | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | LATERAL joins produces the specified behavior inside Advanced SQL | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.5 | GROUPING SETS/ROLLUP/CUBE produces the specified behavior inside Advanced SQL | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | MVCC: concurrent transaction handling produces the specified behavior inside PostgreSQL internals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | VACUUM/autovacuum for bloat produces the specified behavior inside PostgreSQL internals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | WAL for crash recovery produces the specified behavior inside PostgreSQL internals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | EXPLAIN ANALYZE: reading execution plans produces the specified behavior inside PostgreSQL internals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.5 | pg_stat_statements for slow queries produces the specified behavior inside PostgreSQL internals | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | B-tree/Hash/GIN/GiST/BRIN index types produces the specified behavior inside Index types & optimization | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | partial and composite indexes produces the specified behavior inside Index types & optimization | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | index-only scans produces the specified behavior inside Index types & optimization | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | pg_stat_statements for slow query detection produces the specified behavior inside Index types & optimization | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | range/list/hash partitioning produces the specified behavior inside Partitioning & pgvector | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | partition pruning in query plans produces the specified behavior inside Partitioning & pgvector | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | pgvector: vector type + HNSW/IVFFlat indexes produces the specified behavior inside Partitioning & pgvector | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | hybrid search: cosine + ts_vector FTS produces the specified behavior inside Partitioning & pgvector | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | Read Committed/Repeatable Read/Serializable isolation produces the specified behavior inside Transactions & concurrency | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | lost update/write skew/serialization failure produces the specified behavior inside Transactions & concurrency | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | row/table/advisory locks produces the specified behavior inside Transactions & concurrency | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | deadlock prevention by stable lock ordering produces the specified behavior inside Transactions & concurrency | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.5 | SELECT FOR UPDATE SKIP LOCKED work queue produces the specified behavior inside Transactions & concurrency | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.6 | HOT updates and fillfactor produces the specified behavior inside Transactions & concurrency | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.1 | engine/session/transaction scopes produces the specified behavior inside SQLAlchemy integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.2 | text() parameterized SQL produces the specified behavior inside SQLAlchemy integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.3 | streaming results and yield_per produces the specified behavior inside SQLAlchemy integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.4 | capturing EXPLAIN plans in performance tests produces the specified behavior inside SQLAlchemy integration | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── app/3│ ├── main.py4│ ├── api/{routes.py,dependencies.py}5│ ├── domain/{models.py,services.py,errors.py}6│ ├── repositories/7│ ├── schemas/8│ ├── workers/9│ └── observability.py10├── migrations/11├── tests/{unit,integration,contract}/12├── pyproject.toml13├── Dockerfile14└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Advanced SQL | window functions: ROW_NUMBER/RANK/LAG/LEAD/FIRST_VALUE; PARTITION BY and OVER clause; recursive CTEs for tree/hierarchy queries | Demonstration plus focused tests |
| 2 | PostgreSQL internals | MVCC: concurrent transaction handling; VACUUM/autovacuum for bloat; WAL for crash recovery | Demonstration plus focused tests |
| 3 | Index types & optimization | B-tree/Hash/GIN/GiST/BRIN index types; partial and composite indexes; index-only scans | Demonstration plus focused tests |
| 4 | Partitioning & pgvector | range/list/hash partitioning; partition pruning in query plans; pgvector: vector type + HNSW/IVFFlat indexes | Demonstration plus focused tests |
| 5 | Transactions & concurrency | Read Committed/Repeatable Read/Serializable isolation; lost update/write skew/serialization failure; row/table/advisory locks | Demonstration plus focused tests |
| 6 | SQLAlchemy integration | engine/session/transaction scopes; text() parameterized SQL; streaming results and yield_per | Demonstration plus focused tests |
| 7 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
1WITH ranked AS (2 SELECT3 customer_id,4 id AS order_id,5 total,6 created_at,7 ROW_NUMBER() OVER (8 PARTITION BY customer_id9 ORDER BY created_at DESC, id DESC10 ) AS rn,11 SUM(total) OVER (12 PARTITION BY customer_id13 ORDER BY created_at, id14 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW15 ) AS running_total16 FROM orders17 WHERE created_at >= CURRENT_DATE - INTERVAL '1 year'18)19SELECT * FROM ranked WHERE rn <= 3 ORDER BY customer_id, rn;Expected result
1Returns each customer's three most recent orders plus a deterministic lifetime-in-range running total.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | WITH ranked AS ( | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 2 | SELECT | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 3 | customer_id, | Implements the next sql statement in the example's data flow. |
| 4 | id AS order_id, | Implements the next sql statement in the example's data flow. |
| 5 | total, | Implements the next sql statement in the example's data flow. |
| 6 | created_at, | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 7 | ROW_NUMBER() OVER ( | Implements the next sql statement in the example's data flow. |
| 8 | PARTITION BY customer_id | Implements the next sql statement in the example's data flow. |
| 9 | ORDER BY created_at DESC, id DESC | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 10 | ) AS rn, | Implements the next sql statement in the example's data flow. |
| 11 | SUM(total) OVER ( | Implements the next sql statement in the example's data flow. |
| 12 | PARTITION BY customer_id | Implements the next sql statement in the example's data flow. |
| 13 | ORDER BY created_at, id | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 14 | ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW | Implements the next sql statement in the example's data flow. |
| 15 | ) AS running_total | Implements the next sql statement in the example's data flow. |
| 16 | FROM orders | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 17 | WHERE created_at >= CURRENT_DATE - INTERVAL '1 year' | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 18 | ) | Implements the next sql statement in the example's data flow. |
| 19 | SELECT * FROM ranked WHERE rn <= 3 ORDER BY customer_id, rn; | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Advanced SQL | Cycles or explosive fan-out can consume unbounded work. | Bound recursion, index join keys, and inspect row estimates. |
| PostgreSQL internals | A long transaction prevents cleanup, and EXPLAIN ANALYZE executes the statement. | Use EXPLAIN (ANALYZE, BUFFERS) safely on representative data and tune autovacuum per table when needed. |
| Index types & optimization | A long transaction prevents cleanup, and EXPLAIN ANALYZE executes the statement. | Use EXPLAIN (ANALYZE, BUFFERS) safely on representative data and tune autovacuum per table when needed. |
| Partitioning & pgvector | Too many partitions raise planning cost; approximate indexes trade recall for speed. | Partition for lifecycle or proven pruning and evaluate recall/latency on real embeddings. |
| Transactions & concurrency | SKIP LOCKED is suitable for queues, not ordinary user reads; retrying the whole transaction is mandatory after serialization failure. | Express invariants with constraints or serializable/conditional writes, acquire locks in stable order, retry serialization/deadlock failures, and keep transactions short. |
| SQLAlchemy integration | An ORM session is not an authentication scope, and streaming rows is not an LLM streaming response. | Scope sessions to one unit of work, use parameterized statements, close streaming results, and capture representative EXPLAIN plans in performance tests. |
Engineering checklist for this stack
- To do: protect invariants with constraints and transactions
- To do: parameterize every value
- To do: measure representative plans and memory
- To do: bound cardinality and retention
- To do: document recovery, backup, or rebuild behavior
Test strategy
Implement at least 12 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 4 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1@pytest.mark.anyio2async def test_duplicate_request_is_idempotent(client, auth_headers):3 headers = {**auth_headers, "Idempotency-Key": "stable-1"}4 first = await client.post("/resources", json={"name": "one"}, headers=headers)5 second = await client.post("/resources", json={"name": "one"}, headers=headers)6 assert first.status_code == 2017 assert second.status_code in {200, 201}8 assert first.json()["id"] == second.json()["id"]Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?