Create a schema diff CI: template snapshots, required fields check, and live validation.
- User
Create a schema diff CI: template snapshots, required fields check, and live validation.
Assistant
Create a schema diff CI: template snapshots, required fields check, and live validation.
The user wants a "schema diff CI" solution. This implies a Continuous Integration (CI) workflow or pipeline. The core functionality includes three main components:
The context is likely software engineering, dealing with APIs (REST/GraphQL), databases, or message queues (Kafka/RabbitMQ). The implementation will depend heavily on the technology stack (e.g., Python/Pydantic, TypeScript/Zod, SQL/Alembic, Protobuf). Since the user didn't specify a stack, I need to provide a generic but actionable solution, likely using a popular stack like Python (using JSON Schema or Pydantic) or general JSON Schema tooling as the most common denominator.
However, "CI" usually implies scripts, GitHub Actions, GitLab CI, etc.
Plan:
jest (for snapshots) or a simple diff tool like jd or just git diff.git diff --exit-code). This prevents accidental schema drift.required, but we want to ensure new requirements aren't missed, or specific critical fields always exist.required array.Refining the implementation:
Detailed Step-by-Step Design:
Directory Structure:
schemas/ (source of truth)tests/
fixtures/ (sample data for live validation)test_schema.py (or .sh)Step 1: Snapshot Diff.
git diff is too noisy? No, git diff --exit-code is perfect for "Has this file changed unexpectedly?".Step 2: Required Fields Check.
schema['required'] contains ['id', 'timestamp'].Step 3: Live Validation.
tests/fixtures/*.json. Validate each against schema.json. Fail CI if validation errors occur.Drafting the Code (Mental or Scratchpad):
Script: ci_schema_check.py
Requirements: jsonschema (python lib).
Snapshot Logic:
python export_schema.py > schema.json), simply check if git is dirty.oasdiff (for OpenAPI) or just a semantic diff. But the user said "Template Snapshots". Let's stick to the "Golden File" pattern.Let's build a comprehensive GitHub Action workflow with a Python script.
Structure of the answer:
validator.py): This handles the logic (Snapshot, Required, Live).github-actions.yml): How to run it.Self-Correction during drafting: The user asked for "Template Snapshots". In testing terms, this usually means "Compare current render to saved file". If the schema is generated from code (e.g. Typescript interfaces), we generate it and compare. If it's hand-written, maybe they mean comparing the new PR version against main to detect breaking changes. Decision: I will implement the "Golden Master" approach: Run code generation -> Diff against committed file. This ensures code matches schema.
Required Fields Check:
We need a way to define what is required.
Option: Hardcode in the script? No.
Option: A config file schema_rules.yaml.
Let's keep it simple: A list of fields in the CI script or a simple config.
Live Validation: Needs dummy data. I'll create a folder structure example.
Final Polish: Make sure the code is copy-pasteable and works. Use standard libraries where possible.
Code Structure:
schema.json (The subject)fixtures/valid_payload.json (For live validation)check_schema.py (The brain).github/workflows/ci.yml (The runner)The check_schema.py script logic:
export_schema() -> compare. If just static files, this might mean "Check for structural changes" using a diff tool. I will implement a "Breaking Change Diff" as it's more useful for CI than just file diffing (e.g., oasdiff or json-schema-diff). Actually, "Template Snapshots" implies Jest-style snapshots. Let's assume the user generates the schema and wants to freeze it.id in required.jsonschema.validate.Let's write the response. This guide implements a robust CI pipeline for Schema Drift, Enforcement, and Validation. While the concepts apply to any technology, we will use JSON Schema and Python for the concrete implementation, as they are the industry standard for data contracts.
timestamp, id, source) are present and non-nullable..
├── .github/workflows/
│ └── schema-ci.yml # The CI Pipeline
├── schemas/
│ └── event.schema.json # The Source of Truth
├── tests/
│ ├── fixtures/ # Sample data for Live Validation
│ │ └── sample_event.json
│ ├── test_contracts.py # Checks required fields
│ └── test_validation.py # Live validation runner
├── requirements-ci.txt # Dependencies (jsonschema, pytest)
└── scripts/
└── diff_snapshot.py # Handles the Template Snapshots
schemas/event.schema.json)For this example, we assume a generic event schema.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"event_id": { "type": "string", "format": "uuid" },
"timestamp": { "type": "string", "format": "date-time" },
"payload": { "type": "object" }
},
"required": ["event_id", "timestamp"]
}
This script ensures that if someone modifies the schema logic (e.g., in code generation or a separate definition file), the resulting JSON file is updated.
scripts/diff_snapshot.py:
import json
import sys
from pathlib import Path
# This mimics a build step where a schema might be generated from code (e.g. Pydantic/Typescript)
# For this demo, we just read the source, but in reality, this would call a generator.
def generate_schema():
path = Path("schemas/event.schema.json")
return json.dumps(json.load(path.open()), indent=2, sort_keys=True)
def main():
generated_schema = generate_schema()
# Load the committed "Golden Master"
snapshot_path = Path("schemas/event.snapshot.json")
if not snapshot_path.exists():
print("Snapshot missing! Creating initial snapshot.")
snapshot_path.write_text(generated_schema)
sys.exit(0)
current_snapshot = snapshot_path.read_text()
if generated_schema != current_snapshot:
print("ERROR: Schema drift detected!")
print("The generated schema does not match the snapshot file.")
print("Please update your snapshot file or fix the generation logic.")
sys.exit(1)
print("SUCCESS: Schema matches snapshot.")
if __name__ == "__main__":
main()
Instead of just trusting the required list in the JSON, we write a test to enforce business logic (e.g., "All events MUST have a timestamp").
tests/test_contracts.py:
import json
import pytest
SCHEMA_PATH = "schemas/event.schema.json"
def load_schema():
with open(SCHEMA_PATH) as f:
return json.load(f)
def test_mandatory_fields_exist():
"""
Enforce that specific high-priority fields are strictly required.
This prevents a developer from accidentally removing 'timestamp'
from the required list during an edit.
"""
schema = load_schema()
# 1. Check that the 'required' list exists
assert "required" in schema, "Schema missing 'required' list"
# 2. Define the MUST-HAVE fields
mandatory_fields = {"event_id", "timestamp"}
# 3. Verify they are in the schema's required list
schema_required = set(schema["required"])
missing = mandatory_fields - schema_required
assert not missing, f"Critical fields missing from 'required': {missing}"
def test_field_types():
"""
Ensure specific fields have the correct type definition.
"""
schema = load_schema()
props = schema.get("properties", {})
assert props.get("event_id", {}).get("type") == "string"
# Ensure payload is an object, not a string
assert props.get("payload", {}).get("type") == "object"
This validates real data against the schema to catch logic errors (e.g., a regex that is too strict).
tests/test_validation.py:
import json
import glob
from jsonschema import validate, ValidationError, Draft7Validator
import pytest
SCHEMA_PATH = "schemas/event.schema.json"
@pytest.fixture
def schema():
with open(SCHEMA_PATH) as f:
return json.load(f)
def test_all_fixtures_are_valid(schema):
"""
Load all sample JSONs from the fixtures folder and validate them.
"""
fixture_files = glob.glob("tests/fixtures/*.json")
assert len(fixture_files) > 0, "No test fixtures found!"
for file_path in fixture_files:
with open(file_path) as f:
instance = json.load(f)
# This will raise an exception if invalid, failing the test
try:
validate(instance=instance, schema=schema)
except ValidationError as e:
pytest.fail(f"Validation failed for {file_path}: {e.message}")
def test_invalid_data_fails(schema):
"""
Ensure the schema actually catches bad data (Sanity check).
"""
invalid_data = {"event_id": "123"} # Missing timestamp
# Check that this specific error is raised
# Draft7Validator allows detailed error inspection
validator = Draft7Validator(schema)
errors = sorted(validator.iter_errors(invalid_data), key=lambda e: e.path)
assert len(errors) > 0, "Schema should have rejected invalid data"
tests/fixtures/sample_event.json:
{
"event_id": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2023-10-27T10:00:00Z",
"payload": {
"action": "click"
}
}
Create .github/workflows/schema-ci.yml.
name: Schema Validation CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install Dependencies
run: |
pip install -r requirements-ci.txt
# STEP 1: Template Snapshot Diff
- name: Check Schema Snapshots
run: python scripts/diff_snapshot.py
# STEP 2: Run Contract & Validation Tests
- name: Run Pytest (Contracts + Live Validation)
run: pytest tests/
requirements-ci.txt:
pytest
jsonschema
Here is how this pipeline handles specific failures:
.json file, diff_snapshot.py fails."timestamp" from the required array in the schema, test_contracts.py fails.test_validation.py fails because the sample fixture won't validate.