Computing: contracts, machines and evidence

Study the four original on-site mechanism units with the preserved native lessons and quantitative investigations, then the complete Harbor maintenance case and 24-point rubric. No publisher chapter or external account is required. All practice is optional.

Unit 1: programs, abstractions and algorithmic reasoning

From a question to an operational contract

Computing begins by making a task precise enough that a result can be checked. An input domain states what information is accepted. A postcondition describes the relationship the output must bear to that input. Preconditions identify assumptions a component relies on. A failure policy describes what happens when the input is outside that domain or a resource is unavailable. For example, 'return the earliest request' requires decisions about time zones, missing timestamps and ties. Faster code cannot repair an undefined meaning of earliest.

Abstraction deliberately preserves some details and hides others. A queue interface can promise insertion at one end and removal at the other without exposing whether storage uses linked nodes or a circular array. That hidden implementation still affects capacity and performance, so the interface must state any relevant limits. Decomposition assigns responsibilities to components whose contracts fit together. If one component returns seconds and another interprets milliseconds, each can appear locally reasonable while their composition fails. A useful boundary includes representation and units as well as a function name.

An algorithm is a finite description of a procedure; a program expresses behavior through the rules of a programming language and its execution environment. Termination is a property to establish for a particular procedure and input class, not a guarantee provided by calling something an algorithm. A correct implementation must satisfy the contract, including termination where promised. The retained native lower-bound investigation supplies a full invariant argument and changed-boundary counterexample; this expansion explains the programming and representation mechanisms around that investigation.

Expressions, state and control flow

An expression computes a value. A statement directs execution, for example by assigning a value, choosing a branch or repeating work. A variable name refers to a value or storage location according to the language's rules. In Python, assignment binds a name to an object; it does not make a universal promise that a new independent object is copied. If two names refer to the same mutable list, modifying that list through one name can be visible through the other. Rebinding one name to a different list is a different operation.

Sequencing matters when operations observe or modify state. Consider the fictional starting values x=2 and y=5. Executing x=x+y followed by y=x-y yields x=7 and y=2 because the second statement sees the new x. It does not yield y=−3 by using both original values. A trace table should show the state after each statement. When a specification requires simultaneous updates, explicitly compute from the old state before replacing it. This distinction recurs in numerical methods, database updates and concurrent software.

A conditional selects behavior using a Boolean result. An if/elif/else chain chooses the first satisfied branch, so overlapping conditions make their order significant. A loop repeats a body under a control rule. A Python for loop visits items from an iterable; a while loop reevaluates its condition. A loop invariant describes what remains true at a specified point, and a decreasing nonnegative measure can help establish termination. A count of unprocessed input records is such a measure when exactly one record is consumed each iteration. It ceases to work if the loop continually adds records to the same collection.

Worked trace: a fictional filter receives integer readings [4, −1, 4, 0]. Its contract returns the sum of nonnegative readings and the count used, without changing the input. Initialize total=0 and used=0. After 4, the state is(4, 1). After−1 it remains(4, 1). After the second 4 it is(8, 2); after 0 it is(8, 3). The average is 8/3 if requested. Zero belongs in the count because the stated condition is nonnegative. For an empty input the result is(0, 0), and an average is undefined under this contract. Return an explicit absent-average state rather than dividing by zero or silently reporting a meaningful zero average.

Changed facts: readings arrive as strings and one entry is 'missing'. Comparing strings or silently skipping every parsing error changes the accepted domain. Specify parsing and missingness first. A valid redesign can return the accepted count, rejected count and reasons, but it should not pretend that three valid readings from a partially invalid file describe a fully accepted file. The original mathematical trace remains correct for its original integer domain.

Functions, scope, recursion and error boundaries

A function packages a computation behind parameters and a result contract. Local names help contain reasoning, but a function can still modify an object passed to it or access shared state. A pure calculation returns a result from its inputs without changing outside state; this makes some tests easier, but many useful systems must perform effects such as writing a file. Keep validation and calculation distinguishable from those effects so that a failed validation cannot partially apply the operation.

A function call needs an execution context containing its local state and a return point. Recursion expresses a task in terms of smaller instances and requires both a stopping case and progress toward it. For a list sum, sum_from(i) can return 0 at i=len(values), otherwise values[i]+sum_from(i+1). The termination argument uses the decreasing number of unprocessed elements. This conceptual definition is useful for reasoning; a recursive implementation also consumes call-stack space and can exceed an implementation's recursion limit. Replacing a loop with recursion does not automatically improve complexity or reliability.

An exception signals that ordinary control flow cannot continue as specified. A caller should catch errors it can meaningfully handle and preserve enough context to report a failure accurately. Catching every exception and returning 0 can conflate a genuine zero result with malformed data, an absent file or a programming defect. Cleanup and rollback are distinct responsibilities: closing a resource does not inherently undo its committed effects. Later units connect this boundary to persistent storage and transactions.

Languages and execution layers

Source code is text governed by syntax and meaning. Parsing identifies structure; name resolution and type-related rules determine whether operations make sense under a language's model. Translation can produce machine instructions or an intermediate representation. A runtime may interpret instructions, compile them ahead of execution, compile selected paths during execution or combine these approaches. 'Compiled' and 'interpreted' describe implementations and stages, rather than two mutually exclusive categories into which every language permanently falls.

Machine-level instructions operate on representations and resources supplied by an instruction-set architecture. Assembly provides symbolic forms for such operations; high-level constructs express larger abstractions such as functions and collections. CPython normally compiles Python source into implementation-specific bytecode executed by its interpreter. Those bytecode details can change across releases and are not a portable substitute for Python's language behavior. Successful parsing therefore establishes neither correct application logic nor suitability for every execution environment.

Data structures and resource tradeoffs

An array-like sequence supports positional access and ordered traversal. A linked structure follows references between nodes and offers different insertion and traversal costs. A stack removes the most recently added item; a queue removes the oldest queued item under a first-in-first-out contract. A map associates keys with values; a set represents membership without retaining a meaningful count of repeated equal elements. A tree organizes parent/child relationships; a graph permits more general connections. These are concepts and interfaces: a particular library supplies concrete semantics, capacity and cost guarantees.

Choosing a set for fictional readings [4, −1, 4, 0] produces the distinct values{4, −1, 0}. That changes the task if repeated observations must contribute separately. A map keyed by request ID similarly collapses repeated identifiers unless the design records or rejects duplicates explicitly. A hash-based implementation uses a hash to locate candidates and equality to distinguish keys that collide. Equal hash values do not prove equal keys, and expected lookup performance does not establish an unconditional worst-case bound.

Asymptotic analysis studies resource growth under a stated model. A scan can require a number of element inspections proportional to n; comparing every unordered pair requires n(n−1)/2 comparisons. For n=6 that is 15; for n=12 it is 66, not 30. A logarithm describes repeated multiplicative reduction, as developed in the preserved search model. Big-O is an upper-bound relation up to constants beyond a threshold. It is neither an exact time nor necessarily a tight bound; use a matching lower bound or Theta notation when claiming a tight growth rate. Count construction, copying, updates and memory where the real workload pays those costs.

Optional progressive practice and complete model

Question: a fictional dispatch rule returns the first urgent item in arrival order. The records are J1 ordinary, J2 urgent, J3 urgent. A developer sorts by identifier in descending order and returns the first urgent result. Explain the contract failure, supply the correct result and describe an independent check.

Open model reasoning

Model reasoning: arrival order makes J2 the correct result. Descending identifier order places J3 before J2 and solves a different problem. A reference check scans the original arrival sequence and returns the first item whose urgent flag is true, or an explicit no-match result. Test no urgent item, an urgent first item, multiple urgent items and an empty input. Keep the original sequence unchanged if that is part of the interface contract. A benchmark must compare implementations of this same contract, not reward the sorted version for returning a different urgent request.

Changed facts: the policy changes to highest numeric priority, then earliest arrival among ties. Supply J1 priority 2 at 10:00, J2 priority 3 at 10:02 and J3 priority 3 at 10:01, with all times in the same declared zone and date. Now J3 wins. The old first-urgent scan no longer suffices, while the descending-ID method still lacks a valid relation to priority and arrival. Compare the stated priority first and the stated timestamp second, and reject or explicitly handle missing values. The changed answer follows a changed specification, not evidence that the original answer was an arithmetic error.

Unit 2: information, hardware and operating-system boundaries

Information requires an encoding

A physical device distinguishes states; an encoding gives those distinctions a meaning. One bit has two possible values. With n independent bit positions, there are 2ⁿ possible patterns. That count alone does not say whether the patterns denote characters, signed numbers, instructions or colors. A byte commonly contains eight bits. A protocol can combine bytes into a larger value, but must specify order, width and interpretation. The retained native byte/endianness investigation develops those calculations fully.

Text introduces another layer. A character repertoire identifies abstract characters; an encoding maps them to code units or bytes. Unicode code points are not interchangeable with a count of displayed glyphs, and a variable-width encoding such as UTF-8 need not use one byte per character. A format must also describe field boundaries: the adjacent strings '12' and '3' become ambiguous as '123' unless length, delimiters or another framing rule distinguishes them. A delimiter requires escaping or another rule when the delimiter itself appears in the data. Compression reduces size for suitable data by exploiting structure; lossless decoding recovers the original represented data, while lossy coding deliberately discards information. Encryption serves a different purpose and does not guarantee compression or correct authorization.

Binary arithmetic follows positional weights just as decimal arithmetic does, with a different base. For a fixed-width unsigned result, the representable range is finite. A language or interface must define what happens outside that range. Signedness changes interpretation, not the physical bit pattern. Binary floating point represents a finite selection of scaled values, so a decimal quantity can be rounded on conversion and at later arithmetic steps. Display rounding is distinct from changing the underlying stored value. Choose tolerances or exact representations from the application's meaning, rather than testing approximate scientific quantities and exact account balances with one universal equality rule.

Logic, state and instruction execution

A Boolean AND operation is true only when both inputs are true; OR is true when at least one is true; NOT reverses a Boolean value. These functions can be combined into circuits. XOR is true when two Boolean inputs differ. For a one-bit addition with inputs a and b and no incoming carry, the sum bit is a XOR b and the carry bit is a AND b. For inputs 00, 01, 10, 11, the respective sum/carry outputs are 00, 10, 10, 01, where the first output position denotes the sum bit. State the order explicitly: concatenating these two outputs in the opposite order changes how the result is read.

Combinational logic computes outputs from current inputs. Sequential state elements retain information across steps, allowing a later result to depend on earlier events. A simplified processor contains registers, an arithmetic/logic unit and control machinery. Its program counter identifies an instruction position under the architecture's rules. A conceptual instruction cycle fetches an encoded instruction, decodes it, obtains operands, performs an operation and updates state. Actual processors can overlap and reorder internal work while preserving their architecture's required observable behavior. A higher clock frequency alone therefore does not determine an application's execution time.

In a load/store architecture, arithmetic operates on register values while explicit load and store instructions move data between memory and registers. This is an architectural example, not a rule for every instruction set. Consider the conceptual sequence load r1 from X; add immediate 3 to r1; store r1 to Y. If X contains 5, the resulting Y is 8 under sufficient-width integer arithmetic. That trace leaves X unchanged and says nothing about persistence after power loss. Machine instruction semantics, memory visibility and storage durability remain separate layers.

Memory hierarchy and locality

Registers, caches, main memory and persistent storage differ in capacity, access cost and lifetime. A cache keeps copies of selected data so repeated access can avoid a more expensive level. Temporal locality concerns reuse over time; spatial locality concerns nearby locations. A cache hit is useful only if the copy satisfies the consistency rules required for the operation. More cache capacity does not repair an application that accepts stale permission information or assumes a volatile write is durable.

An average-access calculation needs a precise event definition. In a fictional model, every request spends 1 time unit checking a cache; a miss then requires an additional 20 units to retrieve the value. With an 80% hit rate, average cost is 1+0.2×20=5 units per access. It is not 0.8×1+0.2×20=4.8, because the latter incorrectly omits the initial lookup cost on misses. If 'miss cost 20' had instead been explicitly defined as the total cost including lookup, then 4.8 would match that different model. A correct equation depends on the measured boundary, not merely on familiar symbols.

Processes, threads and scheduled execution

A program stored as instructions becomes a process when executed with its own execution state and managed resources. A process can contain multiple threads that share an address space while maintaining separate execution contexts such as registers and stacks. Concurrency means tasks have overlapping lifetimes; parallelism means work actually executes simultaneously on available resources. On a single execution core, interleaving can create concurrency without simultaneous instruction execution by those tasks.

The operating system schedules runnable work and arranges for blocked work to wait for events such as input completion. A context switch saves enough execution state to resume another task. A timer interrupt can return control to the kernel even when an application does not voluntarily yield. A system call is a controlled request for an operating-system service; it is not the same as an ordinary call to any function in a library. Privilege modes and controlled entry points help keep an application from simply performing arbitrary kernel operations.

Scheduling involves tradeoffs among response time, throughput and fairness. A long computation can delay a short interactive task under one policy, while very frequent switching consumes resources under another. A blocked task is not necessarily ready to run merely because it has existed for a long time. Queue length by itself cannot diagnose whether a system is CPU-bound, waiting on storage or constrained by another service. Observe the resource and interval that the claim concerns.

Address translation, files and failure boundaries

A virtual address is interpreted within an address-space context. Hardware and operating-system mechanisms translate permitted addresses to physical storage and enforce access rules. Two processes can use the same numeric virtual address for different underlying data. A page table records mappings at a page granularity; a translation cache can avoid repeating some lookup work. A page fault transfers control to the operating system to handle an absent or disallowed mapping. It does not always mean that the machine must read a page from disk: the fault can require another action, or be an invalid access that cannot be satisfied.

Memory isolation protects boundaries but does not make an application's own data structures correct. Threads sharing writable state still need appropriate synchronization. If two threads both read counter 10, each computes 11 and each writes 11, one logical increment is lost. The problem is not solved by declaring the variable shared. Use a suitable atomic operation or protected critical section under the platform's memory model; a sleep inserted between operations is not a correctness mechanism.

A file interface names and accesses persistent data through operating-system abstractions. Opening a file creates a resource that should be closed, but closing alone is not a universal promise of power-loss durability or multi-file atomicity. Buffering can postpone work, and device/operating-system guarantees matter. A successful write, a synchronized durable write and a database commit answer different questions. The retained transaction investigation adds the requirement that linked state changes and their evidence remain consistent after failure.

Original worked record and changed resource model

The fictional Harbor service handles 1000 requests. At the measured cache boundary, 800 hit and 200 miss. Each incurs the 1 unit lookup and each miss adds 20 units, giving 1000+4000=5000 units total. A proposed change raises the hit count to 950, reducing the same access cost to 1000+1000=2000 units, a 60% reduction for that component. It is not automatically a 60% reduction for the whole service. If other work consumes 5000 unchanged units, total service cost falls from 10000 to 7000, a 30% reduction under this additive model.

Changed facts: the new cache requires 4000 units to rebuild for each 1000 request batch, and that rebuilding was excluded from the reported 2000. The changed total becomes 2000+4000+5000=11000 units, exceeding the original 10000. A repeated warmed-cache benchmark would miss the actual rebuild workload. If a stale cached value also directs a request to a resource the actor cannot access, rejecting unauthorized access is required regardless of the apparent speed gain. Reconcile correctness, construction cost, reuse interval and memory cost before recommending the cache.

Optional address-space practice with full model

Question: a fictional byte-addressed machine has 256 byte pages. Process P reads virtual address 0x0314. Its virtual page 3 maps to physical frame 9. Calculate the page offset and physical byte address under the supplied mapping, and explain why process Q cannot automatically use the same address to obtain the same data.

Open model reasoning

Model: 0x0314 is 788 decimal. Dividing by 256 gives page 3 with offset 20. Frame 9 begins at 9×256=2304, so the physical address is 2324 decimal, or 0x0914. Process Q has its own mapping and permissions; the same numeric virtual address can map elsewhere or be invalid. The calculation does not itself grant read permission. Changed facts: P's page-table entry is present but marked non-readable. The translation arithmetic may still identify a frame, but the access is disallowed; it must not be reported as a successful read. A permission fault and an absent-page fault are distinct cases even when both transfer control to the operating system.

Unit 3: software structure, relational data and credible tests

Requirements become observable behavior

A requirement describes a needed behavior or constraint. 'Reliable reporting' becomes reviewable when the design states which records appear, whose permissions apply, how stale data are labeled and what happens after a partial failure. Functional requirements concern what the system does; quality constraints include response time, availability, accessibility and recoverability under specified conditions. They can conflict. A design review should expose the tradeoff rather than attach every desirable adjective to an unspecified service.

Separate responsibilities so changes have understandable boundaries. A parser converts a representation into validated values. A domain operation checks the application's rules. A storage adapter preserves the required state transition. A presentation component communicates its result. A failed operation must not be rendered as success merely because the screen loaded. Interfaces should describe input/output types, errors, mutation and timing assumptions. Encapsulation reduces callers' dependence on internal details, while excessive coupling makes one change propagate across unrelated components.

A lifecycle connects investigation, design, implementation, review, testing, release and maintenance. Iteration revises assumptions using evidence rather than treating the first requirement as permanently correct. Version control records identifiable changes and their relationships; an isolated branch can help review work before combining it with another line of development. A clean merge resolves text relationships, not every semantic conflict. Two independently passing changes can fail when combined if they alter the same behavior under incompatible assumptions. Release evidence should therefore identify the actual combined version tested.

Entities, relationships and normalization

A relational design represents entities and relationships through tables, rows, attributes and constraints. A primary key identifies a row; a foreign key constrains a reference to another table. A key should express identity rather than a convenient display label. A repeated organization name inside every job row creates an update problem when the name changes in only some rows. Store the organization identity and its current name in one organization relation, then reference that identity from jobs. This reduces a particular redundancy; it does not mean every repeated value is inherently wrong.

Normalization reasons about dependencies. If job ID determines organization ID, and organization ID determines organization name, storing all three in one table repeats an organization fact across jobs. Splitting the organization facts from job facts avoids inconsistent name updates. Relationship tables represent many-to-many associations without squeezing an arbitrary number of references into one text field. Constraints still need an explicit business interpretation: a foreign key can establish that an organization exists, but not that the current caller is allowed to read it.

NULL represents missing or inapplicable information under SQL's rules; it is not generally the same as zero or an empty string. A comparison with an unknown value does not behave like an ordinary true/false comparison with a known number. A query must intentionally handle missing values. Avoid converting missing completion time to zero and then reporting that the job completed instantly. A schema also needs units and permitted ranges, not just column names. A database can store a perfectly valid integer that the application interprets in the wrong currency or time unit.

Queries combine, filter and summarize

A selection filters rows; a projection chooses output attributes; a join combines matching rows from related sources. SQL query plans can implement these operations in different orders while preserving the language's specified result. Do not mistake an instructional processing sequence for a promise that the engine executes precisely that sequence. An index can accelerate some access patterns but also costs storage and update work. A query's actual workload determines whether a particular index is useful.

Original Harbor job record: Organizations contains(O1, North), (O2, South), (O3, West), with unique organization IDs. Jobs contains(J1, O1, open), (J2, O1, closed), (J3, O2, open), (J4, O2, open). Joining Jobs to Organizations on organization ID and filtering status=open yields(J1, North), (J3, South), (J4, South). Grouping those open rows by organization gives North 1 and South 2. West has zero jobs but disappears from an inner join; that is not evidence that West does not exist.

To report every organization including zero counts, begin with all organizations and preserve unmatched rows using a left join. Put the desired open-job restriction in the join condition or otherwise handle unmatched rows explicitly. Count the matched job identifier, which is non-NULL for real matched jobs, rather than blindly counting the synthetic joined row. Then the result is North 1, South 2, West 0. Moving status=open to a WHERE clause that rejects the NULL-extended rows can remove West again. This changes the meaning of the report even though the query remains syntactically valid.

Changed facts: an imported organization source contains a second O2 row named South-copy and the uniqueness constraint was not enforced. Each O2 job can join twice, inflating South-associated totals. DISTINCT is not a universal repair: it can remove legitimate repeated observations or hide inconsistent identity data. First establish which relation should own the authoritative organization identity, detect the duplicate and reconcile it according to evidence. The valid earlier count relied on unique organization IDs. A result table alone cannot demonstrate that this premise held.

Integrity across time and concurrent requests

A transaction groups related state changes according to a database's guarantees. Atomicity concerns all-or-nothing effects at the transaction boundary. Consistency depends on the invariants the database and application actually enforce. Isolation governs the interactions visible among concurrent operations; durability concerns persistence after a successful commit under the configured failure model. These properties do not mean that every transaction implements the right business rule or that a local commit also commits a remote service action.

The retained native ledger/version/audit investigation supplies the detailed optimistic-concurrency and operation-identity cases. A database-specific implementation must also handle errors correctly. In SQLite, for example, only one write transaction can proceed at a time, and a busy result is a real outcome to handle. Do not assume that every statement error automatically undoes every preceding statement in a manually controlled transaction. Specify rollback behavior, verify the persisted state and distinguish a new operation from a retry. These explanations concern fictional local designs; no learner or production database should be used for practice.

Test evidence must challenge the implementation

A test fixture supplies known inputs, initial state and cleanup. A test oracle supplies the expected behavior. If both the implementation and its test compute 'first arrival' by sorting identifiers, they can share the same mistake. An independent small record with explicitly stated expected output is often more revealing than a large random fixture whose expected result is another copy of the algorithm.

Unit tests isolate a component; integration tests inspect interactions such as parsing, authorization and persistence; end-to-end tests follow a visible workflow. A mock can make a dependency predictable but does not demonstrate that the actual dependency behaves that way. Code coverage measures which code was exercised under a definition; it does not prove that assertions address the important risks. Inspect failures by category, including boundary inputs, conflicting requests, missing data, authorization denials and recovery after interrupted work. A passing test suite supports the tested claims, not every possible workload.

Original failure record: a fictional asset service begins with job J7=open, revision 4 and audit entry A0. Operation K would close J7, set revision 5 and append audit entry A1. A controlled failure is injected after the job change but before A1 insertion, inside a transaction intended to include all three effects. The required recovered state is J7=open, revision 4, with A0 preserved and A1 absent. Saying 'the audit table should be empty' would incorrectly delete or ignore the pre-existing history. Inspect the reopened persisted state after failure; observing an exception alone is insufficient.

Changed facts: the job update commits through one connection before a second connection attempts A1. Failing the audit insertion can now leave J7=closed and revision 5 without A1. The single-transaction claim does not apply across those independently committed operations. Repair the transaction boundary or supply a deliberate recoverable protocol with detectable incomplete state. Repeating the same successful-path test cannot establish recovery from this altered failure boundary.

Optional test-design practice with full model

Question: a dashboard displays North 1, South 2 and omits West. A unit test compares the display against a fixture that also omits West. Does it establish the 'every organization, including zero' requirement? Supply a stronger check.

Open model reasoning

Model reasoning: no. The oracle encodes the same omission. Use the complete three-organization/four-job fixture above and require all three organization IDs, with counts 1, 2, 0 and no extra IDs. Also test an organization with only closed jobs and a dataset with no jobs. Verify both the underlying query and the rendered report, because a correct query can be followed by a presentation filter that drops zero values. Changed facts: the requirement is explicitly revised to list only organizations with at least one open job. The earlier omission is now consistent with the new scope, but label the revised report clearly and retain the version of the requirement under which the tests were evaluated.

Unit 4: networked applications, architecture and responsible operation

Layers provide different promises

A network connects endpoints through communication links and intermediate systems. Link-level communication moves frames over a particular local technology; Internet Protocol supports addressing and routing of packets across networks. A transport protocol adds its own service model between endpoints. Application protocols describe exchanges meaningful to a service. These layers separate responsibilities, but an application still experiences their combined delays and failures. An IP address is not automatically a person's verified identity, and a reachable machine does not thereby authorize access to its data.

TCP supplies an ordered byte stream with mechanisms for loss detection and retransmission. The application must still determine where one logical message ends and another begins; a single send need not correspond to a single receive. TCP delivery also does not establish that a business operation committed. UDP supplies datagrams without TCP's ordered-stream and retransmission contract; applications using it need to account for the behaviors their own purpose requires. A reliable application cannot simply infer successful remote work from the name of its transport.

DNS associates names with resource records through resolvers and name servers in a distributed hierarchy. Cached answers have lifetimes, so changing an authoritative record does not mean every client immediately observes the replacement. Successful name resolution supplies information for reaching a service, rather than proving that the service is healthy or its content current. Separate a DNS failure, connection failure, certificate failure and application error in diagnosis; they imply different next observations. A longer timeout does not repair a name that resolves to the wrong intended endpoint.

A browser request crosses several boundaries

A browser identifies a resource using a URL, resolves the relevant host as needed and establishes an appropriate connection. HTTPS adds transport security and authenticated endpoint checks under its trust model. The browser sends an HTTP request describing a method, target, fields and any content; a server sends a response with a status, fields and optional content. A proxy, cache or load balancer can participate between them. HTTP semantics persist across protocol versions, although their wire representations differ.

A GET is intended for retrieval rather than requesting a state-changing business action. POST can submit processing to a resource; its meaning depends on the service contract. An idempotent method has the same intended effect when an identical request is repeated, although responses or logging can differ. Application-level operation identifiers can also make a particular action safely recognizable as a retry. Do not infer that any arbitrary POST can be repeated without duplicate effects. The retained native ambiguous-response investigation develops the required identity and reconciliation reasoning.

HTML describes document structure, CSS contributes presentation, and JavaScript can add interaction. A server-rendered page can remain readable when client controls fail, but that fallback must accurately communicate its limits. Receiving an HTTP 200 with an application error document is not a successful user operation. Similarly, a visible disabled or hidden button is not a substitute for authorization at the protected request boundary. Validate what the API actually serves rather than only what one interface displays.

State, sessions and distributed work

Application state can reside in the browser, a service process, persistent storage or a remote provider. These locations have different lifetimes and trust properties. A session identifier can link requests to authenticated context, but a submitted role or organization field is still untrusted input unless checked against that context. Authorization should apply to the specific operation and object. Collect only data needed for a defined purpose, restrict access and plan retention and correction rather than treating every available field as useful analytics.

An asynchronous queue separates accepting work from finishing it. An acknowledged enqueue can mean only that a job was accepted into a particular queue, not that its downstream effect occurred. A worker can fail after performing an external action but before recording local completion. Retries then require operation identity and reconciliation across that boundary. A database transaction on one service does not atomically commit another provider's state. A protocol needs explicit states such as pending, committed, failed and unknown, with evidence for transitions.

Architecture is a tradeoff, not a product label

A single deployable application can keep several responsibilities in one process while preserving modular interfaces internally. Separating services can support independent scaling or ownership, but introduces more network contracts, deployment coordination and partial failure cases. A load balancer can distribute requests among replicas; replicas cannot safely rely on unshared process memory for durable shared truth. Cache invalidation, version compatibility and state ownership belong in the design before adding more instances.

Cloud computing describes a service model with properties such as on-demand access, resource pooling, elasticity and measured use. Infrastructure, platform and software services assign different responsibilities between provider and customer. Public, private and hybrid deployment arrangements describe organization and use, not automatic security levels. A virtual machine, a container and a managed service expose different boundaries; a container image packages an execution environment but does not by itself supply backups, correct authorization or a recovery plan. Using more than one cloud can reduce some dependencies while increasing identity, networking, consistency and operational complexity.

Enterprise architecture connects a technical system to organizational processes, ownership and constraints. A capability map asks what the organization needs to do; a data-flow view asks what information crosses which boundaries; a deployment view asks where components run and what fails together. A useful architecture decision records alternatives, evidence, costs, responsibilities and a reason to revisit the choice. 'Cloud-native' is not an explanation for why a particular dependency failure is tolerable.

Operation, accessibility and evidence

Logs describe selected events; metrics summarize quantities over a defined population and interval; traces can connect steps across a request path. None is a complete account of reality. A success metric must specify whether it counts accepted jobs, completed jobs, distinct operations or returned responses. Avoid putting private writing, credentials or unnecessary personal data in diagnostic records. Alert thresholds should support a defined response rather than merely generate activity.

Backups require restoration evidence: a file that exists is not automatically a usable recovery point. A release plan should identify the version, compatibility requirements, verification and reversal or repair strategy. Rolling back executable code can be unsafe when data structures have changed incompatibly, so code and data evolution must be considered together. Observe both the changed behavior and a preserved important flow after release, and report which boundary was actually tested.

Accessibility considers whether people with varied abilities can perceive, operate and understand the service. Semantic headings and labels support navigation; keyboard access should expose meaningful focus and operation; information should not depend solely on color. Accessibility, privacy and security are related design responsibilities but not interchangeable claims. A technically fluent AI answer can still be unsupported or unauthorized. The retained native retrieval model demonstrates why permissions must constrain the admitted evidence before generation, and why cited material still needs to support the particular claim.

Original distributed-work record and full model

Harbor's fictional dispatch service accepts operation K9 and returns an acceptance identifier. A worker asks a simulated provider to reserve one asset. The provider stores reservation P41 for K9, but the response is lost. The local worker marks K9=unknown. A second worker sees the unknown state. The correct next step is not to assume failure and reserve again with a new operation ID. Reconcile the provider by K9 or retry according to a provider contract that recognizes that same operation and identical validated content. Only after checking evidence should the service mark a single committed reservation.

Changed facts: the provider offers neither operation-ID lookup nor an idempotent request mechanism. The local database still cannot make the external effect exactly once through its own transaction alone. Preserve the uncertainty and use an explicit reconciliation or human review path under the application's policy. A UI that says 'failed' without evidence can induce a duplicate action; a UI that says 'complete' without evidence can induce reliance on an absent reservation. Bounded retry and honest unknown states are part of correctness.

Optional measurement practice with complete model

Question: a fictional service reports 100 accepted job requests, 90 completed unique jobs and 12 timeout responses. Can the three values describe one interval without contradiction? Can you infer that 22 jobs failed?

Open model reasoning

Model: they can coexist because acceptance, completed operations and responses count different events, and the record does not establish a one-to-one mapping. A request may time out after its job completed, and a retry may produce another response for the same operation. Subtracting 90 and 12 from 100 mixes categories without establishing their overlap. Measure operation IDs and states at a declared cutoff, distinguish retries from new work and reconcile completion evidence. Changed facts: the record explicitly states 100 distinct accepted IDs, 90 committed IDs, 7 terminal failures and 3 unknown states at the cutoff. Those categories now partition 100, but the 3 unknown cannot honestly be labeled failed or successful without additional evidence. The 12 timeout responses remain a separate observation.

Cumulative application: Harbor's maintenance dispatch record

This optional private written investigation integrates specification, representation, software/data design and network recovery. All records are fictional. Do not connect the exercise to a live provider, financial account, learner system or production database. Everything needed for the reasoning is supplied here. A paper trace is sufficient; no external chapter, account, submission or software installation is required.

Complete record and contract

Harbor maintains fictional equipment for three organizations: O1=North, O2=South, O3=West. Its service chooses one eligible job at a time, reserves an asset through a provider and records the result. Eligibility requires status=open and caller membership in the job's organization. Among eligible jobs, select highest numeric priority, then earliest arrival time, then lexicographically smallest job ID for an exact tie. All timestamps below share one date and UTC zone. Invalid or missing fields must be rejected before selection rather than silently assigned a favorable value.

The caller is verified as a member of O1 only. Current authoritative jobs are:

The prototype sorts job IDs in descending order and selects the first open job, then hides details if its organization differs from the caller's. A second prototype searches a priority-sorted cached list built yesterday. Its cache contains J11 and J12 with the same priorities/times above, but omits J10 and still lists J14 as open. The current database contains the authoritative states above. Neither prototype has a documented cache-validity check.

Representation record: the wire format sends cost in a 16-bit unsigned integer, big-endian. The two bytes for J12 are 03 84 in hexadecimal. An import incorrectly reads them as little-endian. The service's mathematical cap is 2000 cents per operation, and it must reject values above the cap. No truncation, modular wrap or conversion to floating point is part of the contract.

Report record: the organization table has the three unique IDs above. The authoritative job table has exactly the five rows above, with organization references valid. The dashboard promises every organization, including zero open jobs. It currently performs an inner join and counts all jobs, without filtering status. A second proposed query uses a left join but places status=open in a WHERE filter that rejects NULL-extended rows.

Operation record: at revision 7, asset availability is 1 and the audit contains entry A0. A request with operation ID K20 asks to reserve the selected job. The intended local transaction records pending K20 and the expected job/revision; a simulated provider accepts K20, stores reservation P90 and loses its response. The local system retains K20=unknown, leaves availability unreconciled and records the attempted request. The provider's contract allows lookup by operation ID and returns the established reservation. An operator proposes retrying with fresh ID K21 because the first request timed out.

Workload record: a batch has 1000 lookups. Each cache lookup costs 1 unit, and a miss adds 20 units. There are 800 hits before a proposed cache change and 950 after it. Other processing costs 5000 units per batch. The proposed cache must rebuild at cost 4000 units at the start of every batch. Both lookup measurements exclude rebuild. The measurements say nothing about authorization correctness or cache freshness.

Prepare a review with six parts: the correct selected job and rejected prototype assumptions; decoded cost/cap decision; corrected complete report; safe recovery state machine for K20; a complete workload comparison; and a validation plan covering independent expected results, failures and preserved behavior. Explain which observed facts justify each conclusion. Then revise the analysis under these changed facts: the caller is verified for both O1 and O2, J13's cost is missing, and the provider no longer supports operation-ID lookup or idempotent retries. All other records are unchanged. Do not fill missing values by guesswork.

Open complete model reasoning

First apply trusted scope and status, then ranking. The eligible O1 open jobs are J10, J11, J12. J11 and J12 tie on priority 3, and J12 arrived earlier, so J12 wins. J13's higher priority is irrelevant to this caller because O2 is outside the verified scope. J14 is closed. Descending identifiers implements a different order, and filtering only after selection can improperly deny a request even when an eligible alternative exists. It can also expose unauthorized data to intermediate processing. A correct service constrains the candidate population at the protected boundary and ranks the permitted records.

The cached prototype is not established as correct merely because J12 can win in its supplied subset. Stale J14 can outrank legitimate open jobs when treated as open, and omission of J10 can matter under another valid workload. A lucky matching answer does not validate the cache contract. Cache validity, invalidation/versioning, permitted scope and the authoritative status must be part of the design. An independent simple scan of current permitted records supplies a reference result for this five-row fixture.

Big-endian 03 84 means 3×256+132=900 cents, matching J12's cost and below the 2000 cap. Reading it little-endian yields 132×256+3=33795, which should be rejected under the cap rather than treated as a larger legitimate charge. Both results fit unsigned 16 bit storage, so an overflow check alone would not detect the endian mistake. Test format interpretation, range and semantic cap separately. Preserve the original bytes and a format version in diagnostic evidence; do not reinterpret them silently after the event.

The correct open-job report is North 3, South 1, West 0. The existing count-all inner join reports North 4, South 1 and omits West. The proposed left join can still omit West when the WHERE filter rejects the unmatched row. Begin with all organizations, constrain matching job rows to open status at the join boundary and count matched non-NULL job IDs. Preserve each organization ID in the result. North's closed J14 must not contribute. Verify keys and constraints as well as the displayed totals; the complete fixture includes both a zero group and an excluded closed job.

For K20, the provider record proves one accepted reservation P90 even though the caller did not receive a response. Query the established operation identity, validate that its job and other immutable request contents match, and reconcile the local state through a controlled transition to committed. Do not decrement availability again as if this were a second reservation. A retry with K21 can request a second effect because it has a new identity. Preserve A0 and record the reconciliation evidence; never rewrite the initial unknown observation as if the response had arrived normally. A local transaction must protect linked local changes, but cannot retroactively make the provider exchange part of that transaction.

A state model can distinguish validated, pending, unknown, committed and terminally rejected. Unknown is not a terminal failure. Transitions require specified evidence: provider confirmation for committed, a definite refusal for rejected, and incomplete evidence for unknown. Scope and content validation apply during retries and reconciliation as well as the first request. The record does not supply enough information to infer that every related cache, dashboard or external consumer has refreshed after the local reconciliation.

Original lookup cost is 1000+200×20=5000 units; proposed lookup cost is 1000+50×20=2000 units. Including unchanged work gives 10000 versus 7000 before rebuild. Including the actual 4000 rebuild gives 11000 for the proposed batch, 10% more than the original 10000. The 60% lookup-component reduction and 30% partial-service reduction do not justify a total-speedup claim. The measured contract also lacks freshness and permission guarantees. A faster incorrect selection is not a successful optimization.

The validation plan needs an independent reference ordering, explicit expected J12, no unauthorized candidate exposure, malformed/missing-field rejection, an exact tie case and a no-eligible-job case. Test both byte orders against fixed known bytes and cap boundaries 1999, 2000, 2001 with the documented encoding. Test the complete report at North 3/South 1/West 0, an organization with only closed jobs and a no-job database. For local transactions, inject failure between each linked change and inspect reopened persisted state, preserving A0. For provider recovery, simulate response loss after commit and require exactly one logical reservation under K20, plus conflict on changed contents under the same ID. Repeat a read after process restart to distinguish volatile cache from persisted truth. A mocked provider proves only the supplied simulation contract; a real integration would need separate authorized testing.

Open changed facts and complete revised model

The changed caller scope now admits O2, but J13's cost is missing and the contract rejects invalid/missing fields before selection. Under a policy that rejects the malformed record and continues among valid records while reporting the rejection, J12 remains the winning valid job and J13 must be identified as excluded for missing cost. Under a stricter batch-atomic validation policy, the entire selection request must fail validation instead. The original contract does not specify which of these two batch-level policies applies. State that unresolved choice rather than silently pick a convenient behavior. Neither policy permits inventing J13's cost 100 from the superseded record or treating missing as zero. Clarify the batch policy before an implementation claims a single required result.

The provider now lacks lookup and idempotent retry support. A timeout no longer has the earlier safe automatic reconciliation path. Keep the state unknown and use the service's explicit manual/provider evidence process; do not make K21 or endlessly repeat K20 on the assumption that the identifier is honored. Even if the local database is perfectly transactional, it cannot establish whether the remote reservation committed without additional evidence. The supplied local record also cannot prove absence of that reservation. This change does not alter the earlier endian calculation, complete open-job report or workload arithmetic, although the authorization population for selection changed. Name which conclusions depend on the changed assumptions.

Private self-review rubric — 24 points

Score each criterion 0–4. 4 requires correct reasoning, explicit assumptions and the relevant limitation; 3 allows a minor omission; 2 means a partly correct method with a material gap; 1 means a relevant assertion without adequate support; 0 means absent or fundamentally inconsistent work. This is optional private feedback, not a credential or externally graded performance.

  1. Specification and authorization: select J12 for the original record, exclude J13 before ranking, reject stale/descending-ID assumptions, and identify the changed batch-validation ambiguity.
  2. Representation: show 900 and 33795 from the supplied bytes, separate width/endianness/cap, and refuse to invent a missing cost.
  3. Relational evidence: derive North 3/South 1/West 0, explain inner/outer-join and NULL-filter effects, and preserve stable unique identities.
  4. Failure and operation identity: reconcile K20 to P90 without a duplicate effect, preserve A0 and unknown-state evidence, and explain why the changed provider contract removes automatic certainty.
  5. Performance: calculate 5000/2000 lookup, 10000/7000 partial totals and 11000 with rebuild; identify the 10% increase and the correctness/freshness limits.
  6. Validation and communication: supply independent expected outputs, boundary/error/concurrency/restart evidence and preserved-flow checks; distinguish a fictional simulation from actual provider execution and learner competence.

An unsupported claim of guaranteed remote exactly-once execution should be revised even when other arithmetic is correct. The aim is an explanation whose scope matches its evidence.

Optional complete fictional laboratory

Every record and model above can be studied without execution. Optionally copy the complete source into a new local file named harbor_written_models.py and run it with Python 3. It uses only the standard library and in-memory SQLite; it does not read/write files, contact networks or use accounts. The local author run passed the supplied selection, byte decoding, query, rollback and workload fixtures. This is not a provider integration, crash-durability test or independent review. The changed missing-cost case explicitly uses record rejection; a batch-atomic policy requires a different result.

"""Optional original Computing270 laboratory: fictional, in-memory fixtures only.

Run with Python3, standard library only. No network, files, accounts or real
records are read or written. Passing finite fixtures is not course acceptance,
production assurance, independent review or evidence of learner competence.
"""
from contextlib import closing
import sqlite3

JOBS = [
    ("J10", "O1", "open", 2, "09:00", 1250),
    ("J11", "O1", "open", 3, "09:02", 800),
    ("J12", "O1", "open", 3, "09:01", 900),
    ("J13", "O2", "open", 9, "08:50", 100),
    ("J14", "O1", "closed", 8, "08:40", 500),
]


def choose_job(rows, allowed_orgs):
    """Record-rejection policy; return winningID plus rejected permittedIDs.

    Each tuple is(id,org,status,priority,arrival,cost). The supplied toy format
    fixes date/timezone and HH:MM ordering. This is not a general timestamp
    parser or server authorization implementation. Scope is a trusted input
    to this model; a real service must derive it from verified identity.
    """
    valid, rejected = [], []
    for row in rows:
        job, org, status, priority, arrival, cost = row
        if org not in allowed_orgs or status != "open":
            continue
        if type(priority) is not int or type(cost) is not int or not 0 <= cost <= 2000:
            rejected.append(job)
            continue
        valid.append(row)
    if not valid:
        return None, rejected
    winner = min(valid, key=lambda row: (-row[3], row[4], row[0]))
    return winner[0], rejected


def report_fixture():
    """Return correct all-organization report and the misleading inner join."""
    with closing(sqlite3.connect(":memory:")) as db:
        db.execute("PRAGMA foreign_keys=ON")
        db.executescript("""
            CREATE TABLE org(id TEXT PRIMARY KEY, name TEXT NOT NULL);
            CREATE TABLE job(id TEXT PRIMARY KEY, org_id TEXT NOT NULL
                REFERENCES org(id), status TEXT NOT NULL);
        """)
        db.executemany("INSERT INTO org VALUES(?,?)",
                       [("O1", "North"), ("O2", "South"), ("O3", "West")])
        db.executemany("INSERT INTO job VALUES(?,?,?)", [r[:3] for r in JOBS])
        correct = db.execute("""
            SELECT o.id, COUNT(j.id)
            FROM org AS o
            LEFT JOIN job AS j ON j.org_id=o.id AND j.status='open'
            GROUP BY o.id ORDER BY o.id
        """).fetchall()
        wrong = db.execute("""
            SELECT o.id, COUNT(j.id)
            FROM org AS o JOIN job AS j ON j.org_id=o.id
            GROUP BY o.id ORDER BY o.id
        """).fetchall()
        return correct, wrong


def failure_fixture():
    """Inject failure inside one explicit transaction; preserve earlierA0."""
    with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
        db.executescript("""
            CREATE TABLE asset_job(id TEXT PRIMARY KEY,status TEXT,revision INTEGER);
            CREATE TABLE evidence(id TEXT PRIMARY KEY);
            INSERT INTO asset_job VALUES('J7','open',4);
            INSERT INTO evidence VALUES('A0');
        """)
        db.execute("BEGIN")
        try:
            db.execute("UPDATE asset_job SET status='closed',revision=5 WHERE id='J7'")
            raise RuntimeError("fictional interruption before A1 insertion")
        except RuntimeError:
            db.execute("ROLLBACK")
        return (db.execute("SELECT status,revision FROM asset_job").fetchall(),
                db.execute("SELECT id FROM evidence ORDER BY id").fetchall())


def run():
    assert choose_job(JOBS, {"O1"}) == ("J12", [])
    assert choose_job(JOBS, {"O1", "O2"}) == ("J13", [])
    changed = [r if r[0] != "J13" else (*r[:5], None) for r in JOBS]
    assert choose_job(changed, {"O1", "O2"}) == ("J12", ["J13"])
    # This explicitly implements record rejection. A batch-atomic contract
    # must reject the entire changed batch instead; it is a different policy.
    assert choose_job([], {"O1"}) == (None, [])
    assert int.from_bytes(bytes([3, 132]), "big") == 900
    assert int.from_bytes(bytes([3, 132]), "little") == 33795
    correct, wrong = report_fixture()
    assert correct == [("O1", 3), ("O2", 1), ("O3", 0)]
    assert wrong == [("O1", 4), ("O2", 1)]
    assert failure_fixture() == ([("open", 4)], [("A0",)])
    old = 1000 + 200 * 20 + 5000
    rebuilt = 1000 + 50 * 20 + 5000 + 4000
    assert (old, rebuilt) == (10000, 11000)
    print("Fictional selection/encoding/query/rollback/workload fixtures PASS.")
    print("No provider/network behavior, crash durability or learner mastery tested.")


if __name__ == "__main__":
    run()

Optional primary and author references

These references support further reading. Required explanations, records, full models, rubric and laboratory source are on this site.