RFC: Typed Runtime Bindings and App-Config Export
Status: Draft
Date: 2026-11-27
Owners: nf.core, nf.sdk, nf.cli, nf.bindings
Summary
This RFC proposes Typed Runtime Bindings and App-Config Export for Netherframe: an end-to-end typed contract connecting infrastructure declarations (nf.core) to application runtime consumers without shipping Netherframe's engine, gRPC transport, or provider packages into application containers.
The design pairs:
- A zero-codegen monorepo authoring surface (
Service+export()+ Python 3.15lazyimports) where a single Python class defines infrastructure, automatically registers typedOutputconstructs, and serves as the static runtime config interface for application code—requiring no separate*Runtimeschema dataclass. - A portable sealed runtime manifest and
nf exportcommand (netherframe.bindings/nf.bindings), enabling zero-dependency startup loading in containers, standalone typed stub generation for multi-repo or existingApp/Outputprojects, and fail-closed secret handling viaSecretRefdescriptors that a running process reads again as secrets rotate. - A hybrid local development loop (
nf run) that binds applied (or local FakeCloud) infrastructure state into live application processes and integration test runs, with nothing passed through the environment.
Together, these features bring the single-source-of-truth ergonomics pioneered by TypeScript-native IaC tools such as Alchemy (alchemy-run/alchemy) into Netherframe while preserving Netherframe's strict determinism, immutable saved plans, fail-closed secret boundaries, and Terraform provider ecosystem.
Motivation
Netherframe already provides strong end-to-end typing on the input side of an infrastructure run (netherframe.core.inputs):
- App factory functions declare type-annotated parameters (and dataclass parameter groups) validated before anything is built.
Secret[T]prevents sensitive inputs from appearing on CLIargvor in plaintext saved plans.Teardown[T]inputs are verified not to alter deployment shape.- Applied deployment inputs are persisted in state so
nf destroyalways reconstructs the exact deployed shape.
By contrast, the output side—where infrastructure hands connection strings, bucket names, queue URLs, and secret references to application code—remains untyped:
Output(netherframe.core.constructs.infrastructure.Output) acceptsvalue: Anywith no typed consumer handle.RunReport.outputs()(netherframe.sdk.run_reports) returns an untypeddict[str, Any].Project.output()(netherframe.sdk.lifecycle) remains a legacy Terraform passthrough.- Application code must manually bridge output keys to environment variables, JSON files, or bespoke config loaders, with no static guarantee that renames, removed outputs, type changes, or sensitivity classifications stay aligned between infrastructure and application code.
Meanwhile, RuntimeValue[T] (netherframe.core.values.runtime_value) already tracks covariant Python types across generated provider bindings (a generated ref_<attr> property such as queue.ref_url is statically typed as RuntimeValue[str]; the dynamic resource.output.<attr> accessor is not, and type checkers see it as an untyped Ref), and output_is_sensitive already tracks whether an evaluated output originated from a sensitive attribute. Netherframe already holds all the type and sensitivity information needed to eliminate the untyped infra-to-app boundary.
Goals
- Single source of truth without duplicate schema classes: In monorepos, allow authors to define infrastructure and typed application outputs in one
Serviceclass with fullty/pyright/mypychecking and IDE autocomplete. - Zero engine bloat in application containers: Application processes importing runtime bindings must require only a tiny zero-dependency package (
netherframe.bindings), nevernetherframe.core,grpcio,libcst,loguru,rich, or generated provider packages. - First-class support for multi-repo and existing apps: Existing
def app() -> Appmodules withOutput(...)constructs must gain the same runtime manifest and generated typed stubs (nf export) without rewriting to aServiceclass. - Fail-closed secret hygiene: Secrets must never silently flow into non-secret outputs or plaintext runtime config files; manifests carry typed
SecretRefpointers that the application process resolves. - Rotation without a restart: A secret that rotates reaches a running process: secrets are read through their
SecretRefeach time they are used, not copied at startup. - No environment variables: Preserve Netherframe's explicit configuration model (Configuration) across
nf export,nf.bindings, andnf run: a manifest is found by path, andnf runsets nothing in its child's environment. - API-first parity: Every command and option lands in
nf.sdkfirst before CLI wiring (test_sdk_parity).
Non-Goals
- No Effect/monadic DSL: Netherframe will not adopt an Effect-TS-style monadic programming model;
Servicebuilds cleanly on Netherframe's construct tree,RuntimeValue[T],@hybrid_runtime, andNfError. - No weakening of the plan/apply wall: Immutable saved plans, final-plan consistency checks, and deterministic
RuntimeValueevaluation remain unchanged (Hybrid Execution Semantics). - No cloud-service emulation engine inside
nf.core: Local execution leverages existing provider/FakeCloud capabilities rather than re-implementing cloud APIs. - No runtime dependency on provider SDKs inside
netherframe.core: Typed client bindings (Phase 4) belong in provider extension packages such asnetherframe.ext.aws.
Architecture Overview
The system separates authoring surfaces, core build/apply tracking, sealed manifest emission, and runtime consumption behind strict package boundaries:
flowchart LR
subgraph Authoring["Authoring Surfaces"]
SVC["Service + export() + lazy imports"]
APP["Existing App + Output constructs"]
end
subgraph Core["Netherframe Engine (nf.core / nf.sdk)"]
REG["Output Registration & Type/Taint Check"]
PLAN["Saved Plans & State Engine"]
EXP["nf export / Project.export()"]
end
subgraph Artifacts["Portable Artifacts"]
MAN["Sealed Runtime Manifest (JSON/TOML + SecretRef)"]
STUB["Generated Typed Stubs (nf_bindings.py)"]
end
subgraph Consumers["Runtime Consumers"]
PROD["App Container (nf.bindings + Service or stub)"]
DEV["Local Dev (nf run / FakeCloud)"]
SDK["Automation Scripts (nf.sdk RunReport.export)"]
end
SVC --> REG
APP --> REG
REG --> PLAN
PLAN --> EXP
EXP --> MAN
EXP --> STUB
MAN --> PROD
SVC -. "runtime() skips __init__" .-> PROD
STUB --> PROD
MAN --> DEV
PLAN --> SDK
1. Zero-Codegen Monorepo Authoring (Service + export())
Surface API
In a monorepo, a developer defines infrastructure and typed runtime exports in a single class using Python 3.15 lazy imports (PEP 810):
# infra/orders.py
lazy from nf.core import App, Stack
lazy from nf.providers.hashicorp.aws import (
AwsProvider,
DynamodbTable,
SecretsmanagerSecret,
SqsQueue,
)
from nf.bindings import Service, export
class Orders(Service, app="orders"):
def __init__(self, env: str = "dev", region: str = "eu-west-1") -> None:
with App(nf_id="orders"), Stack(nf_id=f"orders-{env}"):
AwsProvider(nf_id="aws", region=region)
table = DynamodbTable(
nf_id="table",
name=f"orders-{env}",
billing_mode="PAY_PER_REQUEST",
hash_key="order_id",
)
events = SqsQueue(nf_id="events", name=f"orders-{env}-events")
db_secret = SecretsmanagerSecret(nf_id="db_secret", name=f"orders-{env}-db")
# Generated ref_<attr> properties are typed RuntimeValue[T]; a DynamoDB table's id is its name
self.table_name = export(table.ref_id_)
self.events_queue_url = export(events.ref_url)
self.db_password = export(db_secret.ref_arn, sensitive=True)
The module passes nf_id explicitly instead of starting with # coding: nf_autoid. A file that names that codec cannot be imported where the codec is not installed (SyntaxError: unknown encoding: nf_autoid), and where it is installed, decoding the file imports libcst. Whether service modules can use the codec at all is an open question (see Open Questions).
export is typed with @overloads that unwrap RuntimeValue[T] into T (or Secret[T] when sensitive=True). A runtime value and a constant take separate overloads: a single value: T | RuntimeValue[T] parameter is solved by ty and pyright, but mypy infers Never for it and rejects the call:
from typing import Literal, overload
from nf.bindings import Secret
@overload
def export[T](
value: RuntimeValue[T],
*,
sensitive: Literal[False] = False,
description: str | None = None,
) -> T: ...
@overload
def export[T](
value: RuntimeValue[T],
*,
sensitive: Literal[True],
description: str | None = None,
) -> Secret[T]: ...
@overload
def export[T](
value: T,
*,
sensitive: Literal[False] = False,
description: str | None = None,
) -> T: ...
@overload
def export[T](
value: T,
*,
sensitive: Literal[True],
description: str | None = None,
) -> Secret[T]: ...
Application code imports Orders directly—no separate OrdersRuntime dataclass and no manual field annotations:
# orders/api.py
from infra.orders import Orders
# Style A: lazy runtime handle (statically typed as Orders)
cfg = Orders.runtime()
def publish_order(order_id: str) -> str:
return f"send {order_id} -> {cfg.events_queue_url} (table={cfg.table_name})"
# Style B: decorator injection (the injected parameter comes first)
@Orders.inject
def handle_order(orders: Orders, order_id: str) -> str:
return f"{order_id}:{orders.table_name}"
inject supplies the first parameter: a decorator's type can remove only leading parameters (Concatenate), so callers see handle_order as (order_id: str) -> str. With orders last, every call would be reported as missing an argument.
runtime and inject are classmethods of Service (runtime returns Self), which is why Orders subclasses it and is not decorated: a class decorator's return type cannot add attributes to the class it decorates, and ty, pyright and mypy would all report Orders.runtime as unknown.
Build-Time Lifecycle
When Netherframe loads "infra.orders:Orders" from [tool.nf].hybrid_apps during nf plan, nf apply, or nf destroy:
- Input extraction: The app loader inspects
Orders.__init__using the same parameter, dataclass-group,Secret[T], andTeardown[T]machinery innetherframe.core.inputs. - Build execution: The loader instantiates
Orders(*resolved_args, **resolved_kwargs)inside an activeApp/Stackcapture scope. - Automatic
Outputregistration:export(...)returns a marker holding the value, its sensitivity and description, and the stack that is active when it is called.Servicerecords each marker under the attribute name it is assigned to, as it is assigned, and stores nothing on the instance (see Exports Are Write-Only While Building). Right after__init__returns, each recorded export is registered as anOutput(nf_id=attr_name, value=marker.value, sensitive=marker.sensitive, description=marker.description)on the marker's stack (or designated export stack). Repeatingnf_idis unnecessary. Anexport(...)result that was never assigned to an attribute fails the build. - Schema recording:
Servicerecords the export contract (field names, declared/inferred Python types, sensitivity flags, and input schema) onAppmetadata (semantics["exports"]in saved plans). - Typed SDK consumption:
RunReport.export(Orders)andProject.exports(Orders, app="orders")hydrate and return a realOrdersinstance populated from applied outputs.
Application-Runtime Lifecycle
When application code executes from infra.orders import Orders and calls Orders.runtime() in production:
- Because
nf.coreandnf.providers.*are imported via Python 3.15lazy fromstatements, importinginfra.ordersdoes not loadnetherframe.core,grpcio,libcst, or any provider package. This holds only while nothing resolves the lazy names: a module-level use of one (a base class, a default value, a module constant), or a tool that reads every attribute of the module (inspect.getmembers,getattr(module, "App")), importsnetherframe.coreat that point and raisesModuleNotFoundErrorin a container. Orders.runtime()allocates the instance viaobject.__new__(Orders)—never callingOrders.__init__—and attaches the sealed runtime manifest to it. Nothing is copied onto the instance: each attribute read is served from the manifest, a plain export fromvaluesand a secret through the configuredSecretResolver(see Live Secret Reads and Rotation). An attribute the manifest does not hold raisesAttributeError, naming the app and the export.- Calling
Orders.runtime(expect_inputs={"env": "prod"})verifies manifest provenance at startup and fails fast before serving traffic if the manifest targets the wrong environment or schema digest.
2. Build-Time Semantics of Exported Values & Typing Trade-Offs
The Core Typing Tension
Giving export(table.ref_id_) a static return type of T (str) makes application code (cfg.table_name) completely ergonomic with zero .value unwrapping, and lets type checkers infer the whole contract from the assignments in __init__, with nothing declared twice. The consequence is that inside Orders.__init__, static type checkers (ty, pyright, mypy) also see self.table_name as str, even though no string exists at infrastructure build time: what was exported is a RuntimeValue.
A RuntimeValue cannot stand in for a str in every expression:
- Truthiness (
if,and,or,not),len(),inand iteration raiseTypeError. - Others answer about the expression object, not about the value it stands for, so the code runs and takes a branch decided at build time:
==and!=(Expression.__eq__compares the structure of two expressions),match/case, membership in a concrete container,is None,isinstance(),str()(which gives the Terraform reference text,${aws_dynamodb_table.table.id}) and hashing.
A type checker that has been told str reports none of these.
Exports Are Write-Only While Building
One rule resolves the tension, in place of deferring some of these expressions and linting the rest: while a service is built, an exported attribute can be assigned and never read. Reading self.table_name in any expression during the build raises TypeError, so the str that type checkers see there can never be observed as anything else. Every case above fails closed alike, as soon as Orders(...) is constructed in pytest or nf plan.
Build-time expressions are written on the value that was exported, which is typed as what it is:
class Orders(Service, app="orders"):
def __init__(self, env: str = "dev") -> None:
with App(nf_id="orders"), Stack(nf_id=f"orders-{env}"):
table = DynamodbTable(nf_id="table", name=f"orders-{env}", hash_key="order_id")
self.table_name = export(table.ref_id_)
# table.ref_id_ is RuntimeValue[str], and so is table.ref_id_ + "-dlq"
SqsQueue(nf_id="dlq", name=table.ref_id_ + "-dlq")
self.dlq_name = export(table.ref_id_ + "-dlq")
# TypeError: Orders.table_name is an export: it is write-only while the service is built
SqsQueue(nf_id="audit", name=self.table_name + "-audit")
Service enforces the rule in the two hooks through which an instance's attributes are set and missed:
from typing import TYPE_CHECKING, Any
class Service:
if not TYPE_CHECKING:
def __setattr__(self, name: str, value: Any) -> None:
if isinstance(value, Export): # what export(...) returns
self.__dict__.setdefault("_nf_exports", {})[name] = value
return
object.__setattr__(self, name, value)
def __getattr__(self, name: str) -> Any:
manifest = self.__dict__.get("_nf_manifest")
if manifest is not None: # at runtime: Orders.runtime() attached it
return manifest.read(name)
if name in self.__dict__.get("_nf_exports", {}):
raise TypeError(f"{type(self).__name__}.{name} is an export: it is write-only while the service is built")
raise AttributeError(name)
__setattr__records a marker under the name it is assigned to and leaves the attribute unset. The name comes with the assignment, so nothing scansself.__dict__afterwards.__getattr__runs only for an attribute that is not set. While the service is built it finds the name among the recorded exports and raises. At runtime it serves the manifest (see Application-Runtime Lifecycle).- Both hooks are hidden from type checkers (
if not TYPE_CHECKING:). With a visible__getattr__every attribute name would be accepted, and a misspelledcfg.tabel_namehas to stay an error.
RuntimeValue operators (+, [], |, f-strings) already build expression nodes and are typed, so export(table.ref_id_ + "-dlq") is inferred as str. A method of the underlying type is not available that way: Ref.__getattr__ (netherframe.core.values.expressions) answers every public attribute name with an AttributeAccessor for chained access (resource.output.outputs.vpc_id), so table.ref_id_.upper() raises TypeError: 'AttributeAccessor' object is not callable, and the spelling today is table.ref_id_.call_method("upper"). As an ergonomics improvement, RuntimeValue[str] in netherframe.core.values.runtime_value may expose pure string methods (upper, lower, strip, replace) backed by call_method. They have to exist at runtime: signatures declared only under if TYPE_CHECKING: would pass type checking and then fail with the AttributeAccessor error.
Optional Editor-Time Check (NFB001)
The build-time TypeError is the guarantee. A lint rule NFB001 (service-export-read) could report the same mistake earlier, at edit time: any read of self.<name> in the __init__ of a Service subclass, where <name> is assigned from export(...). It would be a source rule, which nf lint does not have yet: netherframe.core.linting runs rules over the provider arguments of a built app (Rule, NativeRule, PolicyRule) and never reads source, so the rule needs a new AST pass. No phase below depends on it.
Alternative Considered: Strict Honest Types (Output[T] + .value)
An alternative ("Choice B") keeps static types 100% faithful inside __init__ by typing self.table_name as Output[str] at authoring time and reading orders.table_name.value at application call sites:
| Aspect | Choice A: export() -> T, write-only while building (Adopted) |
Choice B: Output[T] + .value |
|---|---|---|
| App call-site ergonomics | orders.table_name (str) |
orders.table_name.value (str) |
| IDE/type-checker accuracy in app code | Exact (T / Secret[T]) |
Exact (T / Secret[T]) |
Static type of self.table_name in __init__ |
str, which is not what is there; no expression can observe the difference, because a read raises |
Output[str], which is what is there |
Reading an export back in __init__ |
TypeError at build time; use the value that was exported |
Allowed, with RuntimeValue operators |
Decision: Choice A. Application read sites vastly outnumber infra export wiring sites, the contract is inferred with nothing declared twice, and the one place where the static type differs from the object cannot be reached.
3. Multi-Repo, Existing Apps, and Polyglot Consumers (nf export)
Not every project uses a Service class, and not every consumer runs in the same Python repository. To support multi-repo teams, existing App/Output projects, and non-Python services, this RFC introduces Project.export(...) in nf.sdk and nf export in nf.cli.
CLI and SDK Surface
from pathlib import Path
from nf.sdk import Project
project = Project(Path("."), inputs={"env": "prod"})
manifest = project.export(
app="orders",
format="json",
out=Path("dist/orders.bindings.json"),
)
Corresponding CLI usage:
nf export --app orders ++env=prod --out dist/orders.bindings.json
nf export --app orders ++env=prod --format py-stub --out orders_bindings.py
nf export --app orders ++env=prod --format toml --out dist/orders.bindings.toml
nf export --app orders ++env=prod --format k8s-configmap --out dist/orders-cm.yaml
Supported --format targets:
- json (default): canonical Sealed Runtime Manifest consumed by nf.bindings.
- toml: human-readable manifest with identical provenance and SecretRef fields.
- env: dotenv key-value export (non-secret values only unless --reveal is explicitly passed for local workflows).
- k8s-configmap: Kubernetes ConfigMap carrying the manifest as <app>.json, to mount at /run/nf/bindings/ (non-secret values and SecretRefs; pairable with External Secrets).
- py-stub: standalone zero-dependency Python module + .pyi containing one typed class per app, backed by nf.bindings.
Standalone Stub Generation (--format py-stub)
For projects using existing def orders(...) -> App factories with Output(...) constructs—or multi-repo teams publishing bindings as a build artifact—nf export --format py-stub derives the typed schema from:
- The exports a
Serviceclass records (when present), or - Provider resource output schemas (
RuntimeValue[T]/GetProviderSchematypes) andoutput_is_sensitivetainting on eachOutputconstruct.
Generated output:
# Generated by `nf export --format py-stub` — do not edit manually.
from nf.bindings import Secret, Service
class OrdersBindings(Service, app="orders"):
table_name: str
events_queue_url: str
db_password: Secret[str]
orders = OrdersBindings.runtime()
The generated class is a Service subclass that declares its exports and has no __init__, so a stub consumer reads the manifest exactly as a monorepo consumer does, secrets that rotate included. This matches Netherframe's existing deterministic code-generation pattern (generate_nf_alias_shims.py and golden tests), allowing CI to verify that published stubs are never stale.
Sealed Runtime Manifest Format
Every exported manifest embeds provenance metadata alongside values so runtime loaders can reject stale, mismatched, or tampered bindings:
{
"schema_version": 1,
"app": "orders",
"inputs": {
"env": "prod",
"region": "eu-west-1"
},
"input_digests": {},
"state_lineage": "9f3b8c1e-4a2b-4c6d-8e1f-0123456789ab",
"serial": 14,
"schema_digest": "sha256:4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a",
"values": {
"table_name": "orders-prod",
"events_queue_url": "https://sqs.eu-west-1.amazonaws.com/123456789012/orders-prod-events"
},
"secrets": {
"db_password": {
"kind": "aws_secretsmanager",
"ref": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:orders-prod-db-AbCdEf",
"sensitive": true
}
}
}
Runtime Manifest Resolution Order
Orders.runtime() finds the app's manifest by path. Nothing is read from the environment, and nf.bindings never parses the host process's command line. The manifest is the first of:
- An explicit
manifest: Path | Mapping[str, Any]argument passed by the caller. <app>.jsonin the directory given toBindingsConfig.configure(directory=...)at the process entrypoint.<app>.jsonin the fixed directory/run/nf/bindings/, where a container mounts its manifests.- The project-local
.nf.out/bindings/<app>.json, in the nearest directory at or above the working directory whosepyproject.tomlhas a[tool.nf]table (localnf runand single-host dev workflows).
When none of them holds the app's manifest, runtime() raises and names each place it looked.
The lookup is a directory and an app name, not one file per process, because a process may consume several services (Orders.runtime() and Billing.runtime()).
- Kubernetes: mount the
ConfigMapthat carries the manifest as a volume at/run/nf/bindings/. Mount the directory, not a single file withsubPath: asubPathmount does not receive updates. - Platforms with no config-file mount (AWS Lambda, and ECS unless a volume is set up for it): ship the manifest inside the deployment package and call
BindingsConfig.configure(directory=...)at the entrypoint. The package is then specific to one deployment.
A fixed path and an explicit call cover what an environment variable would, and a mounted file has one property a variable lacks: it can change under a running process.
4. Security, Secret Tainting, and SecretRef Resolution
Fail-Closed Sensitivity Tainting
Netherframe already propagates sensitivity through RuntimeValue evaluation and marks outputs via mark_output_sensitive / output_is_sensitive. Today a tainted output is not refused: evaluating it marks it sensitive as if it had been declared so, and state records it with sensitive: true. The two refusals below are new behavior. Under this RFC:
- Exporting a sensitive or sensitive-tainted
RuntimeValueviaexport(val)withoutsensitive=Truefails closed during planning (ValidationError) rather than silently emitting the secret intovaluesor aConfigMap. - Similarly, for plain
Output(...)constructs, any tainted value not markedsensitive=Trueis refused bynf export.
SecretRef Instead of Plaintext Secrets
By default, nf export never writes plaintext secrets into values:
- For constructs representing secret stores (e.g., AWS Secrets Manager, SSM
SecureString, GCP Secret Manager, KubernetesSecret), manifests record a typedSecretRef({"kind": ..., "ref": ...}) instead of the plaintext payload. - Plaintext
Output(sensitive=True)values without an externalSecretRefare redacted (null+"redacted": true) unless--revealis passed explicitly for ephemeral local development (nf run).
Pluggable SecretResolver
netherframe.bindings defines a minimal SecretResolver protocol:
from typing import Any, Mapping, Protocol
class SecretResolver(Protocol):
def supports(self, kind: str) -> bool: ...
def resolve(self, ref: Mapping[str, Any]) -> Any: ...
- Built-in (zero external dependencies):
fileresolver for mounted secret volumes (e.g. Kubernetes projected/CSI volumes, Docker secrets, systemdLoadCredentialpaths). - Optional extras (
netherframe.bindings[aws],[gcp], etc.): Cloud SDK resolvers (aws_secretsmanager,aws_ssm,gcp_secretmanager) loaded only when installed and configured.
Live Secret Reads and Rotation
A secret is not copied onto the service object at startup. Each read of cfg.db_password asks the resolver for the secret its SecretRef names, through a per-secret cache, so a secret that rotates reaches a running process without a restart:
- Static type:
Secret[T]isAnnotated[T, SECRET], the markernetherframe.core.inputsalready uses, socfg.db_passwordis a plainstrto type checkers and to the libraries it is passed to. There is no wrapper type and no.reveal(). - Cache: a resolved value is reused for a TTL (
BindingsConfig.configure(secret_ttl=...), default 5 minutes) and resolved again on the first read after it. Set the TTL below the rotation period. For scale, AWS's Python caching client refreshes every hour by default, and Secrets Manager can rotate as often as every four hours. - Refresh on rejection:
nf.bindings.refresh(cfg, "db_password")drops the cached value, for the moment a database or API rejects a credential before the TTL has passed. - Failure: when a refresh fails, the last resolved value is kept and the refresh is retried with backoff. A secret that has never been resolved raises on read.
- Files: the
fileresolver reads the file again when it has changed. Kubernetes updates a mountedSecretvolume in place (asubPathmount and an environment variable are not updated), and the Secrets Store CSI driver does the same when its rotation is enabled. - Rotation scheme: rotate so that the previous credential stays valid for one more period (the "alternating users" strategy of AWS Secrets Manager). A process then never holds a credential that has already stopped working.
What a live read cannot reach is a copy. A connection pool built with password=cfg.db_password keeps the string it was given. Give such a library a callable where it takes one:
import asyncpg
from sqlalchemy import create_engine, event
from infra.orders import Orders
cfg = Orders.runtime()
async def pool() -> asyncpg.Pool:
# asyncpg calls a password callable each time it opens a connection
return await asyncpg.create_pool(host="orders-db.internal", user="orders", password=lambda: cfg.db_password)
engine = create_engine("postgresql+psycopg://orders@orders-db.internal/orders")
@event.listens_for(engine, "do_connect")
def current_password(dialect, conn_rec, cargs, cparams):
cparams["password"] = cfg.db_password
Only a secret held by reference rotates this way. A plaintext Output(sensitive=True) value is redacted from the manifest and has no store to be read from again.
Masking: repr() of a service object shows each secret export as (secret). A value that has been read out is an ordinary str and prints as one.
5. Local Development Loop (nf run)
Netherframe currently provides nf watch (netherframe.sdk.synthesis), which only re-synthesizes legacy Terraform configurations. Hybrid apps lack an integrated "apply/read state → bind config → run app or tests" command.
nf run closes that loop by pairing Typed Runtime Bindings with Netherframe's existing hybrid state and FakeCloud testing infrastructure:
# Run a local dev server bound to the current `dev` applied state
nf run --app orders ++env=dev -- uvicorn orders.api:app --reload
# Run integration tests against applied infrastructure
nf run --app orders ++env=dev -- pytest tests/integration
# Ephemeral zero-cloud-account local run backed by FakeCloud (AWS)
nf run --local --app orders -- uvicorn orders.api:app --reload
Execution Flow
- Resolve app and deployment inputs via
nf.sdk(Project.run(...)). - With
--local: launch/reuse a FakeCloud account (netherframe.testing.fakecloud; that package depends onpytestand is not a dependency ofnetherframe.sdkornetherframe.clitoday), runplan+applyagainst an ephemeral local state, and collect outputs. Without--local: read current outputs from the app's configured state backend (optionally--applyfirst). - Write the Sealed Runtime Manifest to the project-local
.nf.out/bindings/<app>.json(0600), where the child'snf.bindingsfinds it from its working directory (step 4 of the resolution order).nf runsets nothing in the child's environment and adds nothing to its command line. - Hold a lock on that manifest while the child runs. A second
nf runof the same app in the same project shares the manifest when it would write the same one, and is refused otherwise, naming the process that holds it. - Execute the child command cleanly (forwarding signals and exit code), and remove the manifest when the last
nf runholding it exits.
[!NOTE] Nothing here uses the environment:
nf.core,nf.sdk, thenfCLI andnf.bindingsread noNF_*variable, and the manifest reaches the child by path. For the life of the run the manifest sits in the project's.nf.out/, not in a private temporary directory. With--revealit holds the plaintext of sensitive outputs for that time; a secret held bySecretRefis never written to it.
6. Future Layer: Capability Resource Bindings
Once nf.bindings and Service manifests exist, provider extension packages (netherframe.ext.aws, etc.—keeping netherframe.core strictly provider-neutral) can layer Alchemy-style capability bindings on top without changing the core manifest contract:
# Conceptual Phase 4 API (provider extension package: nf.ext.aws)
# bucket.read_write() pairs:
# 1. Deploy-time IAM policy statements wired into the compute role
# 2. Dependency edge registration in NF's graph
# 3. A runtime descriptor serialized into the manifest (yielding a typed S3 helper)
Because Netherframe already supports @app.check(phase="plan") and nf lint, capability bindings enable organization-wide policy invariants directly over declared capabilities (for example, rejecting any public-facing workload holding a read_write binding to a LifecycleRules(retain=...) database).
7. Package Boundaries, Core Layering, and Compatibility
New Package: netherframe.bindings (nf.bindings)
- Location:
libs/netherframe.bindings/ - Runtime dependencies: Python 3.15+ standard library only (
json,tomllib,dataclasses,typing,pathlib,hashlib). Zero dependency onnetherframe.core,netherframe.sdk,grpcio,libcst,loguru, orrich. - Alias shims: Ships generated
nf/bindings/shims viatools/scripts/generate_nf_alias_shims.pysonf.bindingsandnetherframe.bindingsresolve identically for runtime andty. - Optional extras:
netherframe.bindings[aws],netherframe.bindings[gcp], etc., for cloudSecretResolverimplementations.
Core & CLI Layering Compliance
netherframe.core: Never importsnetherframe.sdkornetherframe.cli. Build-time registration of aServiceclass's exports integrates withnetherframe.core.constructs(App,Stack,Output) andnetherframe.core.inputsusinglazyimports where appropriate soimport netherframe.coreretains its minimal startup footprint (test_core_layering.py,test_package_exports.py).netherframe.sdk: ExposesProject.export(...),Project.exports(...),Project.run(...), andRunReport.export(...)first (AsyncProjectparity included).netherframe.cli: Addsnf exportandnf runas lazy commands (test_lazy_commands.py) backed strictly bynf.sdk(test_sdk_parity.py).
Interaction with Existing Netherframe Features
- Saved plans (
--out/--plan-file): Saved plans recordsemantics["exports"](export names, sensitivity flags, andschema_digest).nf apply --plan-fileverifies that aServiceclass's exports match the reviewed plan. - PostgreSQL Graph State (
PostgreSQLGraphBackend): Outputs and manifest emission read committednf_outputsrows under the same consistency guarantees as document backends. - Legacy compatibility (
nf synth): Because aServiceclass's exports become standardOutputconstructs on the stack,nf synthcontinues to emit valid Terraform output blocks without special-casing. nf destroy: Destroying an app invalidates/removes local.nf.out/bindings/<app>.jsonmanifests (while leaving retained-resource outputs in state consistent withLifecycleRules(retain=...)).
Phased Implementation Plan
Phase 1: netherframe.bindings, Sealed Manifest, and nf export
- Create
libs/netherframe.bindings/(zero-dependency runtime loader, manifest dataclass, path-based manifest discovery,SecretRef,fileSecretResolver, live secret reads with a TTL cache andrefresh,nf/alias shims). - Implement
Project.export(...)andRunReport.outputsschema extraction innetherframe.sdk. - Add
nf exportsupportingjson,toml,env,k8s-configmap, andpy-stub. - Enforce fail-closed
output_is_sensitivetaint checking on exports.
Phase 2: Service, export(), and Write-Only Exports
- Implement
Serviceandexport()innetherframe.bindingswith optional build-time hook intonetherframe.core(vialazyimport only when instantiated for infra build). - Enforce write-only exports in
Service: a read while the service is built raises, and anexport(...)never assigned to an attribute fails the build. - Integrate
Serviceparameter extraction withnetherframe.core.inputsand app loading (load_app_from_spec). - Add golden type-check fixtures for
ty, mypy and pyright.
Phase 3: nf run and Cloud SecretResolver Extras
- Implement
Project.run(...)innetherframe.sdkandnf runinnetherframe.cli, with the project-local manifest held under a lock and nothing set in the child's environment. - Add
--localFakeCloud integration for zero-cloud-account local development. - Ship optional
SecretResolverplugins (aws_secretsmanager,aws_ssm,gcp_secretmanager).
Phase 4: Provider-Extension Capability Bindings
- Define capability binding protocols in
netherframe.core/netherframe.bindingswithout adding cloud-specific logic to core. - Implement initial capability bindings (
S3Bucket,SqsQueue,DynamodbTable) innetherframe.ext.aws.
Verification Strategy
- Static typing golden tests: Mirror
libs/netherframe.generation/tests/golden/usage.pyusingtyto verify validOrders.runtime(),@Orders.inject,RunReport.export(Orders), and expected# expect:errors on mismatched field types,Secret[T]violations and misspelled export names. Check the fixtures under mypy and pyright as well: the three checkers do not solveexport()'s type parameter the same way. - Container isolation test: Spawn a fresh Python 3.15 interpreter with
netherframe.core,grpcio,libcst,loguru, andrichabsent/blocked onsys.meta_pathand verifyfrom infra.orders import Orders; cfg = Orders.runtime(...)succeeds cleanly. - Fail-closed security tests: Verify
ValidationErrorwhen a sensitive-taintedRuntimeValueflows intoexport(val)withoutsensitive=True, and verify plaintext secrets never appear injson/toml/k8s-configmapmanifests without--reveal. - Write-only export tests: Verify that reading, comparing, formatting or passing on
self.<export>while a service is built raisesTypeError, thatexport(table.ref_id_ + "-dlq")evaluates correctly in hybrid apply, and that anexport(...)never assigned to an attribute fails the build. - Rotation tests: With a resolver whose secret changes, verify that a running process reads the new value after the TTL and at once after
refresh, that thefileresolver follows a replaced file, and that a failed refresh keeps the last value. - Discovery tests: Verify the resolution order and the error that names each place looked, that no environment variable changes the result, and that a second
nf runof an app with different inputs is refused. - Workspace invariants: Run
test_core_layering.py,test_package_exports.py,test_lazy_commands.py,test_sdk_parity.py, andgenerate_nf_alias_shims.pychecks.
Open Questions
- Multi-stack
Serviceapps: When a singleServiceclass creates multipleStacks, should exported attributes default to flat app-level names (requiring unique attribute names onself) or support nested stack namespaces? nf_autoidin service modules: A module that starts with# coding: nf_autoidcannot be imported without the codec, and with it importslibcst. Should service modules passnf_idexplicitly (as the example does), or shouldnetherframe.bindingsregister a pass-throughnf_autoidcodec for processes that never run__init__?