CS 220 — Web Applications, SQL and Software Engineering — Reasoning and Practice

Full teaching sequence and cumulative subject work

Exercise a real HTTP route and its database boundary — primary material, constructed-response tasks, complete worked model and changed-case examination →

Use this workbook with the full assigned readings. Work independently, then compare each explained solution. Practice and projects are voluntary. Cases and datasets are fictional unless a primary passage is explicitly named.

HTTP is a trust boundary, not a form submission guarantee

A browser form is a client convenience. A caller can send a request without using that form, alter hidden fields or repeat a submission. The server must establish identity, permission and domain validity independently. Distinguish malformed input, unauthenticated requests, unauthorized object access and conflicts; they require different handling even if all must avoid exposing private details.

Accessibility is also part of the interface contract. A visual caption is not necessarily a programmatic label. Associate labels and controls, identify errors in text, and preserve usable focus after errors. Client validation can improve that experience while server validation remains authoritative.

Worked problem

An order form contains a hidden owner_id and min=0 on hours. A signed-in customer changes owner_id to another customer and sends hours=−3. Design the acceptance boundary.

Trace the complete solution
  1. Resolve the customer from a verified server session. Do not adopt the body owner_id as authority.

  2. Validate hours against the server’s type and range contract. A client-side minimum cannot establish that this request satisfies it.

  3. Reject the request before inserting a row. Return an understandable error without revealing another customer’s records.

  4. On the form, connect the error to the hours control and retain the submitted non-sensitive values. Test a raw HTTP request as well as the browser path.

Independent transfer problem

A valid request is repeated after the browser loses the response. Explain how to avoid accidentally creating two orders while preserving a legitimate second order.

Compare the reasoning and result

Use a stable submission identifier with a uniqueness constraint and a stored payload fingerprint. An identical retry returns the original result. A conflicting payload under the same identifier is rejected. A legitimate new order receives a new identifier. Disabling the submit button alone cannot protect against network retries or multiple clients.

Open the unit and assigned readings →

Asynchronous rendering and stale responses

A user can initiate request B while request A is still in flight. Network completion order need not match initiation order. Rendering whichever response arrives last can display stale state. Track the current request generation, and make success, error and loading transitions conditional on that generation. Cancellation can save work, but checking relevance is still useful because completion and cancellation can race.

Treat returned strings as data. textContent displays characters; inserting untrusted HTML can change document structure and introduce executable content in unsafe contexts. A valid JSON shape does not prove that an answer belongs to the currently selected customer.

Worked problem

The user selects customer A, then B. B returns first with five orders; A returns later with two. Trace the correct UI state, including the old request’s error handler.

Trace the complete solution
  1. Assign generation 1 to A and generation 2 to B. The current generation is 2.

  2. B can render five orders and clear its loading state because its generation is current.

  3. A’s success must not replace B’s list. Likewise, A’s later failure must not overwrite B’s success with an error.

  4. Verify the response object and render order descriptions as text. Keep selection identity, request identity and displayed data aligned.

Independent transfer problem

B returns an empty list while A is still running. What should appear, and why should an empty array not be treated as a fetch failure?

Compare the reasoning and result

Render a successful empty state for B, not A’s previous data and not a network error. An empty collection is a legitimate result under the API contract. Ignore A when it completes. Test empty, malformed, denied and failed responses separately so their distinct meanings remain visible.

Open the unit and assigned readings →

Relational grain, joins and aggregation

A relational schema requires a declared grain: one row per order, order line, payment or customer. Joining two one-to-many relationships can multiply rows. SUM over the joined result may then double count perfectly valid stored amounts. Aggregate each child relation to the intended parent grain before joining, or use a query whose grouping matches the business question.

Keys identify entities and foreign keys describe relationships, while constraints enforce only the rules actually declared and enabled. A correctly formatted foreign key does not establish authorization. Query correctness and permission checking need separate evidence.

Worked problem

Order 10 has two line amounts, 300 and 700 cents, and three payment records. A join of order, lines and payments reports a line sum of 3000. Explain and repair it.

Trace the complete solution
  1. Each of the two lines appears once for each of three payments, producing six rows. The line total is repeated three times.

  2. The true line amount is 300+700=1000 cents. SUM(DISTINCT amount) is not a general repair because two legitimate lines could have equal prices.

  3. Aggregate lines by order_id and payments by order_id independently, then join those summaries to orders.

  4. Test with duplicate-valued lines, no payments and no matching child rows. Choose explicit NULL-to-zero behavior for report totals.

Independent transfer problem

Two order lines are both 500 cents and there are two payments. Why does SUM(DISTINCT line_amount) still fail?

Compare the reasoning and result

The actual line total is 1000, but DISTINCT collapses the two equal 500 values and returns 500. Distinct values are not distinct line identities. Group the actual line rows before joining the payment summary; test the join’s cardinality rather than treating DISTINCT as a universal correction.

Open the unit and assigned readings →

Transactions and object-level authorization

Parameterization prevents submitted values from being interpreted as query syntax. It does not decide whether the requester may access the selected row. Constrain data operations by a trusted principal or by a verified permission relation. Prefer one bounded operation over a check followed by an unconstrained action that can race with changes.

A transaction groups database effects, but its isolation level and constraints determine which concurrent histories are allowed. A read-check-write sequence can oversell a resource if two workers both observe the same availability. Make the invariant enforceable at the update or constraint boundary.

Worked problem

Inventory is 1. Two transactions each read 1, approve one sale, and write 0. Both report success. Give an update that makes the final remaining inventory meaningful.

Trace the complete solution
  1. The application authorized two sales from one unit even though the stored count ends at zero. The final value conceals the lost coordination.

  2. Use an atomic conditional decrement such as UPDATE inventory SET quantity=quantity−1 WHERE id=? AND quantity>=1, within the sale transaction.

  3. Require exactly one affected row before recording success. If no row changes, report unavailability and do not create a successful sale.

  4. Rollback the decrement if the required local sale record cannot be committed. External payment still needs a separately coordinated workflow and retry policy.

Independent transfer problem

A parameterized order lookup filters only id. A user guesses another customer’s valid id. What additional condition is needed?

Compare the reasoning and result

Scope the lookup or update to the verified customer, such as id=? AND customer_id=?, or a verified role/permission join. Derive the identity from trusted authentication, not a client field. Parameterization remains necessary but does not supply object-level authorization.

Open the unit and assigned readings →

Integration tests and reversible delivery

Unit tests can establish a function’s behavior while the deployed route never calls it. Integration tests cross the actual boundary: authentication, routing, validation, persistence and serialization. A useful negative test attempts an operation as the wrong user and verifies both the response and the absence of data changes.

Deployment includes schema evolution. An application rollback can fail if a migration removed a column the previous version still requires. Expand-and-contract changes keep old and new application versions compatible during transition. Backups and restoration tests answer a different question from whether a migration script exits successfully.

Worked problem

Version 2 renames customer_name to display_name by deleting the old column immediately. Version 1 remains on one running worker. Explain the failure and a safer sequence.

Trace the complete solution
  1. The old worker can still query customer_name and fail after the migration. Rolling back application code alone does not restore the column.

  2. First add display_name without removing customer_name. Backfill and use a documented compatibility period with synchronized writes or a clear authoritative field.

  3. Deploy code that reads the new field with the required transition fallback. Verify old/new behavior and data reconciliation.

  4. Remove the old field only after all consumers have migrated and rollback requirements are resolved. Test recovery on a disposable copy first.

Independent transfer problem

A unit authorization test passes, but the endpoint accepts role=admin from submitted JSON. Design the integration test that exposes it.

Compare the reasoning and result

Authenticate as an ordinary customer, submit role=admin with a request targeting another customer’s order, and verify denial plus no database change. Then verify the permitted operation on the customer’s own order. The test must call the real route so a correct helper cannot conceal an untrusted role source.

Open the unit and assigned readings →

Caching, representation and recovery

A cache stores representations under keys. If two users request the same URL but receive private data, a shared cache keyed only by URL can cross the privacy boundary. Correctness therefore depends on cache policy, key design and authentication handling at every layer. A route returning private content should not rely on a visual sign-in screen to protect a previously cached response.

A deployment plan also needs operational evidence: detect failure, identify the affected version and recover consistently. A successful health response may prove only that a process is alive. Include a readiness check that exercises essential dependencies without exposing private data.

Worked problem

Customer A loads /orders and a proxy caches the body publicly for ten minutes. Customer B opens the same URL. Explain the risk and a verification procedure.

Trace the complete solution
  1. The proxy may serve A’s body before the origin checks B’s identity. Origin authorization cannot repair a response already returned from an unsafe shared cache.

  2. For the private response use an appropriate private/no-store policy and configure the shared layer consistently. Do not infer that one header controls every intermediary.

  3. Test with two authenticated accounts and separate sessions, verifying bodies and actual response headers through the public deployment.

  4. Invalidate unsafe cached objects if they existed. A future policy change alone may not remove content already retained.

Independent transfer problem

The homepage is healthy while every order request fails because the database is unavailable. What does the homepage check establish?

Compare the reasoning and result

It establishes that the homepage can respond, not that the order workflow is ready. Add a bounded dependency/readiness check and a real synthetic order-read scenario using fictional data. Distinguish liveness from readiness, avoid logging credentials, and define rollback or degraded behavior when persistence is unavailable.

Open the unit and assigned readings →

Integrated project

Build a fictional work-order application with accessible forms, authenticated customer ownership, line items, payments and inventory. Include raw HTTP bypass tests, duplicate-submission behavior, independent line/payment summaries, concurrent inventory handling, and a reversible schema migration. Supply a two-account cache-isolation test and a recovery plan.

Evidence and evaluation criteria

  1. Accessible labels and error behavior plus authoritative server validation.
  2. Ownership derived from verified identity, tested with a hostile body and another customer’s object ID.
  3. Correct relational grain with duplicate-valued line items and multiple payments.
  4. Atomic stock mutation and documented coordination of external effects.
  5. Route-level tests demonstrating persistence is unchanged after rejection.
  6. A compatible migration sequence, deployed cache checks and dependency-readiness evidence.
Worked project approach and limitations

Start with one inventory unit and two competing requests; only one conditional decrement may authorize success. For an order with two 500-cent lines and three payments, aggregate the lines to 1000 before joining the payment summary. An ordinary customer supplying role=admin must still be denied access to another customer’s row. Repeat an identical submission ID without creating another order, but reject an altered payload under that ID. Verify A and B receive only their own data through the public cache path. Demonstrate migration and rollback on disposable data. The Python relational reference supports database reasoning; completing this project also requires actual HTTP handlers and browser behavior, which a database-only demonstration cannot establish.

Cumulative assessment

These are new situations. Explain your choice before opening the feedback.

Problem 1

A hidden form field sets owner_id. Which identity should authorize an insert?

  1. The verified server principal
  2. Whatever owner_id the browser sends
  3. The first customer in the database
Answer and reasoning for every option

Best answer: A

  1. Correct. Submitted hidden fields remain client-controlled.
  2. Incorrect. Hidden is not trusted.
  3. Incorrect. That is unrelated to the requester.

Problem 2

A second click is a legitimate new order, but an identical network retry is not. What distinguishes them?

  1. Equal order descriptions alone
  2. A disabled button alone
  3. A stable operation ID with explicit retry semantics
Answer and reasoning for every option

Best answer: C

  1. Incorrect. Legitimate orders can have equal descriptions.
  2. Incorrect. Requests can repeat outside the button.
  3. Correct. Identity separates the same operation from a new one.

Problem 3

An older request fails after the current request succeeds. Which UI transition is correct?

  1. Erase the current selection
  2. Ignore the obsolete failure for the current view
  3. Replace success with the old error
Answer and reasoning for every option

Best answer: B

  1. Incorrect. The user did not request that change.
  2. Correct. Its generation no longer owns the displayed state.
  3. Incorrect. That associates the wrong request with the view.

Problem 4

A successful API response is an empty order array. What should the interface show?

  1. A successful empty state
  2. A JSON parsing error
  3. The previous customer’s orders
Answer and reasoning for every option

Best answer: A

  1. Correct. No matching orders is distinct from a failed request.
  2. Incorrect. An empty array can be valid JSON and valid domain output.
  3. Incorrect. That displays stale and potentially private data.

Problem 5

Two equal-price line items join three payment rows. Why is SUM(DISTINCT price) unsafe?

  1. DISTINCT always reconstructs business grain
  2. The database cannot add integers
  3. It can collapse legitimate distinct line items
Answer and reasoning for every option

Best answer: C

  1. Incorrect. It cannot know which equal values are separate transactions.
  2. Incorrect. The problem is multiplicity, not arithmetic.
  3. Correct. Value equality is not row identity.

Problem 6

A query uses parameters but omits customer ownership. What remains possible?

  1. Authorization is already guaranteed
  2. Unauthorized access using a valid guessed ID
  3. Every SQL injection necessarily succeeds
Answer and reasoning for every option

Best answer: B

  1. Incorrect. No identity relationship has been checked.
  2. Correct. Parameters protect syntax, not permission.
  3. Incorrect. Parameterization still serves its own purpose.

Problem 7

Two buyers compete for one unit. Which database result should authorize a sale?

  1. A successful conditional decrement affecting one row
  2. An earlier read showing one unit
  3. A client checkbox confirming availability
Answer and reasoning for every option

Best answer: A

  1. Correct. The capacity invariant is checked at mutation time.
  2. Incorrect. Another transaction may act after that read.
  3. Incorrect. Clients cannot establish concurrent inventory truth.

Problem 8

A route ignores a correct validation helper. Which test finds the defect?

  1. Only another helper unit test
  2. A screenshot of the form
  3. A request through the actual route with invalid input
Answer and reasoning for every option

Best answer: C

  1. Incorrect. That can pass while the route remains disconnected.
  2. Incorrect. The form does not exercise the bypassed server path.
  3. Correct. The route’s connection to validation must be exercised.

Problem 9

A migration removes a column used by the previous version. What risk remains during rollback?

  1. Only typography changes
  2. The old application may no longer match the schema
  3. No risk because version numbers decrease
Answer and reasoning for every option

Best answer: B

  1. Incorrect. The failure concerns data access.
  2. Correct. Code rollback alone does not restore deleted structure.
  3. Incorrect. Numbers do not restore compatibility.

Problem 10

Private responses share one public URL. What should be tested?

  1. Cross-user bodies and cache behavior through the deployed layers
  2. Only whether the sign-in button is visible
  3. Only whether the HTML has a title
Answer and reasoning for every option

Best answer: A

  1. Correct. A shared cache can bypass the origin on a hit.
  2. Incorrect. Visual state does not establish cache isolation.
  3. Incorrect. Titles do not protect representations.

Problem 11

The server returns an order description containing <script> as text data. Which rendering boundary is appropriate?

  1. Insert the string as arbitrary HTML
  2. Trust it because JSON parsed
  3. A text node or textContent
Answer and reasoning for every option

Best answer: C

  1. Incorrect. That changes the trust boundary.
  2. Incorrect. Syntactic JSON validity is not content safety.
  3. Correct. It displays the characters without treating them as markup.

Problem 12

A health page works while persistence is down. What is established?

  1. Backups have been restored
  2. That page responds; dependency readiness remains unproven
  3. All user workflows work
Answer and reasoning for every option

Best answer: B

  1. Incorrect. A page response is not a restoration test.
  2. Correct. Liveness and full workflow readiness are different claims.
  3. Incorrect. The failed dependency contradicts that inference.

Assigned sources