Part II — Intermediate Development · Chapter 7 · Lesson 7 of 7 · 6 min read
Chapter 7 Checkpoint: Typed Employee-Rules Service
Checkpoint level: Intermediate
Purpose: Integrate optional annotations, inference, generics, structural protocols, Option, Result, Future, and flow-aware semantic checks into one portable employee-rules service.
Checkpoint outcomes
By completing this checkpoint, you will demonstrate that you can:
- design typed public and internal contracts;
- validate portable boundary values before trusted use;
- apply inference without hiding important contracts;
- use generics to preserve type relationships;
- define focused provider protocols;
- model absence, failure, and deferred work distinctly;
- write flow-safe branches and loops;
- run focused and project-wide semantic checks;
- test every meaningful outcome; and
- return validated portable results without leaking sensitive data.
Project scenario
An HR host submits an employee-rules request. The service validates the request, loads an employee through an approved provider, evaluates eligibility and review-routing rules, and returns a portable decision record. A valid lookup may find no employee; provider operations may fail; remote providers may complete asynchronously.
The checkpoint uses synthetic records only. Do not include real employee data, credentials, tokens, or personal identifiers.
7C.1 Required service boundary
The host request is a string-keyed portable map containing:
| Field | Contract |
|---|---|
| request_id | Nonempty string used for correlation |
| employee_id | Nonempty synthetic identifier |
| action | One of eligibility, review, or summary |
| effective_date | Validated date string in the documented format |
| context | Optional string-keyed portable map |
Reject missing, malformed, unsupported, or oversized input before invoking domain logic.
7C.2 Typed internal model
Define typed internal values for the validated request, employee record, decision, validation error, provider error, and service error. Every exported function must have parameter and return annotations.
Use precise domain names and units. Do not represent dates, percentages, status codes, or identifiers as interchangeable values merely because their runtime representation is similar.
7C.3 Provider protocol
Define a focused structural protocol conceptually requiring:
- name() -> String;
- health() -> Map; and
- load(employee_id: String) -> Future<Result<Option<Employee>, ProviderError>>.
Create conceptual local and remote provider implementations. Keep credentials, network clients, database handles, and host objects outside the protocol.
7C.4 Validation contract
The request validator returns Result<EmployeeRequest, ValidationError>. It must check required keys, portable value shapes, allowed actions, date format, collection sizes, string lengths, and unknown-field policy.
Validation errors must include stable codes and safe field context without echoing sensitive values.
7C.5 Lookup outcome
The provider load contract preserves three independent facts:
- Future: completion may be deferred.
- Result: the provider may fail.
- Option: a successful lookup may find no employee.
Do not collapse no match, provider failure, timeout, and cancellation into one null or status string.
7C.6 Required employee fields
Use synthetic employee values containing:
- employee_id;
- employment_status;
- country_code;
- job_level;
- tenure_months;
- performance_band;
- manager_assigned; and
- active_policy_codes.
Validate enumerations, ranges, and collection bounds before rule evaluation.
7C.7 Rules to implement
The service must produce one decision for the requested action:
- eligibility: determine whether the employee meets the documented tenure, status, and policy conditions;
- review: determine whether manual review is required based on synthetic job-level, manager, and policy conditions; and
- summary: return a safe, minimal summary without sensitive attributes.
Each decision includes allowed, outcome, reason_code, explanation, and evidence_codes. Keep policy thresholds as constants.
7C.8 Rule precedence
Apply rules in this order:
- invalid or inactive employee state;
- mandatory manual-review policy;
- action-specific eligibility conditions;
- ordinary allow or informational outcome.
Document overlaps and ensure the first matching rule produces a complete, internally consistent decision.
7C.9 Generic utilities
Implement at least two relationship-preserving generic utilities, such as selecting a present value with a fallback policy or transforming a list while retaining its element relationship. Do not use broad types when a type parameter preserves the contract.
Any operation required on a generic type must be justified by a focused protocol constraint.
7C.10 Flow-aware implementation requirements
- Narrow validation Results before using the request.
- Await the provider Future before handling its completed outcome.
- Handle provider error and successful absence separately.
- Access Employee members only on the present path.
- Assign every decision field on every continuing path.
- Use early returns to isolate invalid outcomes.
- Eliminate unreachable statements and incompatible branch joins.
7C.11 Deadline, cancellation, and cleanup
Apply a documented deadline to provider work. Preserve cancellation as an operational outcome rather than reporting not found. Cleanup must run exactly once for every provider attempt.
Use structured exception handling for exceptional runtime failures and Result for expected typed failures. Do not hide resource or permission failures as business decisions.
7C.12 Portable response contract
Return a string-keyed map containing:
- request_id;
- status;
- outcome;
- reason_code;
- explanation;
- evidence_codes;
- provider_name;
- attempt_count; and
- safe diagnostic information when unsuccessful.
Allowed status values are success, not_found, invalid_request, provider_error, timeout, cancelled, and internal_error. Never return a live Future, typed object, exception, host handle, or secret.
7C.13 Service invariants
- Every request produces exactly one terminal response.
- Success contains a complete decision.
- Not-found contains no fabricated employee.
- Provider failure is distinct from absence.
- Every provider attempt increments attempt_count exactly once.
- Cleanup occurs exactly once per attempt.
- No response contains sensitive input or credentials.
- Every returned value is portable.
- Semantic checks pass without unexplained suppressions.
7C.14 Required test matrix
| Case | Condition | Expected status |
|---|---|---|
| A | Valid eligible employee | success |
| B | Valid employee requiring manual review | success |
| C | Valid ineligible employee | success |
| D | Valid lookup with no match | not_found |
| E | Missing required request field | invalid_request |
| F | Unsupported action | invalid_request |
| G | Provider typed error | provider_error |
| H | Deadline exceeded | timeout |
| I | Cancellation requested | cancelled |
| J | Malformed provider output | provider_error |
Add boundary tests for every numeric threshold and overlap tests for rule precedence.
7C.15 Deliberate semantic defects
Create temporary variants demonstrating:
- an incompatible parameter argument;
- an inconsistent return path;
- a conflicting generic substitution;
- a missing protocol member;
- an unsafe Option unwrap;
- using Result as its success value;
- a missing await;
- a possibly unassigned decision field;
- unreachable code; and
- an incompatible branch join.
Record the diagnostic, root cause, minimal correction, and regression test for each.
7C.16 Validation workflow
- Format all changed source.
- Run ordinary source checks.
- Run focused type checking on changed modules.
- Run project-wide semantic analysis.
- Run the required outcome matrix.
- Run protocol conformance and boundary-validation tests.
- Verify portable responses and redaction.
- Review every suppression, warning, and excluded module.
Use the exact commands exposed by the installed v0.63 toolchain and record their exit statuses separately.
7C.17 Submission package
- architecture and trust-boundary note;
- typed request, employee, decision, and error contracts;
- provider protocol and two implementations;
- generic utility module;
- service orchestration module;
- portable request and response schemas;
- test results for cases A–J and all threshold tests;
- semantic-defect diagnostic table;
- format, source-check, type-check, and test evidence;
- security, redaction, cancellation, and cleanup statement; and
- compatibility note for future provider changes.
7C.18 Assessment rubric
| Area | Evidence of mastery |
|---|---|
| Contracts | Annotations, inference, and domain types are precise and coherent. |
| Generics | Reusable utilities preserve type relationships without broad types. |
| Protocols | Providers satisfy a focused structural contract. |
| Outcomes | Absence, failure, deferred work, timeout, and cancellation remain distinct. |
| Flow safety | Every path narrows safely, assigns required values, and returns correctly. |
| Boundaries | Inputs and outputs are validated, portable, bounded, and redacted. |
| Testing | All outcome, boundary, overlap, and defect cases are covered. |
| Workflow | Formatting, source checks, semantic checks, and tests are separate gates. |
| Security | Least privilege, deadlines, cleanup, and secret handling are explicit. |
Completion standard: Every required case passes, every invariant holds, project-wide semantic analysis succeeds, and the learner can explain the type and flow of every service outcome.
7C.19 Reflection questions
- Which contract benefited most from explicit annotations?
- Where did inference improve readability?
- Which generic relationship prevented a broad type?
- Why is the provider protocol structural?
- How is no match distinguished from provider failure?
- Why must timeout and cancellation remain separate?
- Which flow-aware diagnostic exposed the most important defect?
- What evidence proves cleanup occurs exactly once?
- Which response fields are stable enough for automated assertions?
- How would a new provider capability be added without breaking existing consumers?
Chapter 7 summary
You can now state optional type contracts, use inference deliberately, preserve relationships with generics, define structural protocols, model absence and failure explicitly, represent deferred completion, and apply flow-aware semantic analysis across a project.
Transition to Chapter 8
Chapter 8 develops standard-library mastery. The next lesson introduces the stable std namespace and compatibility conventions for dependable library use.
Checkpoint status: Ready for review.