Skip to content

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:

  1. A zero-codegen monorepo authoring surface (Service + export() + Python 3.15 lazy imports) where a single Python class defines infrastructure, automatically registers typed Output constructs, and serves as the static runtime config interface for application code—requiring no separate *Runtime schema dataclass.
  2. A portable sealed runtime manifest and nf export command (netherframe.bindings / nf.bindings), enabling zero-dependency startup loading in containers, standalone typed stub generation for multi-repo or existing App/Output projects, and fail-closed secret handling via SecretRef descriptors that a running process reads again as secrets rotate.
  3. 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 CLI argv or in plaintext saved plans.
  • Teardown[T] inputs are verified not to alter deployment shape.
  • Applied deployment inputs are persisted in state so nf destroy always 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) accepts value: Any with no typed consumer handle.
  • RunReport.outputs() (netherframe.sdk.run_reports) returns an untyped dict[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 Service class with full ty/pyright/mypy checking and IDE autocomplete.
  • Zero engine bloat in application containers: Application processes importing runtime bindings must require only a tiny zero-dependency package (netherframe.bindings), never netherframe.core, grpcio, libcst, loguru, rich, or generated provider packages.
  • First-class support for multi-repo and existing apps: Existing def app() -> App modules with Output(...) constructs must gain the same runtime manifest and generated typed stubs (nf export) without rewriting to a Service class.
  • Fail-closed secret hygiene: Secrets must never silently flow into non-secret outputs or plaintext runtime config files; manifests carry typed SecretRef pointers that the application process resolves.
  • Rotation without a restart: A secret that rotates reaches a running process: secrets are read through their SecretRef each time they are used, not copied at startup.
  • No environment variables: Preserve Netherframe's explicit configuration model (Configuration) across nf export, nf.bindings, and nf run: a manifest is found by path, and nf run sets nothing in its child's environment.
  • API-first parity: Every command and option lands in nf.sdk first before CLI wiring (test_sdk_parity).

Non-Goals

  • No Effect/monadic DSL: Netherframe will not adopt an Effect-TS-style monadic programming model; Service builds cleanly on Netherframe's construct tree, RuntimeValue[T], @hybrid_runtime, and NfError.
  • No weakening of the plan/apply wall: Immutable saved plans, final-plan consistency checks, and deterministic RuntimeValue evaluation 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 as netherframe.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:

  1. Input extraction: The app loader inspects Orders.__init__ using the same parameter, dataclass-group, Secret[T], and Teardown[T] machinery in netherframe.core.inputs.
  2. Build execution: The loader instantiates Orders(*resolved_args, **resolved_kwargs) inside an active App/Stack capture scope.
  3. Automatic Output registration: export(...) returns a marker holding the value, its sensitivity and description, and the stack that is active when it is called. Service records 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 an Output(nf_id=attr_name, value=marker.value, sensitive=marker.sensitive, description=marker.description) on the marker's stack (or designated export stack). Repeating nf_id is unnecessary. An export(...) result that was never assigned to an attribute fails the build.
  4. Schema recording: Service records the export contract (field names, declared/inferred Python types, sensitivity flags, and input schema) on App metadata (semantics["exports"] in saved plans).
  5. Typed SDK consumption: RunReport.export(Orders) and Project.exports(Orders, app="orders") hydrate and return a real Orders instance populated from applied outputs.

Application-Runtime Lifecycle

When application code executes from infra.orders import Orders and calls Orders.runtime() in production:

  1. Because nf.core and nf.providers.* are imported via Python 3.15 lazy from statements, importing infra.orders does not load netherframe.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")), imports netherframe.core at that point and raises ModuleNotFoundError in a container.
  2. Orders.runtime() allocates the instance via object.__new__(Orders)—never calling Orders.__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 from values and a secret through the configured SecretResolver (see Live Secret Reads and Rotation). An attribute the manifest does not hold raises AttributeError, naming the app and the export.
  3. 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(), in and iteration raise TypeError.
  • 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 scans self.__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 misspelled cfg.tabel_name has 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:

  1. The exports a Service class records (when present), or
  2. Provider resource output schemas (RuntimeValue[T] / GetProviderSchema types) and output_is_sensitive tainting on each Output construct.

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:

  1. An explicit manifest: Path | Mapping[str, Any] argument passed by the caller.
  2. <app>.json in the directory given to BindingsConfig.configure(directory=...) at the process entrypoint.
  3. <app>.json in the fixed directory /run/nf/bindings/, where a container mounts its manifests.
  4. The project-local .nf.out/bindings/<app>.json, in the nearest directory at or above the working directory whose pyproject.toml has a [tool.nf] table (local nf run and 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 ConfigMap that carries the manifest as a volume at /run/nf/bindings/. Mount the directory, not a single file with subPath: a subPath mount 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 RuntimeValue via export(val) without sensitive=True fails closed during planning (ValidationError) rather than silently emitting the secret into values or a ConfigMap.
  • Similarly, for plain Output(...) constructs, any tainted value not marked sensitive=True is refused by nf 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, Kubernetes Secret), manifests record a typed SecretRef ({"kind": ..., "ref": ...}) instead of the plaintext payload.
  • Plaintext Output(sensitive=True) values without an external SecretRef are redacted (null + "redacted": true) unless --reveal is 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): file resolver for mounted secret volumes (e.g. Kubernetes projected/CSI volumes, Docker secrets, systemd LoadCredential paths).
  • 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] is Annotated[T, SECRET], the marker netherframe.core.inputs already uses, so cfg.db_password is a plain str to 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 file resolver reads the file again when it has changed. Kubernetes updates a mounted Secret volume in place (a subPath mount 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

  1. Resolve app and deployment inputs via nf.sdk (Project.run(...)).
  2. With --local: launch/reuse a FakeCloud account (netherframe.testing.fakecloud; that package depends on pytest and is not a dependency of netherframe.sdk or netherframe.cli today), run plan + apply against an ephemeral local state, and collect outputs. Without --local: read current outputs from the app's configured state backend (optionally --apply first).
  3. Write the Sealed Runtime Manifest to the project-local .nf.out/bindings/<app>.json (0600), where the child's nf.bindings finds it from its working directory (step 4 of the resolution order). nf run sets nothing in the child's environment and adds nothing to its command line.
  4. Hold a lock on that manifest while the child runs. A second nf run of 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.
  5. Execute the child command cleanly (forwarding signals and exit code), and remove the manifest when the last nf run holding it exits.

[!NOTE] Nothing here uses the environment: nf.core, nf.sdk, the nf CLI and nf.bindings read no NF_* 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 --reveal it holds the plaintext of sensitive outputs for that time; a secret held by SecretRef is 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 on netherframe.core, netherframe.sdk, grpcio, libcst, loguru, or rich.
  • Alias shims: Ships generated nf/bindings/ shims via tools/scripts/generate_nf_alias_shims.py so nf.bindings and netherframe.bindings resolve identically for runtime and ty.
  • Optional extras: netherframe.bindings[aws], netherframe.bindings[gcp], etc., for cloud SecretResolver implementations.

Core & CLI Layering Compliance

  • netherframe.core: Never imports netherframe.sdk or netherframe.cli. Build-time registration of a Service class's exports integrates with netherframe.core.constructs (App, Stack, Output) and netherframe.core.inputs using lazy imports where appropriate so import netherframe.core retains its minimal startup footprint (test_core_layering.py, test_package_exports.py).
  • netherframe.sdk: Exposes Project.export(...), Project.exports(...), Project.run(...), and RunReport.export(...) first (AsyncProject parity included).
  • netherframe.cli: Adds nf export and nf run as lazy commands (test_lazy_commands.py) backed strictly by nf.sdk (test_sdk_parity.py).

Interaction with Existing Netherframe Features

  • Saved plans (--out / --plan-file): Saved plans record semantics["exports"] (export names, sensitivity flags, and schema_digest). nf apply --plan-file verifies that a Service class's exports match the reviewed plan.
  • PostgreSQL Graph State (PostgreSQLGraphBackend): Outputs and manifest emission read committed nf_outputs rows under the same consistency guarantees as document backends.
  • Legacy compatibility (nf synth): Because a Service class's exports become standard Output constructs on the stack, nf synth continues to emit valid Terraform output blocks without special-casing.
  • nf destroy: Destroying an app invalidates/removes local .nf.out/bindings/<app>.json manifests (while leaving retained-resource outputs in state consistent with LifecycleRules(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, file SecretResolver, live secret reads with a TTL cache and refresh, nf/ alias shims).
  • Implement Project.export(...) and RunReport.outputs schema extraction in netherframe.sdk.
  • Add nf export supporting json, toml, env, k8s-configmap, and py-stub.
  • Enforce fail-closed output_is_sensitive taint checking on exports.

Phase 2: Service, export(), and Write-Only Exports

  • Implement Service and export() in netherframe.bindings with optional build-time hook into netherframe.core (via lazy import only when instantiated for infra build).
  • Enforce write-only exports in Service: a read while the service is built raises, and an export(...) never assigned to an attribute fails the build.
  • Integrate Service parameter extraction with netherframe.core.inputs and 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(...) in netherframe.sdk and nf run in netherframe.cli, with the project-local manifest held under a lock and nothing set in the child's environment.
  • Add --local FakeCloud integration for zero-cloud-account local development.
  • Ship optional SecretResolver plugins (aws_secretsmanager, aws_ssm, gcp_secretmanager).

Phase 4: Provider-Extension Capability Bindings

  • Define capability binding protocols in netherframe.core / netherframe.bindings without adding cloud-specific logic to core.
  • Implement initial capability bindings (S3Bucket, SqsQueue, DynamodbTable) in netherframe.ext.aws.

Verification Strategy

  • Static typing golden tests: Mirror libs/netherframe.generation/tests/golden/usage.py using ty to verify valid Orders.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 solve export()'s type parameter the same way.
  • Container isolation test: Spawn a fresh Python 3.15 interpreter with netherframe.core, grpcio, libcst, loguru, and rich absent/blocked on sys.meta_path and verify from infra.orders import Orders; cfg = Orders.runtime(...) succeeds cleanly.
  • Fail-closed security tests: Verify ValidationError when a sensitive-tainted RuntimeValue flows into export(val) without sensitive=True, and verify plaintext secrets never appear in json/toml/k8s-configmap manifests without --reveal.
  • Write-only export tests: Verify that reading, comparing, formatting or passing on self.<export> while a service is built raises TypeError, that export(table.ref_id_ + "-dlq") evaluates correctly in hybrid apply, and that an export(...) 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 the file resolver 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 run of 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, and generate_nf_alias_shims.py checks.

Open Questions

  1. Multi-stack Service apps: When a single Service class creates multiple Stacks, should exported attributes default to flat app-level names (requiring unique attribute names on self) or support nested stack namespaces?
  2. nf_autoid in service modules: A module that starts with # coding: nf_autoid cannot be imported without the codec, and with it imports libcst. Should service modules pass nf_id explicitly (as the example does), or should netherframe.bindings register a pass-through nf_autoid codec for processes that never run __init__?