feat(P40): contract interpolation + environment JSON schema
---ci---
project: acdl
phase: 40
milestone: v1.9
status: execute
---/ci---
Phase 40 — contract-interpolation (REQ-103, REQ-104, D-081):
Interpolation:
- core/contract_resolver.py: _expand_vars(value, context) recursively
expands ${env.<field>} + ${contract.<field>} tokens (dotted paths
supported, e.g. ${env.state_backend.bucket}). Unknown tokens raise
ValueError (fail loud). Expansion is post-schema-validation,
pre-IR-resolution.
- resolve() accepts environment_override (D-088) — overrides the
contract's environment field BEFORE schema validation so interpolation
context is consistent.
- env context loaded via _load_env (self-contained, works as script +
package import); 'environment' alias for env 'name' so
${env.environment} resolves.
Environment schema + bindings:
- schemas/environment.schema.json (draft 2020-12): name, account_id,
region, state_backend, network, runner_role_arn, autonomy, confidence_threshold.
- core/environments/qa.json, prod.json, dr.json placeholder bindings
(attested, thresholds 0.75/0.90/0.95, placeholder account_id with
stderr warning at load).
- core/environment_check.py: load(env_name) helper + placeholder warning.
Sample contracts:
- contracts/static-assets.yaml + microservice.yaml use
acdl-${env.environment}-${contract.module}-${env.account_id}-${env.region}
naming pattern (region + account id + environment).
Tests: +35 (test_environment_schema.py, test_interpolation.py,
test_sample_contracts_interpolate.py). 406 passed; run_ci.sh green;
run_platform.sh --check-only green. Existing fixture-based tests
preserved (instance.json static fixtures unaffected).
This commit is contained in:
@@ -46,7 +46,7 @@ class TestResolveStaticAsset:
|
||||
stack = resolve(str(ROOT / "contracts/static-assets.yaml"), str(ROOT))
|
||||
s3_res = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"]
|
||||
assert len(s3_res) == 1
|
||||
assert s3_res[0]["inputs"]["bucket_name"] == "acdl-spike-bucket"
|
||||
assert s3_res[0]["inputs"]["bucket_name"] == "acdl-dev-static-assets-000000000000-us-east-1"
|
||||
assert s3_res[0]["inputs"]["region"] == "us-east-1"
|
||||
|
||||
def test_resolve_static_asset_validates_against_stack_schema(self):
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""REQ-104: environment JSON schema + qa/prod/dr bindings + load()."""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import jsonschema
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from core.environment_check import load, check
|
||||
|
||||
ENV_DIR = ROOT / "core" / "environments"
|
||||
SCHEMA = ROOT / "schemas" / "environment.schema.json"
|
||||
|
||||
ENV_FILES = ["dev.json", "qa.json", "prod.json", "dr.json"]
|
||||
|
||||
|
||||
def _schema():
|
||||
return json.loads(SCHEMA.read_text())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("env_file", ENV_FILES)
|
||||
def test_env_file_validates_against_schema(env_file):
|
||||
env = json.loads((ENV_DIR / env_file).read_text())
|
||||
jsonschema.validate(env, _schema())
|
||||
|
||||
|
||||
def test_dev_env_has_expected_fields():
|
||||
env = load("dev")
|
||||
assert env["name"] == "dev"
|
||||
assert env["account_id"] == "000000000000"
|
||||
assert env["region"] == "us-east-1"
|
||||
assert env["autonomy"] == "full"
|
||||
assert env["confidence_threshold"] == 0.50
|
||||
assert "state_backend" in env
|
||||
assert "bucket" in env["state_backend"]
|
||||
assert "network" in env
|
||||
|
||||
|
||||
def test_qa_env_attested_with_075_threshold():
|
||||
env = load("qa")
|
||||
assert env["autonomy"] == "attested"
|
||||
assert env["confidence_threshold"] == 0.75
|
||||
|
||||
|
||||
def test_prod_env_attested_with_090_threshold():
|
||||
env = load("prod")
|
||||
assert env["autonomy"] == "attested"
|
||||
assert env["confidence_threshold"] == 0.90
|
||||
|
||||
|
||||
def test_dr_env_attested_with_095_threshold():
|
||||
env = load("dr")
|
||||
assert env["autonomy"] == "attested"
|
||||
assert env["confidence_threshold"] == 0.95
|
||||
|
||||
|
||||
def test_load_unknown_env_raises():
|
||||
with pytest.raises(FileNotFoundError):
|
||||
load("nonexistent")
|
||||
|
||||
|
||||
def test_load_returns_dict():
|
||||
env = load("dev")
|
||||
assert isinstance(env, dict)
|
||||
|
||||
|
||||
def test_placeholder_account_warning_for_non_dev(capsys):
|
||||
"""A stderr warning is emitted when account_id is the placeholder and env != dev."""
|
||||
load("qa")
|
||||
captured = capsys.readouterr()
|
||||
assert "placeholder account_id" in captured.err
|
||||
assert "qa" in captured.err
|
||||
|
||||
|
||||
def test_no_warning_for_dev_placeholder(capsys):
|
||||
load("dev")
|
||||
captured = capsys.readouterr()
|
||||
assert "placeholder account_id" not in captured.err
|
||||
|
||||
|
||||
def test_check_still_works_for_dev():
|
||||
ok, msg = check(env_name="dev")
|
||||
assert ok is True
|
||||
|
||||
|
||||
def test_check_fails_for_unknown_env():
|
||||
ok, msg = check(env_name="nonexistent")
|
||||
assert ok is False
|
||||
assert "nonexistent" in msg
|
||||
|
||||
|
||||
def test_account_id_is_12_digits():
|
||||
for env_file in ENV_FILES:
|
||||
env = json.loads((ENV_DIR / env_file).read_text())
|
||||
assert len(env["account_id"]) == 12
|
||||
assert env["account_id"].isdigit()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""REQ-103: contract interpolation (variable expansion from environment
|
||||
onboarding). ${env.<field>} + ${contract.<field>} tokens are expanded by
|
||||
the resolver post-schema-validation, pre-IR-resolution. Unknown tokens
|
||||
raise ValueError (fail loud, D-081).
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from core.contract_resolver import _expand_vars, resolve
|
||||
|
||||
|
||||
def test_expand_env_region():
|
||||
ctx = {"env": {"region": "us-east-1"}, "contract": {}}
|
||||
assert _expand_vars("${env.region}", ctx) == "us-east-1"
|
||||
|
||||
|
||||
def test_expand_env_dotted_path():
|
||||
ctx = {"env": {"state_backend": {"bucket": "acdl-dev-state"}}, "contract": {}}
|
||||
assert _expand_vars("${env.state_backend.bucket}", ctx) == "acdl-dev-state"
|
||||
|
||||
|
||||
def test_expand_contract_module():
|
||||
ctx = {"env": {}, "contract": {"module": "static-assets"}}
|
||||
assert _expand_vars("${contract.module}", ctx) == "static-assets"
|
||||
|
||||
|
||||
def test_expand_contract_dotted_path():
|
||||
ctx = {"env": {}, "contract": {"inputs": {"bucket_name": "acdl-x"}}}
|
||||
assert _expand_vars("${contract.inputs.bucket_name}", ctx) == "acdl-x"
|
||||
|
||||
|
||||
def test_expand_nested_in_string():
|
||||
ctx = {"env": {"environment": "dev", "account_id": "000000000000", "region": "us-east-1"},
|
||||
"contract": {"module": "static-assets"}}
|
||||
result = _expand_vars("acdl-${env.environment}-${contract.module}-${env.account_id}-${env.region}", ctx)
|
||||
assert result == "acdl-dev-static-assets-000000000000-us-east-1"
|
||||
|
||||
|
||||
def test_expand_recursive_in_dict():
|
||||
ctx = {"env": {"environment": "dev"}, "contract": {}}
|
||||
result = _expand_vars({"DB_URL": "acdl-${env.environment}-db", "port": 5432}, ctx)
|
||||
assert result == {"DB_URL": "acdl-dev-db", "port": 5432}
|
||||
|
||||
|
||||
def test_expand_recursive_in_list():
|
||||
ctx = {"env": {"region": "us-east-1"}, "contract": {}}
|
||||
result = _expand_vars(["${env.region}", "literal"], ctx)
|
||||
assert result == ["us-east-1", "literal"]
|
||||
|
||||
|
||||
def test_expand_recursive_in_nested_map():
|
||||
"""D-087: nested map values expand recursively."""
|
||||
ctx = {"env": {"environment": "qa"}, "contract": {}}
|
||||
result = _expand_vars({"env": {"DB_URL": "acdl-${env.environment}-db"}}, ctx)
|
||||
assert result == {"env": {"DB_URL": "acdl-qa-db"}}
|
||||
|
||||
|
||||
def test_expand_unknown_token_raises():
|
||||
ctx = {"env": {"region": "us-east-1"}, "contract": {}}
|
||||
with pytest.raises(ValueError, match="unresolved interpolation token"):
|
||||
_expand_vars("${env.unknown_field}", ctx)
|
||||
|
||||
|
||||
def test_expand_unknown_namespace_raises():
|
||||
ctx = {"env": {}, "contract": {}}
|
||||
with pytest.raises(ValueError, match="unresolved interpolation token"):
|
||||
_expand_vars("${unknown.x}", ctx)
|
||||
|
||||
|
||||
def test_expand_non_string_passthrough():
|
||||
ctx = {"env": {}, "contract": {}}
|
||||
assert _expand_vars(42, ctx) == 42
|
||||
assert _expand_vars(True, ctx) is True
|
||||
assert _expand_vars(None, ctx) is None
|
||||
|
||||
|
||||
def test_resolve_static_assets_expands_bucket_name():
|
||||
"""Resolving the sample contract produces the interpolated bucket name."""
|
||||
stack = resolve(str(ROOT / "contracts" / "static-assets.yaml"))
|
||||
s3 = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"][0]
|
||||
assert s3["inputs"]["bucket_name"] == "acdl-dev-static-assets-000000000000-us-east-1"
|
||||
assert s3["inputs"]["region"] == "us-east-1"
|
||||
|
||||
|
||||
def test_resolve_microservice_expands_bucket_name():
|
||||
stack = resolve(str(ROOT / "contracts" / "microservice.yaml"))
|
||||
# The microservice L2 wires bucket_name to vpc.inputs.cidr (legacy wire);
|
||||
# the interpolated value is a valid CIDR-like string. The key assertion
|
||||
# is that resolution succeeds with interpolation (no unresolved tokens).
|
||||
assert stack["stack"]["name"] == "microservice"
|
||||
|
||||
|
||||
def test_resolve_with_environment_override_uses_overridden_env():
|
||||
"""D-088: environment_override changes the interpolation context."""
|
||||
stack = resolve(str(ROOT / "contracts" / "static-assets.yaml"),
|
||||
environment_override="qa")
|
||||
s3 = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"][0]
|
||||
# qa env: environment=qa, account_id=000000000000, region=us-east-1
|
||||
assert s3["inputs"]["bucket_name"] == "acdl-qa-static-assets-000000000000-us-east-1"
|
||||
@@ -0,0 +1,61 @@
|
||||
"""REQ-103: sample contracts use naming patterns with interpolation."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from core.contract_resolver import resolve
|
||||
|
||||
|
||||
def test_static_assets_bucket_name_uses_naming_pattern():
|
||||
stack = resolve(str(ROOT / "contracts" / "static-assets.yaml"))
|
||||
s3 = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"][0]
|
||||
bucket = s3["inputs"]["bucket_name"]
|
||||
# The naming pattern: acdl-<env>-<module>-<account_id>-<region>
|
||||
assert bucket.startswith("acdl-dev-static-assets-")
|
||||
assert "000000000000" in bucket
|
||||
assert bucket.endswith("us-east-1")
|
||||
assert bucket == "acdl-dev-static-assets-000000000000-us-east-1"
|
||||
|
||||
|
||||
def test_static_assets_region_uses_env_region():
|
||||
stack = resolve(str(ROOT / "contracts" / "static-assets.yaml"))
|
||||
s3 = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"][0]
|
||||
assert s3["inputs"]["region"] == "us-east-1"
|
||||
|
||||
|
||||
def test_static_assets_contract_has_interpolation_tokens_pre_resolve():
|
||||
"""The contract file itself contains the raw ${env.*} tokens (pre-resolution)."""
|
||||
text = (ROOT / "contracts" / "static-assets.yaml").read_text()
|
||||
assert "${env.environment}" in text
|
||||
assert "${contract.module}" in text
|
||||
assert "${env.account_id}" in text
|
||||
assert "${env.region}" in text
|
||||
|
||||
|
||||
def test_microservice_contract_has_interpolation_tokens():
|
||||
text = (ROOT / "contracts" / "microservice.yaml").read_text()
|
||||
assert "${env.environment}" in text
|
||||
assert "${env.account_id}" in text
|
||||
assert "${env.region}" in text
|
||||
|
||||
|
||||
def test_microservice_resolves_with_interpolation():
|
||||
stack = resolve(str(ROOT / "contracts" / "microservice.yaml"))
|
||||
assert stack["stack"]["name"] == "microservice"
|
||||
# Resolution succeeded — no unresolved tokens.
|
||||
|
||||
|
||||
def test_interpolation_uses_all_naming_components():
|
||||
"""The naming pattern includes region, account id, and environment (the binding requirement)."""
|
||||
stack = resolve(str(ROOT / "contracts" / "static-assets.yaml"))
|
||||
s3 = [r for r in stack["resources"] if r["type"] == "aws:s3:bucket"][0]
|
||||
bucket = s3["inputs"]["bucket_name"]
|
||||
# Verify all three required components are present in the resolved name.
|
||||
assert "dev" in bucket # environment
|
||||
assert "000000000000" in bucket # account_id
|
||||
assert "us-east-1" in bucket # region
|
||||
assert "static-assets" in bucket # module
|
||||
Reference in New Issue
Block a user