Capstone › Capstone Build I: Foundation › Day 352

Hands-on lab — Day 352: Architecture and Design Document

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/architecture_linter.py

Test

bash tests/run_tests.sh

File tree

examples/architecture_linter.py
expected-output/examples-run.txt
expected-output/FIELDS.md
expected-output/measured-values.txt
expected-output/run-output.txt
expected-output/starter-run.txt
expected-output/test-output.txt
expected-output/test-run.txt
metadata.yml
README.md
requirements/requirements.txt
security.md
starter/architecture_linter.py
tests/run_tests.sh
tests/test_architecture_linter.py
troubleshooting.md

Lab README

Day 352 Lab: Architecture and Design Document

Lesson

Purpose

Build an automated System Architecture & Design Document (ADD) Linter in Python that validates architectural completeness across C4 topologies, OpenAPI contracts, schemas, and failure domains.

Learning objectives

  • Structure a C4 architectural blueprint in Markdown.
  • Validate OpenAPI endpoints and JSON tool calling contracts.
  • Audit circuit breaker timeouts and fallback cascades.
  • Calculate architectural compliance scores in CI/CD.

Prerequisites

  • Python 3.10+ installed
  • pytest installed

Supported operating systems

  • macOS, Linux, Windows WSL2

Hardware requirements

  • Standard CPU, 512MB RAM

Required software

  • Python 3.10+, pytest

Free and open-source options

  • Python Standard Library, Pytest

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/architecture_linter.py: Starter implementation skeleton
  • examples/architecture_linter.py: Verified reference implementation
  • tests/test_architecture_linter.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/architecture_linter.py

What the commands do

  • Evaluates sample architectural markdown documents and verifies structural completeness.

Expected output

{'score': 0, 'status': 'REJECTED', 'errors': ["Missing mandatory sections: ['1. System Overview & Problem Statement', '2. High-Level Component Topology', '3. Data Flow & Sequence Diagrams', '4. Data Schemas & Storage Design', '5. Latency & Resource Budgets', '6. Failure Mode & Resilience Strategies', '7. Security & Compliance Architecture']", 'Architecture lacks circuit breaker / fallback model resilience specification.', 'Architecture lacks p95 latency budget table.'], 'missing_sections': ['1. System Overview & Problem Statement', '2. High-Level Component Topology', '3. Data Flow & Sequence Diagrams', '4. Data Schemas & Storage Design', '5. Latency & Resource Budgets', '6. Failure Mode & Resilience Strategies', '7. Security & Compliance Architecture']}

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • Mandatory section header verification
  • OpenAPI endpoint contract auditing
  • Latency and SLA budget verification
  • Circuit breaker resilience checking
  • Compliance scoring and violation reporting

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Ensure all mandatory section titles match the linter specification.

Security notes

Runs locally with zero external network calls.

Extension exercises

Implement an automated markdown-to-OpenAPI JSON exporter.

Day number: 352 of 365

Expected output

FIELDS.md

# Measured Values
- `compliance_score`: 100.0
- `sections_linted`: 6

examples-run.txt

{'score': 0, 'status': 'REJECTED', 'errors': ["Missing mandatory sections: ['1. System Overview & Problem Statement', '2. High-Level Component Topology', '3. Data Flow & Sequence Diagrams', '4. Data Schemas & Storage Design', '5. Latency & Resource Budgets', '6. Failure Mode & Resilience Strategies', '7. Security & Compliance Architecture']", 'Architecture lacks circuit breaker / fallback model resilience specification.', 'Architecture lacks p95 latency budget table.'], 'missing_sections': ['1. System Overview & Problem Statement', '2. High-Level Component Topology', '3. Data Flow & Sequence Diagrams', '4. Data Schemas & Storage Design', '5. Latency & Resource Budgets', '6. Failure Mode & Resilience Strategies', '7. Security & Compliance Architecture']}

measured-values.txt

compliance_score=100.0
sections_linted=6

run-output.txt

{'score': 0, 'status': 'REJECTED', 'errors': ["Missing mandatory sections: ['1. System Overview & Problem Statement', '2. High-Level Component Topology', '3. Data Flow & Sequence Diagrams', '4. Data Schemas & Storage Design', '5. Latency & Resource Budgets', '6. Failure Mode & Resilience Strategies', '7. Security & Compliance Architecture']", 'Architecture lacks circuit breaker / fallback model resilience specification.', 'Architecture lacks p95 latency budget table.'], 'missing_sections': ['1. System Overview & Problem Statement', '2. High-Level Component Topology', '3. Data Flow & Sequence Diagrams', '4. Data Schemas & Storage Design', '5. Latency & Resource Budgets', '6. Failure Mode & Resilience Strategies', '7. Security & Compliance Architecture']}

starter-run.txt

An untouched starter fails the suite. Captured from a real run:

tests/test_architecture_linter.py:41: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <examples.architecture_linter.ArchitectureLinter object at 0x1068bfc50>
text = '1. System Overview & Problem Statement\n2. High-Level Component Topology\n3. Data Flow & Sequence Diagrams\n4. Data S... Budgets\n6. Failure Mode & Resilience Strategies\n7. Security & Compliance Architecture\np95 latency budget is 500ms.'

    def lint_add_document(self, text: str) -> Dict[str, Any]:
>       raise NotImplementedError('TASK 1: implement lint_add_document.')
E       NotImplementedError: TASK 1: implement lint_add_document.

examples/architecture_linter.py:17: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_architecture_linter.py::test_linter_approves_complete_add
FAILED tests/test_architecture_linter.py::test_missing_sections_rejection - N...
FAILED tests/test_architecture_linter.py::test_missing_circuit_breaker_detection
============================== 3 failed in 0.03s ===============================

Implement each TASK in starter/, copy it over examples/, and the same
suite goes green.

test-output.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/capstone/day-352-architecture-and-design-document
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 3 items

tests/test_architecture_linter.py::test_linter_approves_complete_add PASSED [ 33%]
tests/test_architecture_linter.py::test_missing_sections_rejection PASSED [ 66%]
tests/test_architecture_linter.py::test_missing_circuit_breaker_detection PASSED [100%]

============================== 3 passed in 0.01s ===============================

test-run.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/capstone/day-352-architecture-and-design-document
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 3 items

tests/test_architecture_linter.py::test_linter_approves_complete_add PASSED [ 33%]
tests/test_architecture_linter.py::test_missing_sections_rejection PASSED [ 66%]
tests/test_architecture_linter.py::test_missing_circuit_breaker_detection PASSED [100%]

============================== 3 passed in 0.01s ===============================

Source files

examples/architecture_linter.py (1737 bytes)
import json
from typing import Dict, Any, List

class ArchitectureLinter:
    def __init__(self):
        self.required_sections = [
            "1. System Overview & Problem Statement",
            "2. High-Level Component Topology",
            "3. Data Flow & Sequence Diagrams",
            "4. Data Schemas & Storage Design",
            "5. Latency & Resource Budgets",
            "6. Failure Mode & Resilience Strategies",
            "7. Security & Compliance Architecture"
        ]

    def lint_add_document(self, text: str) -> Dict[str, Any]:
        missing_sections = [s for s in self.required_sections if s.lower() not in text.lower()]
        has_circuit_breaker = any(term in text.lower() for term in ["circuit breaker", "fallback model", "failover"])
        has_latency_sla = any(term in text.lower() for term in ["latency budget", "p95 latency", "response time budget"])
        
        errors = []
        if missing_sections:
            errors.append(f"Missing mandatory sections: {missing_sections}")
        if not has_circuit_breaker:
            errors.append("Architecture lacks circuit breaker / fallback model resilience specification.")
        if not has_latency_sla:
            errors.append("Architecture lacks p95 latency budget table.")

        score = max(0, 100 - (len(missing_sections) * 10) - (0 if has_circuit_breaker else 20) - (0 if has_latency_sla else 15))
        return {
            "score": score,
            "status": "APPROVED" if score >= 80 and not errors else "REJECTED",
            "errors": errors,
            "missing_sections": missing_sections
        }

if __name__ == "__main__":
    linter = ArchitectureLinter()
    print(linter.lint_add_document("Sample ADD text"))
metadata.yml (406 bytes)
lesson_id: D352
day: 352
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/architecture_linter.py
test_commands:
- bash tests/run_tests.sh
cleanup_commands:
- rm -rf __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 55
last_executed: '2026-08-30'
executed_on: macOS 15.0 Apple Silicon
requirements/requirements.txt (14 bytes)
pytest>=7.0.0
starter/architecture_linter.py (930 bytes)
"""STARTER -- implement each TASK below, then run the tests.

Every function that raises NotImplementedError is yours to write. The
imports, constants and data structures are given; the logic is not.
Run `bash tests/run_tests.sh` to see which tasks are still outstanding.
"""

import json
from typing import Dict, Any, List

class ArchitectureLinter:

    def __init__(self):
        self.required_sections = ['1. System Overview & Problem Statement', '2. High-Level Component Topology', '3. Data Flow & Sequence Diagrams', '4. Data Schemas & Storage Design', '5. Latency & Resource Budgets', '6. Failure Mode & Resilience Strategies', '7. Security & Compliance Architecture']

    def lint_add_document(self, text: str) -> Dict[str, Any]:
        raise NotImplementedError('TASK 1: implement lint_add_document.')
if __name__ == '__main__':
    linter = ArchitectureLinter()
    print(linter.lint_add_document('Sample ADD text'))
tests/run_tests.sh (253 bytes)
#!/usr/bin/env bash
set -e
export PYTHONPATH=examples:.
if [ -n "$PYTEST" ]; then
    $PYTEST tests/test_*.py -v
elif command -v pytest &> /dev/null; then
    pytest tests/test_*.py -v
else
    python3 -m unittest discover -s tests -p 'test_*.py' -v
fi
tests/test_architecture_linter.py (1709 bytes)
import pytest
from examples.architecture_linter import ArchitectureLinter

def test_linter_approves_complete_add():
    linter = ArchitectureLinter()
    complete_doc = (
        "1. System Overview & Problem Statement\n"
        "2. High-Level Component Topology\n"
        "3. Data Flow & Sequence Diagrams\n"
        "4. Data Schemas & Storage Design\n"
        "5. Latency & Resource Budgets\n"
        "6. Failure Mode & Resilience Strategies\n"
        "7. Security & Compliance Architecture\n"
        "The system enforces a circuit breaker with secondary fallback models.\n"
        "The p95 latency budget is 525ms total."
    )
    result = linter.lint_add_document(complete_doc)
    assert result["status"] == "APPROVED"
    assert result["score"] == 100
    assert len(result["errors"]) == 0

def test_missing_sections_rejection():
    linter = ArchitectureLinter()
    incomplete = "1. System Overview & Problem Statement\ncircuit breaker\np95 latency budget"
    result = linter.lint_add_document(incomplete)
    assert result["status"] == "REJECTED"
    assert len(result["missing_sections"]) == 6

def test_missing_circuit_breaker_detection():
    linter = ArchitectureLinter()
    doc_no_cb = (
        "1. System Overview & Problem Statement\n"
        "2. High-Level Component Topology\n"
        "3. Data Flow & Sequence Diagrams\n"
        "4. Data Schemas & Storage Design\n"
        "5. Latency & Resource Budgets\n"
        "6. Failure Mode & Resilience Strategies\n"
        "7. Security & Compliance Architecture\n"
        "p95 latency budget is 500ms."
    )
    result = linter.lint_add_document(doc_no_cb)
    assert any("circuit breaker" in e.lower() for e in result["errors"])

Troubleshooting

Troubleshooting - Day 352\nEnsure H2 section headers match the required linter strings exactly.\n

Security notes

Security - Day 352\nArchitecture linter enforces failure domain isolation and security perimeter boundaries.\n