Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(appsync): execute GraphQL with graphql-core instead of regex (#1563)
Jacob Schooleyaf9c78aeefc9
diff --git a/Dockerfile b/Dockerfileindex 6e9f460b..889ec026 100644--- a/Dockerfile+++ b/Dockerfile@@ -16,6 +16,7 @@ RUN pip install --no-cache-dir --no-compile \"asyncssh>=2.14" \"boto3>=1.34" \"jsonata-python>=0.7.0" \+ "graphql-core==3.2.12" \"awscli==1.45.63"# Strip awscli help examples (~25 MB) and Python cache files (~15 MB).diff --git a/ministack/app.py b/ministack/app.pyindex 8575d353..81e582bf 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -209,7 +209,10 @@ class _ErrorModule:)def get_state(self):- return {}+ # None, not {}. This module never loaded, so it has no state — and+ # writing an empty dict here would overwrite whatever the last working+ # run persisted, losing every resource the service held.+ return Nonedef restore_state(self, data):passdiff --git a/ministack/core/appsync_graphql.py b/ministack/core/appsync_graphql.pynew file mode 100644index 00000000..2e33fe1e--- /dev/null+++ b/ministack/core/appsync_graphql.py@@ -0,0 +1,138 @@+"""GraphQL execution for AppSync.++The data plane used to match the query with a regex and split the body with more+regex — no schema, no validation, no execution algorithm. That capped how+correct it could be: fragments, aliases, `@skip`/`@include`, introspection,+variable coercion and validation are not things a regex can do, and each new+client shape found a new way to be mis-parsed.++This runs the real algorithm with graphql-core — the reference implementation+port — against the SDL the API already stores, and hands each field to a+resolver callback that dispatches into the existing data source handlers.++The schema is built once per API and cached against the SDL it came from, so a+schema change invalidates it and nothing else pays for the parse.+"""++from __future__ import annotations++import logging++from graphql import (+ GraphQLError,+ GraphQLSchema,+ build_schema,+ execute_sync,+ parse,+ validate,+)+from graphql.execution import ExecutionResult++logger = logging.getLogger("appsync")++# AppSync's own scalars and auth directives are not in the GraphQL spec, so a+# schema using them will not build without declarations. Declaring them is the+# only accommodation the real engine needs.+APPSYNC_PRELUDE = """+scalar AWSDate+scalar AWSTime+scalar AWSDateTime+scalar AWSTimestamp+scalar AWSEmail+scalar AWSJSON+scalar AWSURL+scalar AWSPhone+scalar AWSIPAddress++directive @aws_subscribe(mutations: [String!]!) on FIELD_DEFINITION+directive @aws_auth(cognito_groups: [String!]) on FIELD_DEFINITION | OBJECT+directive @aws_cognito_user_pools(cognito_groups: [String!]) on FIELD_DEFINITION | OBJECT+directive @aws_api_key on FIELD_DEFINITION | OBJECT+directive @aws_iam on FIELD_DEFINITION | OBJECT+directive @aws_oidc on FIELD_DEFINITION | OBJECT+directive @aws_lambda on FIELD_DEFINITION | OBJECT+"""++# api_id -> (sdl_fingerprint, schema)+_schema_cache: dict = {}+++class SchemaUnavailable(Exception):+ """The API has no usable schema, so nothing can be validated or executed."""+++def build_api_schema(api_id: str, sdl: str) -> GraphQLSchema:+ """Build (and cache) the executable schema for an API."""+ key = (len(sdl), hash(sdl))+ cached = _schema_cache.get(api_id)+ if cached and cached[0] == key:+ return cached[1]+ try:+ schema = build_schema(APPSYNC_PRELUDE + sdl, assume_valid_sdl=True)+ except GraphQLError as exc:+ raise SchemaUnavailable(f"Schema could not be built: {exc.message}") from exc+ _schema_cache[api_id] = (key, schema)+ return schema+++def forget_schema(api_id: str | None = None):+ """Drop a cached schema — on schema replacement, API deletion, or reset."""+ if api_id is None:+ _schema_cache.clear()+ else:+ _schema_cache.pop(api_id, None)+++def _as_appsync_errors(errors):+ """Render graphql-core errors the way AppSync renders them."""+ out = []+ for err in errors or []:+ original = getattr(err, "original_error", None)+ entry = {"message": err.message}+ if err.path:+ entry["path"] = list(err.path)+ if err.locations:+ entry["locations"] = [+ {"line": loc.line, "column": loc.column} for loc in err.locations+ ]+ # A resolver that raised through util.error carries its own type, which+ # clients switch on; keep it rather than flattening to a message.+ error_type = getattr(original, "error_type", None)+ if error_type:+ entry["errorType"] = error_type+ data = getattr(original, "data", None)+ if data is not None:+ entry["data"] = data+ out.append(entry)+ return out+++def execute(api_id, sdl, query, variables, operation_name, field_resolver, context):+ """Parse, validate and execute one operation.++ `field_resolver(source, info, **args)` is called for every field, and is+ where AppSync's resolvers are dispatched. Returns (data, errors) with errors+ already in AppSync's shape.+ """+ schema = build_api_schema(api_id, sdl)++ try:+ document = parse(query)+ except GraphQLError as exc:+ return None, _as_appsync_errors([exc])++ # Validation is the step the regex could never do: an unknown field or a+ # mistyped variable is refused here instead of resolving to null.+ errors = validate(schema, document)+ if errors:+ return None, _as_appsync_errors(errors)++ result: ExecutionResult = execute_sync(+ schema,+ document,+ variable_values=variables or {},+ operation_name=operation_name,+ context_value=context,+ field_resolver=field_resolver,+ )+ return result.data, _as_appsync_errors(result.errors)diff --git a/ministack/core/persistence.py b/ministack/core/persistence.pyindex 4d85ea9f..3ccac0e6 100644--- a/ministack/core/persistence.py+++ b/ministack/core/persistence.py@@ -197,9 +197,21 @@ def load_state(service: str) -> dict | None:def save_all(services: dict) -> None:- """Save all service states. services = {name: get_state_fn}"""+ """Save all service states. services = {name: get_state_fn}++ A service that returns None has nothing to save and is skipped. That is not+ the same as returning empty state: a module that failed to import has no+ state to report, and writing its empty dict would destroy whatever was+ persisted from the last run that worked.+ """for name, get_state in services.items():try:- save_state(name, get_state())+ state = get_state()except Exception as e:logger.error("Persistence: error getting state for %s: %s", name, e)+ continue+ if state is None:+ logger.debug("Persistence: %s reported no state; leaving %s.json alone",+ name, name)+ continue+ save_state(name, state)diff --git a/ministack/services/appsync.py b/ministack/services/appsync.pyindex 72dfc2bc..36dc3737 100644--- a/ministack/services/appsync.py+++ b/ministack/services/appsync.py@@ -267,6 +267,8 @@ def _delete_graphql_api(api_id):_functions.pop(api_id, None)_schemas.pop(api_id, None)_caches.pop(api_id, None)+ from ministack.core import appsync_graphql+ appsync_graphql.forget_schema(api_id)_cache_entries.pop(api_id, None)_tags.pop(arn, None)@@ -560,6 +562,8 @@ def _start_schema_creation(api_id, body):elif isinstance(definition, (bytes, bytearray)):definition = definition.decode("utf-8", "replace")+ from ministack.core import appsync_graphql+ appsync_graphql.forget_schema(api_id)_schemas[api_id] = {"definition": definition,"status": "SUCCESS",@@ -1153,6 +1157,9 @@ def reset():_caches.clear()_cache_entries.clear()# Drop the JS worker so its compiled-module cache does not outlive a reset.+ from ministack.core import appsync_graphql, appsync_js+ appsync_js.reset()+ appsync_graphql.forget_schema()from ministack.core import appsync_jsappsync_js.reset()_tags.clear()@@ -1368,6 +1375,110 @@ def _unauthorized_response():})+# Off by default: ministack has no authentication of its own by design, and a+# suite written against the permissive behaviour would start failing. Set+# APPSYNC_ENFORCE_AUTH=1 to have an API refuse a caller that satisfies none of+# its configured providers, the way AWS does — which is what makes an+# authorization test meaningful.+_ENFORCE_AUTH = os.environ.get("APPSYNC_ENFORCE_AUTH", "0") not in ("0", "", "false", "False")+++def _auth_modes(api):+ """Every authentication type the API accepts."""+ modes = {api.get("authenticationType") or "API_KEY"}+ for extra in api.get("additionalAuthenticationProviders") or []:+ t = extra.get("authenticationType") if isinstance(extra, dict) else extra+ if t:+ modes.add(t)+ return modes+++def _request_is_authenticated(api_id, api, request_headers):+ """Whether the request satisfies any of the API's configured providers.++ AppSync accepts a request if any one provider accepts it. Credentials are+ not verified here — ministack issued these tokens and does not check+ signatures — but a request carrying nothing at all matches no provider, and+ that is the case worth refusing: it is the one that makes an authorization+ test pass no matter what the resolvers do.+ """+ headers = {str(k).lower(): v for k, v in (request_headers or {}).items()}+ modes = _auth_modes(api)+ auth = str(headers.get("authorization") or "")++ if "API_KEY" in modes:+ supplied = headers.get("x-api-key")+ if supplied and supplied in (_api_keys.get(api_id) or {}):+ return True+ if {"AMAZON_COGNITO_USER_POOLS", "OPENID_CONNECT"} & modes:+ # A bearer token, as distinct from a SigV4 credential.+ if auth and not auth.startswith("AWS4-HMAC-SHA256"):+ return True+ if "AWS_IAM" in modes and auth.startswith("AWS4-HMAC-SHA256"):+ return True+ if "AWS_LAMBDA" in modes and api.get("lambdaAuthorizerConfig"):+ # The authorizer runs below and may still reject.+ return True+ return False+++def _execute_with_schema(api_id, sdl, query, variables, operation_name, request_headers):+ """Execute against the API's schema with the real GraphQL algorithm."""+ from ministack.core import appsync_graphql++ api = _apis.get(api_id, {})+ identity = None+ if api.get("userPoolConfig"):+ identity = _cognito_identity(api, request_headers)+ if api.get("lambdaAuthorizerConfig"):+ try:+ identity = _invoke_lambda_authorizer(+ api_id, api["lambdaAuthorizerConfig"], request_headers,+ query=query, variables=variables, operation_name=operation_name)+ except _AuthorizerRejected:+ return _unauthorized_response()++ appended = []++ def field_resolver(source, info, **args):+ """Called for every field graphql-core resolves."""+ type_name = info.parent_type.name+ field_name = info.field_name++ resolver = (_resolvers.get(api_id) or {}).get(type_name, {}).get(field_name)+ if resolver is None:+ # No resolver on this field: read it off the parent, which is how+ # AppSync resolves a plain attribute of a returned object.+ if isinstance(source, dict):+ return source.get(field_name)+ return getattr(source, field_name, None)++ return _resolve_field(+ api_id, resolver, args, [], variables,+ field_name=field_name,+ identity=identity,+ request_headers=request_headers,+ source=source if isinstance(source, dict) else {},+ appended_errors=appended,+ type_name=type_name,+ )++ try:+ data, errors = appsync_graphql.execute(+ api_id, sdl, query, variables, operation_name, field_resolver, None)+ except appsync_graphql.SchemaUnavailable as exc:+ return _json(200, {"data": None, "errors": [{"message": str(exc)}]})++ # util.appendError is non-fatal and rides alongside the data.+ for a in appended:+ errors.append({"message": a.get("message"), "errorType": a.get("errorType")})++ body = {"data": data}+ if errors:+ body["errors"] = errors+ return _json(200, body)++def _execute_graphql(api_id, data, request_headers=None):"""Execute a GraphQL query/mutation against the configured resolvers."""query = data.get("query", "")@@ -1380,6 +1491,20 @@ def _execute_graphql(api_id, data, request_headers=None):if api_id not in _apis:return _json(404, {"errors": [{"message": f"API {api_id} not found"}]})+ # Applied before either execution path, so it does not depend on whether the+ # API has a schema.+ if _ENFORCE_AUTH and not _request_is_authenticated(+ api_id, _apis.get(api_id, {}), request_headers or {}):+ return _unauthorized_response()++ # A schema means the real engine: parse, validate, execute. The regex path+ # below is kept only for an API that has no schema yet, where there is+ # nothing to validate against.+ sdl = (_schemas.get(api_id) or {}).get("definition")+ if sdl:+ return _execute_with_schema(+ api_id, sdl, query, variables, operation_name, request_headers or {})+# Parse the top-level operation# Strip __typename fields — Amplify adds these everywherequery_clean = _re.sub(r'__typename\s*', '', query)diff --git a/pyproject.toml b/pyproject.tomlindex b8230ca9..2d3af933 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -37,6 +37,10 @@ dependencies = [# documents Step Functions as implementing per the JSONata 2.0.6 spec. Pure# Python, no transitive dependencies."jsonata-python>=0.7.0",+ # AppSync queries are parsed, validated and executed by the reference Python+ # GraphQL implementation rather than by regular expressions. Pure Python, no+ # transitive dependencies. Pinned: a parser change is a behaviour change.+ "graphql-core==3.2.12",][project.optional-dependencies]diff --git a/tests/test_appsync.py b/tests/test_appsync.pyindex 265820db..dd26d9ac 100644--- a/tests/test_appsync.py+++ b/tests/test_appsync.py@@ -1317,6 +1317,15 @@ def test_appsync_deleting_an_api_releases_its_cache(appsync):assert e.value.response["Error"]["Code"] == "NotFoundException"+def _graphql(api_id, api_key, query, variables=None):+ """POST a query to the API's data plane the way an SDK would."""+ import requests as _rq+ payload = {"query": query}+ if variables is not None:+ payload["variables"] = variables+ r = _rq.post(f"{_ENDPOINT}/v1/apis/{api_id}/graphql",+ headers={"x-api-key": api_key, "content-type": "application/json"},+ json=payload, timeout=15)def _graphql(api_id, api_key, query):"""POST a query to the API's data plane the way an SDK would."""import requests as _rq@@ -1885,6 +1894,99 @@ def test_appsync_js_aliased_utils_import_binds(appsync):got = _graphql(api_id, key, '{ ping }')["data"]["ping"]assert got["id"] == 36assert got["hasRuntime"] == "function"+++_GC_SDL = """+type Thing { id: ID! label: String owner: String }+type Query { getThing(id: ID!): Thing echo(n: Int): Int }+type Mutation { makeThing(input: MakeInput!): Thing }+input MakeInput { label: String! }+schema { query: Query mutation: Mutation }+"""+++def _gc_api(appsync, name):+ api_id, key = _js_api(appsync, name)+ appsync.start_schema_creation(apiId=api_id, definition=_GC_SDL.encode())+ _js_resolver(appsync, api_id, "getThing", """+ export function request(ctx) { return { payload: { id: ctx.args.id } } }+ export function response(ctx) { return ctx.result }+ """)+ appsync.create_resolver(+ apiId=api_id, typeName="Thing", fieldName="label", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { return { payload: 'L-' + ctx.source.id } }+ export function response(ctx) { return ctx.result }+ """)+ return api_id, key+++def test_appsync_graphql_field_alias(appsync):+ """`a: getThing(...)` — the response is keyed by the alias, not the field."""+ api_id, key = _gc_api(appsync, "qa-gc-alias")+ out = _graphql(api_id, key, '{ a: getThing(id: "t1") { id } }')+ assert out["data"]["a"]["id"] == "t1", out+++def test_appsync_graphql_fragments(appsync):+ """A named fragment and an inline fragment both contribute their fields."""+ api_id, key = _gc_api(appsync, "qa-gc-frag")+ out = _graphql(api_id, key, """+ { getThing(id: "t1") { ...F ... on Thing { label } } }+ fragment F on Thing { id }+ """)+ assert out["data"]["getThing"]["id"] == "t1", out+ assert out["data"]["getThing"]["label"] == "L-t1", out+++def test_appsync_graphql_skip_and_include_directives(appsync):+ """@skip and @include decide whether a field is in the response at all."""+ api_id, key = _gc_api(appsync, "qa-gc-directives")+ out = _graphql(api_id, key,+ 'query($yes: Boolean!, $no: Boolean!) '+ '{ getThing(id: "t1") { id label @include(if: $no) owner @skip(if: $yes) } }',+ {"yes": True, "no": False})+ thing = out["data"]["getThing"]+ assert "label" not in thing, f"@include(if: false) must omit the field: {thing}"+ assert "owner" not in thing, f"@skip(if: true) must omit the field: {thing}"+++def test_appsync_graphql_rejects_an_invalid_query(appsync):+ """A query naming a field the schema does not have is refused, not executed."""+ api_id, key = _gc_api(appsync, "qa-gc-validate")+ out = _graphql(api_id, key, '{ getThing(id: "t1") { nope } }')+ assert out.get("errors"), "an invalid selection must be an error"+ assert "nope" in out["errors"][0]["message"]+ assert not (out.get("data") or {}).get("getThing")+++def test_appsync_graphql_introspection(appsync):+ """__schema is how every client and codegen tool starts."""+ api_id, key = _gc_api(appsync, "qa-gc-introspect")+ out = _graphql(api_id, key, '{ __schema { queryType { name } } }')+ assert out["data"]["__schema"]["queryType"]["name"] == "Query", out+++def test_appsync_graphql_variable_defaults_and_coercion(appsync):+ """A variable default applies, and values coerce to the declared type."""+ api_id, key = _gc_api(appsync, "qa-gc-vars")+ _js_resolver(appsync, api_id, "echo", """+ export function request(ctx) { return { payload: ctx.args.n } }+ export function response(ctx) { return ctx.result }+ """)+ out = _graphql(api_id, key, 'query($n: Int = 42) { echo(n: $n) }')+ assert out["data"]["echo"] == 42, out+++def test_appsync_js_function_early_return_continues_the_pipeline(appsync):+ """earlyReturn in a FUNCTION skips its data source and response — and the+ pipeline continues to the next function.++ AWS: "the data source and response handler are skipped, and the next+ function request handler (or the pipeline resolver response handler if this+ was the last AWS AppSync function) is called."+def test_appsync_js_function_early_return_continues_the_pipeline(appsync):"""earlyReturn in a FUNCTION skips its data source and response — and thepipeline continues to the next function.@@ -1912,6 +2014,7 @@ def test_appsync_js_function_early_return_continues_the_pipeline(appsync):export function request(ctx) { ctx.stash.result = 'SECOND_RAN'; return { payload: 1 } }export function response(ctx) { return ctx.result }""")["functionConfiguration"]["functionId"]+appsync.create_resolver(apiId=api_id, typeName="Query", fieldName="chain", kind="PIPELINE",runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},@@ -1923,6 +2026,12 @@ def test_appsync_js_function_early_return_continues_the_pipeline(appsync):out = _graphql(api_id, key, '{ chain }')assert out["data"]["chain"] == "SECOND_RAN", \f"a function's earlyReturn must not end the pipeline: {out}"+++def test_appsync_js_resolver_early_return_still_runs_the_response(appsync):+ """earlyReturn in the pipeline RESOLVER's request skips the functions, and+ the resolver's own response handler still runs.+def test_appsync_js_resolver_early_return_still_runs_the_response(appsync):"""earlyReturn in the pipeline RESOLVER's request skips the functions, andthe resolver's own response handler still runs.@@ -1951,6 +2060,8 @@ def test_appsync_js_resolver_early_return_still_runs_the_response(appsync):out = _graphql(api_id, key, '{ chain }')assert out["data"]["chain"] == "RESPONSE_RAN", \f"the resolver's response must still run, and the functions must not: {out}"++def test_appsync_js_early_return_skip_to_end(appsync):"""skipTo: 'END' from a function skips the rest of the pipeline and goesstraight to the resolver's response handler."""@@ -1982,6 +2093,8 @@ def test_appsync_js_early_return_skip_to_end(appsync):""")out = _graphql(api_id, key, '{ chain }')assert out["data"]["chain"] == "ENDED", f"skipTo END must stop the pipeline: {out}"++def test_appsync_js_pipeline_response_sees_ctx_result(appsync):"""A pipeline resolver's response handler gets ctx.result as well asctx.prev.result — AWS documents result as "available only to response@@ -2003,6 +2116,12 @@ def test_appsync_js_pipeline_response_sees_ctx_result(appsync):export function response(ctx) { return ctx.result.v }""")assert _graphql(api_id, key, '{ chain }')["data"]["chain"] == "FROM_FUNCTION"+++def test_appsync_js_lambda_datasource_receives_the_payload_verbatim(appsync, lam):+ """A JS resolver returning {operation: 'Invoke', payload} sends exactly that+ payload as the Lambda event.+def test_appsync_js_lambda_datasource_receives_the_payload_verbatim(appsync, lam):"""A JS resolver returning {operation: 'Invoke', payload} sends exactly thatpayload as the Lambda event.@@ -2013,11 +2132,13 @@ def test_appsync_js_lambda_datasource_receives_the_payload_verbatim(appsync, lam"""import ioimport zipfile+def _zip(src):buf = io.BytesIO()with zipfile.ZipFile(buf, "w") as z:z.writestr("index.py", src)return buf.getvalue()+code = _zip("def handler(e, c):\n"" # Echo the event back so the test can see exactly what arrived.\n"@@ -2051,3 +2172,97 @@ def test_appsync_js_lambda_datasource_receives_the_payload_verbatim(appsync, lamgot = _graphql(api_id, key, '{ echo }')["data"]["echo"]assert got == {"text": ["a", "b"]}, \f"the payload must arrive verbatim, not wrapped in a resolver event: {got}"+++ os.environ.get("APPSYNC_ENFORCE_AUTH", "0") in ("0", "", "false", "False"),+ reason="enforcement is opt-in; run the server with APPSYNC_ENFORCE_AUTH=1")+def test_appsync_cognito_api_refuses_an_unauthenticated_request(appsync, cognito_idp):+ """An API whose auth mode is AMAZON_COGNITO_USER_POOLS refuses a caller with+ no credentials.++ ministack already refuses an unknown API key on this path, so an API that+ declares Cognito should likewise not serve an anonymous caller — otherwise+ every authorization test passes locally regardless of what the resolvers do,+ which is the opposite of useful.+ """+ pool = cognito_idp.create_user_pool(PoolName="qa-authmode-pool")["UserPool"]+ api = appsync.create_graphql_api(+ name="qa-authmode", authenticationType="AMAZON_COGNITO_USER_POOLS",+ userPoolConfig={"userPoolId": pool["Id"], "awsRegion": "us-east-1",+ "defaultAction": "ALLOW"},+ )["graphqlApi"]+ api_id = api["apiId"]+ appsync.create_data_source(apiId=api_id, name="DS", type="NONE")+ appsync.create_resolver(+ apiId=api_id, typeName="Query", fieldName="secret", dataSourceName="DS",+ runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"},+ code="""+ export function request(ctx) { return { payload: 'LEAKED' } }+ export function response(ctx) { return ctx.result }+ """)++ import requests as _rq+ r = _rq.post(f"{_ENDPOINT}/v1/apis/{api_id}/graphql",+ headers={"content-type": "application/json"},+ json={"query": "{ secret }"}, timeout=15)+ assert r.status_code == 401, f"expected 401, got {r.status_code} {r.text[:200]}"+ assert "LEAKED" not in r.text+++def test_appsync_schemaless_api_keeps_lenient_execution(ddb):+ """An API with no schema is executed leniently, exactly as before.++ Validation is a per-API property that appears when a schema does: parsing+ always happens, but a query is only checked against a schema once one has+ been uploaded. Every API created before StartSchemaCreation existed is+ schemaless, so validating those would start rejecting queries that work+ today — this pins that it does not.+ """+ import json+ import urllib.request+ from conftest import make_client++ appsync = make_client("appsync")++ ddb.create_table(+ TableName="schemaless-users",+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )++ api = appsync.create_graphql_api(+ name="schemaless-api", authenticationType="API_KEY")["graphqlApi"]+ api_id = api["apiId"]+ key = appsync.create_api_key(apiId=api_id)["apiKey"]++ appsync.create_data_source(+ apiId=api_id, name="usersDS", type="AMAZON_DYNAMODB",+ dynamodbConfig={"tableName": "schemaless-users", "awsRegion": "us-east-1"},+ )+ appsync.create_resolver(+ apiId=api_id, typeName="Mutation", fieldName="createUser",+ dataSourceName="usersDS",+ )++ # No StartSchemaCreation call — this API has no schema at all.+ assert not appsync.get_graphql_api(apiId=api_id)["graphqlApi"].get("_schema")++ def _post(query):+ req = urllib.request.Request(+ f"{_ENDPOINT}/v1/apis/{api_id}/graphql",+ data=json.dumps({"query": query}).encode(),+ headers={"Content-Type": "application/json", "x-api-key": key["id"]},+ )+ with urllib.request.urlopen(req) as r:+ return json.loads(r.read())++ body = _post('mutation { createUser(input: {id: "u1", name: "Ada"}) { id name } }')+ assert "errors" not in body, body+ assert body["data"]["createUser"]["id"] == "u1", body++ # The decisive half: with a schema this field would be a validation error+ # before any resolver ran. Schemaless, it must still reach the resolver.+ body = _post('mutation { createUser(input: {id: "u2", nope: 1}) { id } }')+ assert body.get("data", {}).get("createUser", {}).get("id") == "u2", bodydiff --git a/tests/test_ministack.py b/tests/test_ministack.pyindex f610a6b0..3fcbeb61 100644--- a/tests/test_ministack.py+++ b/tests/test_ministack.py@@ -804,3 +804,47 @@ def test_boot_sweep_takes_our_predecessor_but_spares_other_instances(fake_dockerassert "ours-previous-run" not in fake_docker.live(), "boot sweep left our own orphan"assert "another-instance" in fake_docker.live(), "boot sweep destroyed another instance's container"+++def test_persistence_keeps_state_when_a_module_fails_to_load():+ """A service that could not import must not overwrite its persisted state.++ A failed import produces a stand-in module with no state. It used to report+ an empty dict, which save_all happily wrote over the file — so one bad boot+ (a missing dependency, a syntax error) silently destroyed every resource the+ service had persisted. Recovering meant recreating them from scratch.+ """+ import json+ import os+ import tempfile++ from ministack.core import persistence++ with tempfile.TemporaryDirectory() as tmp:+ original_dir, original_flag = persistence.STATE_DIR, persistence.PERSIST_STATE+ persistence.STATE_DIR, persistence.PERSIST_STATE = tmp, True+ try:+ path = os.path.join(tmp, "svc.json")+ persistence.save_state("svc", {"things": {"a": 1}})+ assert os.path.exists(path)++ # A module that loaded and genuinely holds nothing still writes.+ persistence.save_all({"svc": lambda: {"things": {}}})+ with open(path) as f:+ assert json.load(f)["payload"] == {"things": {}}++ persistence.save_state("svc", {"things": {"a": 1}})+ # A module that failed to load reports None, and the file survives.+ persistence.save_all({"svc": lambda: None})+ with open(path) as f:+ assert json.load(f)["payload"] == {"things": {"a": 1}}, \+ "a failed module must not overwrite persisted state"+ finally:+ persistence.STATE_DIR, persistence.PERSIST_STATE = original_dir, original_flag+++def test_a_failed_service_module_reports_no_state():+ """The stand-in for a module that would not import reports None."""+ from ministack.app import _ErrorModule++ assert _ErrorModule("appsync", "No module named 'graphql'").get_state() is None