sailfork / t3code-github / .repos/ alchemy-effect/ packages/ alchemy/ test/ apply.test.ts

import { assert, describe, expect } from "@alchemy.run/test";
import * as Test from "@alchemy.run/test/Alchemy";
import { Data, Layer } from "effect";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import { Action } from "@/Action";
import { adopt, AdoptPolicy, OwnedBySomeoneElse, Unowned, Unresolved } from "@/AdoptPolicy";
import { apply, DestroyError } from "@/Apply";
import { isResolved } from "@/Diff";
import * as ProviderLayer from "@/Local/ProviderLayer";
import * as Namespace from "@/Namespace.ts";
import * as Output from "@/Output";
import * as Plan from "@/Plan";
import * as Provider from "@/Provider";
import { remote } from "@/ProviderMode.ts";
import * as RemovalPolicy from "@/RemovalPolicy.ts";
import { renamedFrom } from "@/Rename.ts";
import { Cli } from "@/Report.ts";
import { Resource } from "@/Resource";
import { Stack, make as makeStack } from "@/Stack";
import { Stage } from "@/Stage";
import {
  type ActionState,
  type CreatingResourceState,
  type ReplacedResourceState,
  type ReplacingResourceState,
  type ResourceState,
  State,
  StateStoreError,
} from "@/State";
import {
  AliasedWidget,
  aliasedWidgetDeletes,
  aliasedWidgetProvider,
  ArtifactProbe,
  BindingTarget,
  capturedConfigHost,
  CollisionRegistry,
  DeleteFirstResource,
  DeletedBindingRegressionTarget,
  DurationResource,
  FqnProbe,
  Function,
  inDev,
  KindStablesResource,
  ModalResource,
  modalCalls,
  type ModalResourceProps,
  PhasedTarget,
  ProbeBinding,
  StaticStablesResource,
  TestLayers,
  TestResource,
  TestResourceHooks,
  type TestResourceProps,
} from "./test.resources.ts";

const { test } = Test.make({ providers: TestLayers() });

const getState = Effect.fn(function* <S = ResourceState>(resourceId: string) {
  const state = yield* yield* State;
  const stk = yield* Stack;
  return (yield* state.get({ stack: stk.name, stage: stk.stage, fqn: resourceId })) as S;
});
/** The planned action for a logical id, or `undefined` if it isn't planned. */
const actionOfPlan = (plan: any, logicalId: string) =>
  (Object.values(plan.resources) as any[]).find(
    (node: any) => node.resource.LogicalId === logicalId,
  )?.action;

const listState = Effect.fn(function* () {
  const state = yield* yield* State;
  const stk = yield* Stack;
  return yield* state.list({ stack: stk.name, stage: stk.stage });
});

const recordingCli = (events: Array<{ id: string; status: string }>) =>
  Cli.of({
    startPlanningSession: () =>
      Effect.succeed({
        update: () => Effect.void,
        succeed: () => Effect.void,
        fail: () => Effect.void,
        close: Effect.void,
      }),
    approvePlan: () => Effect.succeed(true),
    displayPlan: () => Effect.void,
    startApplySession: () =>
      Effect.succeed({
        done: () => Effect.void,
        emit: (event) =>
          Effect.sync(() => {
            if (event.type === "apply.resource.status") {
              events.push({ id: event.id, status: event.status });
            }
          }),
      }),
  });

const expectConvergedStatus = (status: ResourceState["status"] | undefined) => {
  expect(["created", "updated"]).toContain(status);
};

// Graceful failure handling means downstream resources of a failed upstream
// may have committed an intermediate "creating"/"replacing" status before
// their `waitForDeps` discovered the upstream failure - or may have fully
// converged using a stable previous output of the failed upstream (e.g. a
// replacement whose old generation is still live). This helper tolerates any
// of those outcomes; the corresponding recovery deploy validates terminal
// state.
const expectNotStarted = (state: ResourceState | undefined) => {
  expect([undefined, "creating", "replacing", "created", "updated"]).toContain(state?.status);
};

export class ResourceFailure extends Data.TaggedError("ResourceFailure")<{ message: string }> {
  constructor() {
    super({ message: `Failed to create` });
  }
}

const hook =
  (hooks?: {
    create?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
    update?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
    delete?: (id: string) => Effect.Effect<void, any>;
    read?: (id: string) => Effect.Effect<any, any>;
  }) =>
  <A, Err, Req>(test: Effect.Effect<A, Err, Req>) =>
    test.pipe(
      Effect.provide(
        Layer.succeed(
          TestResourceHooks,
          hooks ?? {
            create: () => Effect.fail(new ResourceFailure()),
            update: () => Effect.fail(new ResourceFailure()),
            delete: () => Effect.fail(new ResourceFailure()),
            read: () => Effect.succeed(undefined),
          },
        ),
      ),
      // Phase-1 (create/update) failures surface as the raw ResourceFailure;
      // Phase-2 (GC/destroy) delete failures are aggregated into DestroyError.
      // @ts-expect-error - catchTag changes the return type
      Effect.catchTag(["ResourceFailure", "DestroyError"], () => Effect.succeed(true)),
    ) as Effect.Effect<A, Err, Req | State>;

// Helper to fail on specific resource IDs
const failOn = (
  resourceId: string,
  hook: "create" | "update" | "delete",
): {
  create?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
  update?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
  delete?: (id: string) => Effect.Effect<void, any>;
} => ({
  [hook]: (id: string) =>
    id === resourceId ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
});

// Helper to fail on multiple resource IDs for different hooks
const failOnMultiple = (
  failures: Array<{ id: string; hook: "create" | "update" | "delete" }>,
): {
  create?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
  update?: (id: string, props: TestResourceProps) => Effect.Effect<void, any>;
  delete?: (id: string) => Effect.Effect<void, any>;
} => {
  const createFailures = failures.filter((f) => f.hook === "create").map((f) => f.id);
  const updateFailures = failures.filter((f) => f.hook === "update").map((f) => f.id);
  const deleteFailures = failures.filter((f) => f.hook === "delete").map((f) => f.id);

  return {
    create: (id: string) =>
      createFailures.includes(id) ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
    update: (id: string) =>
      updateFailures.includes(id) ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
    delete: (id: string) =>
      deleteFailures.includes(id) ? Effect.fail(new ResourceFailure()) : Effect.succeed(undefined),
  };
};

describe("Action output convergence", { tags: ["unit", "local"] }, () => {
  for (const consumer of ["prop", "binding"] as const) {
    test.provider(
      `unchanged Action ${consumer} consumers stop reconciling after the first deploy`,
      (stack) =>
        Effect.gen(function* () {
          let runs = 0;
          const reconciled: string[] = [];
          const Compute = Action("Compute", (_: {}) =>
            Effect.sync(() => {
              runs++;
              return { value: "v1" };
            }),
          );
          const program = Effect.gen(function* () {
            const result = yield* Compute({});
            if (consumer === "prop") {
              const host = yield* TestResource("Host", { string: result.value });
              return host.string;
            }
            const host = yield* BindingTarget("Host", {});
            yield* host.bind("Result", { env: { RESULT: result.value } });
            return host.env.RESULT;
          });
          yield* Effect.gen(function* () {
            for (const _ of [1, 2, 3]) {
              expect(yield* stack.deploy(program)).toBe("v1");
            }
            expect(runs).toBe(1);
            expect(reconciled).toEqual(["create"]);
            const plan = yield* stack.plan(program);
            expect(actionOfPlan(plan, "Host")).toBe("noop");
          }).pipe(
            Effect.provideService(TestResourceHooks, {
              create: () =>
                Effect.sync(() => {
                  reconciled.push("create");
                }),
              update: () =>
                Effect.sync(() => {
                  reconciled.push("update");
                }),
            }),
          );
        }),
    );
  }

  for (const sameOutput of [false, true]) {
    test.provider(
      `changed Action input ${sameOutput ? "with the same output" : "with a fresh output"} converges after the rerun`,
      (stack) =>
        Effect.gen(function* () {
          let runs = 0;
          const reconciled: (string | undefined)[] = [];
          const Compute = Action("Compute", (input: { revision: string }) =>
            Effect.sync(() => {
              runs++;
              return { value: sameOutput ? "constant" : input.revision };
            }),
          );
          const program = (revision: string) =>
            Effect.gen(function* () {
              const result = yield* Compute({ revision });
              const host = yield* TestResource("Host", { string: result.value });
              return host.string;
            });
          const record = (_: string, props: TestResourceProps) =>
            Effect.sync(() => {
              reconciled.push(props.string);
            });
          yield* Effect.gen(function* () {
            expect(yield* stack.deploy(program("v1"))).toBe(sameOutput ? "constant" : "v1");
            expect(yield* stack.deploy(program("v2"))).toBe(sameOutput ? "constant" : "v2");
            expect(runs).toBe(2);
            if (sameOutput) {
              expect([1, 2]).toContain(reconciled.length);
              expect(reconciled.every((value) => value === "constant")).toBe(true);
            } else {
              expect(reconciled).toEqual(["v1", "v2"]);
            }
            const settledCount = reconciled.length;
            expect(actionOfPlan(yield* stack.plan(program("v2")), "Host")).toBe("noop");
            yield* stack.deploy(program("v2"));
            expect(runs).toBe(2);
            expect(reconciled).toHaveLength(settledCount);
          }).pipe(Effect.provideService(TestResourceHooks, { create: record, update: record }));
        }),
    );
  }

  test.provider(
    "changed Action binding data reaches the host before subsequent deploys converge",
    (stack) =>
      Effect.gen(function* () {
        let runs = 0;
        let reconciles = 0;
        const Compute = Action("Compute", (input: { value: string }) =>
          Effect.sync(() => {
            runs++;
            return input;
          }),
        );
        const program = (value: string) =>
          Effect.gen(function* () {
            const result = yield* Compute({ value });
            const host = yield* BindingTarget("Host", {});
            yield* host.bind("Result", { env: { RESULT: result.value } });
            return host.env.RESULT;
          });
        const record = () =>
          Effect.sync(() => {
            reconciles++;
          });
        yield* Effect.gen(function* () {
          expect(yield* stack.deploy(program("v1"))).toBe("v1");
          expect(yield* stack.deploy(program("v2"))).toBe("v2");
          expect(runs).toBe(2);
          expect(reconciles).toBe(2);
          expect(actionOfPlan(yield* stack.plan(program("v2")), "Host")).toBe("noop");
          expect(yield* stack.deploy(program("v2"))).toBe("v2");
          expect(runs).toBe(2);
          expect(reconciles).toBe(2);
        }).pipe(Effect.provideService(TestResourceHooks, { create: record, update: record }));
      }),
  );

  test.provider(
    "Action chains propagate fresh outputs and stop rerunning once unchanged",
    (stack) =>
      Effect.gen(function* () {
        const runs: string[] = [];
        const Compute = Action("Compute", (input: { value: string }) =>
          Effect.sync(() => {
            runs.push(input.value);
            return { value: `${input.value}!` };
          }),
        );
        const program = (value: string) =>
          Effect.gen(function* () {
            const first = yield* Compute("First", { value });
            const second = yield* Compute("Second", { value: first.value });
            const host = yield* Function("Host", { env: { RESULT: second.value } });
            return host.env.RESULT;
          });
        expect(yield* stack.deploy(program("v1"))).toBe("v1!!");
        expect(yield* stack.deploy(program("v2"))).toBe("v2!!");
        expect(yield* stack.deploy(program("v2"))).toBe("v2!!");
        expect(runs).toEqual(["v1", "v1!", "v2", "v2!"]);
        expect(actionOfPlan(yield* stack.plan(program("v2")), "Host")).toBe("noop");
      }),
  );

  test.provider(
    "binding-only changes to an upstream resource invalidate Action inputs and consumer outputs",
    (stack) =>
      Effect.gen(function* () {
        const seen: string[] = [];
        const Compute = Action("Compute", (input: { value: string }) =>
          Effect.sync(() => {
            seen.push(input.value);
            return input;
          }),
        );
        const program = (value: string) =>
          Effect.gen(function* () {
            const source = yield* BindingTarget("Source", {});
            yield* source.bind("Value", { env: { RESULT: value } });
            const result = yield* Compute({ value: source.env.RESULT });
            const host = yield* Function("Host", { env: { RESULT: result.value } });
            return host.env.RESULT;
          });
        expect(yield* stack.deploy(program("v1"))).toBe("v1");
        const changed = yield* stack.plan(program("v2"));
        expect(changed.resources.Source.action).toBe("update");
        expect(changed.actions.Compute.action).toBe("run");
        expect(changed.resources.Host.action).toBe("update");
        expect(yield* stack.deploy(program("v2"))).toBe("v2");
        expect(yield* stack.deploy(program("v2"))).toBe("v2");
        expect(seen).toEqual(["v1", "v2"]);
        expect(actionOfPlan(yield* stack.plan(program("v2")), "Host")).toBe("noop");
      }),
  );

  test.provider(
    "an Action planned to run skips its body when upstream resolves to the same input",
    (stack) =>
      Effect.gen(function* () {
        let firstRuns = 0;
        let secondRuns = 0;
        const First = Action("First", (_: { revision: string }) =>
          Effect.sync(() => {
            firstRuns++;
            return { value: "constant" };
          }),
        );
        const Second = Action("Second", (input: { value: string }) =>
          Effect.sync(() => {
            secondRuns++;
            return { value: `${input.value}!` };
          }),
        );
        const program = (revision: string) =>
          Effect.gen(function* () {
            const first = yield* First({ revision });
            const second = yield* Second({ value: first.value });
            const host = yield* Function("Host", { env: { RESULT: second.value } });
            return host.env.RESULT;
          });
        expect(yield* stack.deploy(program("v1"))).toBe("constant!");
        const changed = yield* stack.plan(program("v2"));
        expect(changed.actions.First.action).toBe("run");
        expect(changed.actions.Second.action).toBe("run");
        expect(yield* stack.deploy(program("v2"))).toBe("constant!");
        expect(firstRuns).toBe(2);
        expect(secondRuns).toBe(1);
        const forced = yield* program("v2").pipe(
          makeStack({ name: stack.name, providers: TestLayers(), state: stack.state }),
          Effect.flatMap((spec) =>
            Plan.make(spec, { force: true }).pipe(
              Effect.flatMap(apply),
              Effect.provide(spec.services),
            ),
          ),
          Effect.provideService(Stage, stack.stage),
        );
        expect(forced).toBe("constant!");
        expect(firstRuns).toBe(3);
        expect(secondRuns).toBe(2);
        expect(actionOfPlan(yield* stack.plan(program("v2")), "Host")).toBe("noop");
      }),
  );

  test.provider(
    "changed Action output replaces the whole environment without retaining removed keys",
    (stack) =>
      Effect.gen(function* () {
        const Compute = Action("Compute", (input: { revision: number }) =>
          Effect.succeed<Record<string, string>>(
            input.revision === 1 ? { KEEP: "old", REMOVE: "old" } : { KEEP: "new" },
          ),
        );
        const program = (revision: number) =>
          Effect.gen(function* () {
            const env = yield* Compute({ revision });
            const host = yield* Function("Host", { env });
            return host.env;
          });
        expect(yield* stack.deploy(program(1))).toEqual({ KEEP: "old", REMOVE: "old" });
        expect(yield* stack.deploy(program(2))).toEqual({ KEEP: "new" });
        expect(actionOfPlan(yield* stack.plan(program(2)), "Host")).toBe("noop");
      }),
  );

  test.provider(
    "a failed Action rerun blocks its value consumer and recovery uses the new output",
    (stack) =>
      Effect.gen(function* () {
        let fail = false;
        const reconciled: (string | undefined)[] = [];
        const Compute = Action("Compute", (input: { revision: string }) =>
          Effect.gen(function* () {
            if (fail) return yield* Effect.fail(new ResourceFailure());
            return { value: input.revision };
          }),
        );
        const program = (revision: string) =>
          Effect.gen(function* () {
            const result = yield* Compute({ revision });
            const host = yield* TestResource("Host", { string: result.value });
            return host.string;
          });
        const record = (_: string, props: TestResourceProps) =>
          Effect.sync(() => {
            reconciled.push(props.string);
          });
        yield* Effect.gen(function* () {
          expect(yield* stack.deploy(program("v1"))).toBe("v1");
          fail = true;
          const failed = yield* Effect.exit(stack.deploy(program("v2")));
          assert(Exit.isFailure(failed));
          expect(failed.cause.reasons.find(Cause.isFailReason)?.error).toBeInstanceOf(
            ResourceFailure,
          );
          expect(reconciled).toEqual(["v1"]);
          fail = false;
          expect(yield* stack.deploy(program("v2"))).toBe("v2");
          expect(reconciled).toEqual(["v1", "v2"]);
        }).pipe(Effect.provideService(TestResourceHooks, { create: record, update: record }));
      }),
  );

  for (const value of [undefined, null, false, 0, ""] as const) {
    test.provider(
      `persisted ${String(value)} Action output remains reusable after apply`,
      (stack) =>
        Effect.gen(function* () {
          let runs = 0;
          const Compute = Action("Compute", (_: {}) =>
            Effect.sync(() => {
              runs++;
              return value;
            }),
          );
          const program = Effect.gen(function* () {
            const result = yield* Compute({});
            const host = yield* Function("Host", { env: { RESULT: Output.map(result, String) } });
            return host.env.RESULT;
          });
          expect(yield* stack.deploy(program)).toBe(String(value));
          expect(yield* stack.deploy(program)).toBe(String(value));
          expect(runs).toBe(1);
          expect(actionOfPlan(yield* stack.plan(program), "Host")).toBe("noop");
        }),
    );
  }

  test.provider(
    "a forced Action rerun publishes fresh output instead of its persisted result",
    (stack) =>
      Effect.gen(function* () {
        let runs = 0;
        const Compute = Action("Compute", (_: {}) =>
          Effect.sync(() => ({ value: String(++runs) })),
        );
        const program = Effect.gen(function* () {
          const result = yield* Compute({});
          const host = yield* Function("Host", { env: { RESULT: result.value } });
          return host.env.RESULT;
        });
        expect(yield* stack.deploy(program)).toBe("1");
        const forced = yield* program.pipe(
          makeStack({ name: stack.name, providers: TestLayers(), state: stack.state }),
          Effect.flatMap((spec) =>
            Plan.make(spec, { force: true }).pipe(
              Effect.flatMap(apply),
              Effect.provide(spec.services),
            ),
          ),
          Effect.provideService(Stage, stack.stage),
        );
        expect(forced).toBe("2");
        expect(yield* stack.deploy(program)).toBe("2");
        expect(runs).toBe(2);
      }),
  );

  test.provider(
    "an Action migration marker in the environment converges without removing its dependency",
    (stack) =>
      Effect.gen(function* () {
        let runs = 0;
        const Compute = Action("Compute", (_: {}) =>
          Effect.sync(() => {
            runs++;
            return { migrated: true };
          }),
        );
        const program = Effect.gen(function* () {
          const result = yield* Compute({});
          const host = yield* Function("Host", {
            name: "host",
            env: { MIGRATION: Output.map(result, JSON.stringify) },
          });
          return host.name;
        });
        expect(yield* stack.deploy(program)).toBe("host");
        expect(yield* stack.deploy(program)).toBe("host");
        expect(runs).toBe(1);
        const plan = yield* stack.plan(program);
        expect(plan.actions.Compute.action).toBe("noop");
        expect(actionOfPlan(plan, "Host")).toBe("noop");
      }),
  );

  for (const operation of ["create", "update", "replace"] as const) {
    test.provider(`Action completion precedes bound host ${operation}`, (stack) =>
      Effect.gen(function* () {
        const events: string[] = [];
        const Compute = Action("Compute", (_: { revision: string }) =>
          Effect.gen(function* () {
            yield* Effect.yieldNow;
            events.push("action completed");
            return { migrated: true };
          }),
        );
        const program = (revision: string) =>
          Effect.gen(function* () {
            const result = yield* Compute({ revision });
            const host = yield* BindingTarget("Host", {
              string: revision,
              replaceString: operation === "replace" ? revision : "fixed",
            });
            yield* host.bind("Migration", {
              env: { MIGRATION: Output.map(result, JSON.stringify) },
            });
            return host.string;
          });
        const record = () =>
          Effect.sync(() => {
            events.push("host reconciled");
          });
        yield* Effect.gen(function* () {
          if (operation !== "create") yield* stack.deploy(program("v1"));
          events.length = 0;
          expect(actionOfPlan(yield* stack.plan(program("v2")), "Host")).toBe(operation);
          expect(yield* stack.deploy(program("v2"))).toBe("v2");
          expect(events).toEqual(["action completed", "host reconciled"]);
        }).pipe(Effect.provideService(TestResourceHooks, { create: record, update: record }));
      }),
    );

    test.provider(`Action failure prevents bound host ${operation}`, (stack) =>
      Effect.gen(function* () {
        let fail = false;
        const reconciled: string[] = [];
        const Compute = Action("Compute", (_: { revision: string }) =>
          fail ? Effect.fail(new ResourceFailure()) : Effect.succeed("done"),
        );
        const program = (revision: string) =>
          Effect.gen(function* () {
            const result = yield* Compute({ revision });
            const host = yield* BindingTarget("Host", {
              string: revision,
              replaceString: operation === "replace" ? revision : "fixed",
            });
            yield* host.bind("Migration", {
              env: { MIGRATION: Output.map(result, JSON.stringify) },
            });
            return host.string;
          });
        const record = (id: string) =>
          Effect.sync(() => {
            reconciled.push(id);
          });
        yield* Effect.gen(function* () {
          if (operation !== "create") yield* stack.deploy(program("v1"));
          reconciled.length = 0;
          fail = true;
          expect(actionOfPlan(yield* stack.plan(program("v2")), "Host")).toBe(operation);
          const failed = yield* Effect.exit(stack.deploy(program("v2")));
          assert(Exit.isFailure(failed));
          expect(failed.cause.reasons.find(Cause.isFailReason)?.error).toBeInstanceOf(
            ResourceFailure,
          );
          expect(reconciled).toEqual([]);
        }).pipe(Effect.provideService(TestResourceHooks, { create: record, update: record }));
      }),
    );
  }
});

// #1831: a changed value read by a Platform's Init must reach the provider,
// even though `CapturedConfigHost`'s diff always returns `noop`.
describe("Platform Init-captured config", { tags: ["unit", "local"] }, () => {
  test.provider("a changed captured value deploys and converges", (stack) =>
    Effect.gen(function* () {
      expect((yield* stack.deploy(capturedConfigHost("a"))).mode).toBe("a");
      expect(actionOfPlan(yield* stack.plan(capturedConfigHost("a")), "Host")).toBe("noop");
      expect((yield* stack.deploy(capturedConfigHost("b"))).mode).toBe("b");
      expect(actionOfPlan(yield* stack.plan(capturedConfigHost("b")), "Host")).toBe("noop");
    }),
  );
});

describe("basic operations", { tags: ["unit", "local"] }, () => {
  test.provider("should create, update, and delete resources", (stack) =>
    Effect.gen(function* () {
      expect(
        yield* Effect.gen(function* () {
          const A = yield* TestResource("A", { string: "test-string" });
          return A.string;
        }).pipe(stack.deploy),
      ).toEqual("test-string");

      expect(
        yield* Effect.gen(function* () {
          const A = yield* TestResource("A", { string: "test-string-new" });
          return A.string;
        }).pipe(stack.deploy),
      ).toEqual("test-string-new");

      yield* stack.destroy();

      expect(yield* getState("A")).toBeUndefined();
      expect(yield* listState()).toEqual([]);
    }),
  );

  test.provider("should resolve output properties", (stack) =>
    Effect.gen(function* () {
      expect(
        yield* Effect.gen(function* () {
          const A = yield* TestResource("A", {
            string: "test-string",
            stringArray: ["test-string-array"],
          });
          const B = yield* TestResource("B", { string: A.string });
          return B.string;
        }).pipe(stack.deploy),
      ).toEqual("test-string");

      expect(
        yield* Effect.gen(function* () {
          const A = yield* TestResource("A", {
            string: "test-string",
            stringArray: ["test-string-array"],
          });
          const B = yield* TestResource("B", {
            string: A.string.pipe(Output.map((string) => string.toUpperCase())),
          });
          return B.string;
        }).pipe(stack.deploy),
      ).toEqual("TEST-STRING");

      expect(
        yield* Effect.gen(function* () {
          const A = yield* TestResource("A", {
            string: "test-string",
            stringArray: ["test-string-array"],
          });
          const B = yield* TestResource("B", {
            string: A.string.pipe(Output.map((string) => string.toUpperCase() + "-NEW")),
          });
          return B.string;
        }).pipe(stack.deploy),
      ).toEqual("TEST-STRING-NEW");

      expect(
        yield* Effect.gen(function* () {
          const A = yield* TestResource("A", {
            string: "test-string",
            stringArray: ["test-string-array"],
          });
          const B = yield* TestResource("B", {
            string: A.string.pipe(
              Output.flatMap((string) => Output.literal(string.toUpperCase() + "-FLAT")),
            ),
          });
          return B.string;
        }).pipe(stack.deploy),
      ).toEqual("TEST-STRING-FLAT");
    }),
  );

  test.provider(
    "should apply downstream resources when a stable kind shadows an output discriminator",
    (stack) =>
      Effect.gen(function* () {
        yield* KindStablesResource("Database", { value: "v1" }).pipe(stack.deploy);

        const output = yield* Effect.gen(function* () {
          const database = yield* KindStablesResource("Database", { value: "v2" });
          const role = yield* KindStablesResource("Role", { value: "role", upstream: database });
          return { database, role };
        }).pipe(stack.deploy);

        expect(output.database.value).toBe("v2");
        expect(output.role.upstreamKind).toBe("postgresql");
      }),
  );

  test.provider("should resolve bindings inside constructs using namespaced resources", (stack) =>
    Effect.gen(function* () {
      const Site = (id: string, _props: {}) =>
        Effect.gen(function* () {
          const bucket = yield* BindingTarget("Bucket", { string: "bucket-value" });
          const distribution = yield* BindingTarget("Distribution", {
            string: "distribution-value",
          });

          yield* bucket.bind("Policy", {
            env: { BUCKET: bucket.string, DISTRIBUTION: distribution.string },
          });

          return { bucket, distribution };
        }).pipe(Namespace.push(id));

      const output = yield* Site("MarketingSite", {}).pipe(stack.deploy);

      expect(output.bucket.env).toEqual({
        BUCKET: "bucket-value",
        DISTRIBUTION: "distribution-value",
      });
      expectConvergedStatus((yield* getState("MarketingSite/Bucket"))?.status);
      expect((yield* getState("MarketingSite/Distribution"))?.status).toEqual("created");
    }),
  );

  test.provider("should exclude deleted bindings before provider updates", (stack) =>
    Effect.gen(function* () {
      const created = yield* stack.deploy(
        Effect.gen(function* () {
          const target = yield* DeletedBindingRegressionTarget("A", { name: "target" });
          yield* target.bind("TestBinding", { env: { FEATURE_FLAG: "on" } });
          return target;
        }),
      );

      expect(created.env).toEqual({ FEATURE_FLAG: "on" });

      const updated = yield* stack.deploy(
        Effect.gen(function* () {
          return yield* DeletedBindingRegressionTarget("A", { name: "target" });
        }),
      );

      expect(updated.env).toEqual({});
      expect(yield* getState("A")).toMatchObject({ bindings: [], attr: { env: {} } });
    }),
  );

  // #874: terminal commits must persist the RESOLVED binding payload the
  // provider reconciled with, not the raw plan-time expressions. Raw
  // `node.bindings` hold unresolved Outputs (silently dropped by JSON state
  // stores), so persisting them makes every later plan's `diffBindings`
  // compare a lossy stored shape against fully-resolved data — a phantom
  // binding update on every plan. Exercises the create, update, and replace
  // commit sites.
  test.provider("terminal commits persist resolved binding payloads", (stack) =>
    Effect.gen(function* () {
      const program = (opts: { source: string; replaceString?: string }) =>
        Effect.gen(function* () {
          const source = yield* BindingTarget("BindSource", { string: opts.source });
          const host = yield* BindingTarget("BindHost", {
            name: "host",
            replaceString: opts.replaceString,
          });
          // `source.string` is an unresolved Output at plan time.
          yield* host.bind("FromSource", { env: { VALUE: source.string } });
          return { source, host };
        });

      const actionOf = (plan: any, logicalId: string) =>
        (Object.values(plan.resources) as any[]).find(
          (node: any) => node.resource.LogicalId === logicalId,
        )?.action;

      const expectHostBindings = Effect.fn(function* (value: string) {
        const hostState = yield* getState("BindHost");
        expect(hostState?.bindings).toEqual([
          { sid: "FromSource", data: { env: { VALUE: value } } },
        ]);
      });

      // ── create commit ──
      yield* stack.deploy(program({ source: "v1" }));
      yield* expectHostBindings("v1");
      const created = yield* stack.plan(program({ source: "v1" }));
      expect(actionOf(created, "BindSource")).toBe("noop");
      expect(actionOf(created, "BindHost")).toBe("noop");

      // ── update commit ──
      yield* stack.deploy(program({ source: "v2" }));
      yield* expectHostBindings("v2");
      const updated = yield* stack.plan(program({ source: "v2" }));
      expect(actionOf(updated, "BindSource")).toBe("noop");
      expect(actionOf(updated, "BindHost")).toBe("noop");

      // ── replace commit ──
      yield* stack.deploy(program({ source: "v2", replaceString: "flip" }));
      yield* expectHostBindings("v2");
      const replaced = yield* stack.plan(program({ source: "v2", replaceString: "flip" }));
      expect(actionOf(replaced, "BindSource")).toBe("noop");
      expect(actionOf(replaced, "BindHost")).toBe("noop");
    }),
  );

  test.provider(
    "persists resolved binding data so an unchanged redeploy plans binding noops",
    (stack) =>
      Effect.gen(function* () {
        // Binding data references an output of a resource created in the
        // SAME deploy — unresolved at plan time, resolved during apply.
        const program = Effect.gen(function* () {
          const upstream = yield* BindingTarget("Upstream", { string: "upstream-value" });
          const target = yield* BindingTarget("Target", { string: "t" });
          yield* target.bind("Cap", { env: { UPSTREAM: upstream.string } });
          return target;
        });

        const created = yield* stack.deploy(program);
        expect(created.env).toEqual({ UPSTREAM: "upstream-value" });

        // The persisted binding data must hold the RESOLVED value (what
        // `reconcile` received) — not the raw plan-time data, whose Output
        // proxies JSON state stores silently drop.
        expect(yield* getState("Target")).toMatchObject({
          status: "created",
          bindings: [{ sid: "Cap", data: { env: { UPSTREAM: "upstream-value" } } }],
        });

        // An unchanged redeploy must plan the binding as a noop. Before the
        // fix, the truncated persisted data diffed against the now-resolved
        // value and forced a spurious update on every deploy after a create.
        yield* stack.deploy(program);
        expect((yield* getState("Target"))?.status).toEqual("created");
      }),
  );

  test.provider(
    "should update a surviving consumer before deleting a removed dependency",
    (stack) =>
      Effect.gen(function* () {
        const created = yield* stack.deploy(
          Effect.gen(function* () {
            const secret = yield* TestResource("Secret", { string: "secret-value" });
            const worker = yield* Function("Worker", {
              name: "worker",
              env: { SECRET: secret.string },
            });
            return { secret, worker };
          }),
        );

        expect(created.worker.env).toEqual({ SECRET: "secret-value" });
        expect((yield* getState("Secret"))?.status).toEqual("created");
        expect((yield* getState("Worker"))?.status).toEqual("created");

        const updated = yield* stack.deploy(
          Effect.gen(function* () {
            return yield* Function("Worker", { name: "worker" });
          }),
        );

        expect(updated.env).toEqual({});
        expect(yield* getState("Secret")).toBeUndefined();
        expect((yield* getState("Worker"))?.status).toEqual("updated");
      }),
  );

  test.provider(
    "should create a resource with a binding that references its own output",
    (stack) =>
      Effect.gen(function* () {
        const created = yield* stack.deploy(
          Effect.gen(function* () {
            const target = yield* DeletedBindingRegressionTarget("A", { name: "target" });
            yield* target.bind("SelfBinding", { env: { SELF_NAME: target.name } });
            return target;
          }),
        );

        expect(created.env).toEqual({ SELF_NAME: "target" });
      }),
    { timeout: 10_000 },
  );
});

// Regression: a logical ID may legitimately contain the FQN separator ("/").
// The GitHub event source registers a webhook keyed by `${owner}/${repository}`
// (e.g. "alchemy-run/alchemy"). During destroy the deletion path used to
// recompute the state key via `toFqn(namespace, logicalId)`, but `logicalId`
// came from `parseFqn` which splits on "/" and keeps only the last segment
// ("alchemy"). The recomputed key missed the real state row, so the
// resource was deleted from the cloud yet never removed from state — resurfacing
// as an orphan deletion on every subsequent destroy, forever.
describe("FQN separator in logical ID", { tags: ["unit", "local"] }, () => {
  test.provider("destroy clears state for a top-level logical ID containing '/'", (stack) =>
    Effect.gen(function* () {
      const fqn = "alchemy-run/alchemy";

      yield* stack.deploy(
        Effect.gen(function* () {
          return yield* TestResource(fqn, { string: "v1" });
        }),
      );

      // The row is persisted under the full FQN (separator and all).
      expect((yield* getState(fqn))?.status).toEqual("created");

      const deleted: string[] = [];
      yield* stack.destroy().pipe(
        hook({
          delete: (id: string) =>
            Effect.sync(() => {
              deleted.push(id);
            }),
        }),
      );

      // provider.delete ran exactly once, AND the state row was removed
      // (the pre-fix bug deleted the cloud resource but missed the row).
      expect(deleted).toHaveLength(1);
      expect(yield* getState(fqn)).toBeUndefined();
      expect(yield* listState()).toEqual([]);
    }),
  );

  test.provider("destroy clears state for a namespaced logical ID containing '/'", (stack) =>
    Effect.gen(function* () {
      // Mirrors the GitHub webhook: a host construct (the Worker) whose
      // child resource's logical ID is "owner/repo".
      const fqn = "ReleaseService/alchemy-run/alchemy";

      yield* stack.deploy(
        Effect.gen(function* () {
          return yield* TestResource("alchemy-run/alchemy", { string: "v1" });
        }).pipe(Namespace.push("ReleaseService")),
      );

      expect((yield* getState(fqn))?.status).toEqual("created");

      yield* stack.destroy();

      expect(yield* getState(fqn)).toBeUndefined();
      expect(yield* listState()).toEqual([]);
    }),
  );
});

// A ref to a resource the same program declares (current stack and stage) is
// a dependency like a direct reference. Each case slows the side a missing
// edge would let run first, so a race shows up as a wrong order instead of
// passing by luck.
describe("same-stack refs to declared resources", { tags: ["unit", "local"] }, () => {
  const program = (shared: TestResourceProps, withConsumer = true) =>
    Effect.gen(function* () {
      const declared = yield* TestResource("Shared", shared);
      if (!withConsumer) return { shared: declared, consumer: undefined };
      const ref = yield* TestResource.ref("Shared");
      const consumer = yield* TestResource("Consumer", { string: ref.string });
      return { shared: declared, consumer };
    });

  // Target first, then the dependent: a ref that already resolves from state,
  // so the later assertions isolate ordering and freshness from the
  // same-deploy create case.
  const deployInPhases = (stack: Test.ScratchStack, shared: TestResourceProps) =>
    Effect.gen(function* () {
      yield* stack.deploy(program(shared, false));
      return yield* stack.deploy(program(shared));
    });

  const recorder = () => {
    const events: string[] = [];
    const record = (event: string, slow?: string) => (id: string) =>
      Effect.gen(function* () {
        if (id === slow) yield* Effect.sleep("100 millis");
        events.push(`${event} ${id}`);
      });
    return { events, record };
  };

  test.provider("deploys a ref to a resource created in the same deploy, target first", (stack) =>
    Effect.gen(function* () {
      const { events, record } = recorder();
      const output = yield* program({ string: "v1" }).pipe(
        stack.deploy,
        hook({ create: record("create", "Shared") }),
      );

      expect(output.consumer!.string).toEqual("v1");
      expect(events).toEqual(["create Shared", "create Consumer"]);
      // The edge is persisted, so a later destroy orders deletes without the program.
      expect((yield* getState("Shared"))?.downstream).toContain("Consumer");
    }),
  );

  test.provider("destroy deletes the ref's dependent before its target", (stack) =>
    Effect.gen(function* () {
      yield* deployInPhases(stack, { string: "v1" });

      const { events, record } = recorder();
      yield* stack.destroy().pipe(hook({ delete: record("delete", "Consumer") }));

      expect(events).toEqual(["delete Consumer", "delete Shared"]);
      expect(yield* listState()).toEqual([]);
    }),
  );

  test.provider("removing both from the program deletes the dependent first", (stack) =>
    Effect.gen(function* () {
      yield* deployInPhases(stack, { string: "v1" });

      const { events, record } = recorder();
      yield* stack
        .deploy(Effect.gen(function* () {}))
        .pipe(hook({ delete: record("delete", "Consumer") }));

      expect(events).toEqual(["delete Consumer", "delete Shared"]);
    }),
  );

  test.provider("removing only the dependent keeps the target", (stack) =>
    Effect.gen(function* () {
      yield* deployInPhases(stack, { string: "v1" });

      const { events, record } = recorder();
      yield* stack
        .deploy(program({ string: "v1" }, false))
        .pipe(hook({ delete: record("delete") }));

      expect(events).toEqual(["delete Consumer"]);
      expect((yield* getState("Shared"))?.status).toEqual("created");
      expect((yield* getState("Shared"))?.downstream ?? []).not.toContain("Consumer");
    }),
  );

  test.provider("an update to the target reaches the dependent fresh, never stale", (stack) =>
    Effect.gen(function* () {
      yield* deployInPhases(stack, { string: "v1" });

      const seen: string[] = [];
      const output = yield* program({ string: "v2" }).pipe(
        stack.deploy,
        hook({
          update: (id, props) =>
            Effect.gen(function* () {
              if (id === "Shared") yield* Effect.sleep("100 millis");
              if (id === "Consumer" && typeof props.string === "string") seen.push(props.string);
            }),
        }),
      );

      expect(output.consumer!.string).toEqual("v2");
      expect(seen).toEqual(["v2"]);
    }),
  );

  test.provider("a replaced target hands the dependent its new generation", (stack) =>
    Effect.gen(function* () {
      yield* deployInPhases(stack, { string: "v1", replaceString: "a" });

      const { events, record } = recorder();
      const output = yield* program({ string: "v2", replaceString: "b" }).pipe(
        stack.deploy,
        hook({
          create: record("create", "Shared"),
          update: record("update"),
          delete: record("delete"),
        }),
      );

      expect(output.shared.replaceString).toEqual("b");
      expect(output.consumer!.string).toEqual("v2");
      // Create-first replacement: new generation, then the dependent, then
      // the old generation is retired.
      expect(events).toEqual(["create Shared", "update Consumer", "delete Shared"]);
    }),
  );

  test.provider(
    "a resource's ref to itself reads its persisted state without waiting on itself",
    (stack) =>
      Effect.gen(function* () {
        yield* stack.deploy(TestResource("Self", { string: "v1" }));

        const output = yield* stack.deploy(
          Effect.gen(function* () {
            const self = yield* TestResource.ref("Self");
            return yield* TestResource("Self", { string: "v2", stringArray: [self.string] });
          }),
        );

        expect(output.string).toEqual("v2");
        expect(output.stringArray).toEqual(["v1"]);
        expect((yield* getState("Self"))?.downstream ?? []).not.toContain("Self");
      }),
  );

  test.provider("a ref used only in a binding persists the binding edge", (stack) =>
    Effect.gen(function* () {
      yield* stack.deploy(TestResource("Shared", { string: "v1" }));
      const output = yield* stack.deploy(
        Effect.gen(function* () {
          yield* TestResource("Shared", { string: "v1" });
          const ref = yield* TestResource.ref("Shared");
          const host = yield* BindingTarget("Host", { name: "host" });
          yield* host.bind("Shared", { env: { SHARED: ref.string } });
          return host;
        }),
      );

      expect(output.env.SHARED).toEqual("v1");
      expect((yield* getState("Shared"))?.downstream).toContain("Host");
    }),
  );
});

describe("linear update propagation", { tags: ["unit", "local"] }, () => {
  // Regression: in a linear chain (A -> B with no cycle), an update to A
  // followed by an update to B must let B see A's *post-update* attr, never
  // the stale prior attr. Before the cycle-gating change, A would publish
  // its prior attr early and B's update would race against the live value,
  // sometimes deploying with stale data (e.g. a Worker reading a Build's
  // outdir/hash before the build finished).
  test.provider("downstream update receives upstream's post-update attr", (stack) =>
    Effect.gen(function* () {
      yield* stack.deploy(
        Effect.gen(function* () {
          const A = yield* TestResource("A", { string: "v1" });
          const B = yield* TestResource("B", { string: A.string });
          return { A, B };
        }),
      );

      const sawByB: string[] = [];
      const captureBHooks = {
        create: () => Effect.succeed(undefined),
        update: (id: string, props: TestResourceProps) =>
          Effect.sync(() => {
            if (id === "B" && typeof props.string === "string") {
              sawByB.push(props.string);
            }
          }),
        delete: () => Effect.succeed(undefined),
        read: () => Effect.succeed(undefined),
      };

      const output = yield* Effect.gen(function* () {
        const A = yield* TestResource("A", { string: "v2" });
        const B = yield* TestResource("B", { string: A.string });
        return { A, B };
      }).pipe(stack.deploy, hook(captureBHooks));

      expect(output.A.string).toEqual("v2");
      expect(output.B.string).toEqual("v2");
      // B.update must have observed the fresh upstream value, never the
      // stale "v1". A single fresh-only call is the ideal; we accept any
      // sequence as long as no stale value leaked through.
      expect(sawByB.length).toBeGreaterThan(0);
      expect(sawByB.every((v) => v === "v2")).toBe(true);
    }),
  );

  // Regression: a dependent that repins from upstream A to upstream B updates
  // *itself*, while A and B are both noops. The noop pass must still persist
  // their new `downstream` — delete ordering reads it from the persisted row,
  // so a stale list would delete B concurrently with the dependent that still
  // references it (and needlessly wait on A).
  test.provider("noop upstreams persist a repinned dependent's downstream edge", (stack) =>
    Effect.gen(function* () {
      const program = (pin: "A" | "B") =>
        Effect.gen(function* () {
          const A = yield* TestResource("A", { string: "a" });
          const B = yield* TestResource("B", { string: "b" });
          const C = yield* TestResource("C", { string: (pin === "A" ? A : B).string });
          return { A, B, C };
        });

      yield* stack.deploy(program("A"));
      expect((yield* getState("A"))?.downstream).toEqual(["C"]);
      expect((yield* getState("B"))?.downstream).toEqual([]);

      yield* stack.deploy(program("B"));
      expect((yield* getState("A"))?.downstream).toEqual([]);
      expect((yield* getState("B"))?.downstream).toEqual(["C"]);
    }),
  );
});

// Regression: `deleteFirst` on a `replace` diff was plumbed from the provider
// all the way into persisted state but never *read* — every replacement was
// create-first, with the old generation reclaimed afterwards by Phase-2 GC.
// That silently broke any resource whose replacement can't coexist with the
// original (fixed physical name, singleton): the create collided with the
// not-yet-deleted original. These tests pin both orderings.
describe("deleteFirst replacements", { tags: ["unit", "local"] }, () => {
  test.provider("deletes the old generation BEFORE creating the replacement", (stack) =>
    Effect.gen(function* () {
      yield* stack.deploy(
        Effect.gen(function* () {
          return yield* DeleteFirstResource("R", { replaceString: "v1" });
        }),
      );

      const order: string[] = [];
      const recordHooks = {
        create: () =>
          Effect.sync(() => {
            order.push("create");
          }),
        update: () => Effect.succeed(undefined),
        delete: () =>
          Effect.sync(() => {
            order.push("delete");
          }),
      };

      yield* Effect.gen(function* () {
        return yield* DeleteFirstResource("R", { replaceString: "v2" });
      }).pipe(stack.deploy, hook(recordHooks));

      // The whole point: delete-old precedes create-new.
      expect(order).toEqual(["delete", "create"]);

      // The resource collapses straight to a terminal `created` state with
      // no leftover replacement chain for GC to drain.
      const state = yield* getState("R");
      expect(state?.status).toEqual("created");
      expect((state as { old?: unknown }).old).toBeUndefined();
      expect(yield* listState()).toHaveLength(1);
    }),
  );

  test.provider("default (non-deleteFirst) replacement still creates BEFORE deleting", (stack) =>
    Effect.gen(function* () {
      // `TestResource` returns a plain `{ action: "replace" }` (deleteFirst
      // defaults to false), so the engine must stay create-first.
      yield* stack.deploy(
        Effect.gen(function* () {
          return yield* TestResource("R", { replaceString: "v1" });
        }),
      );

      const order: string[] = [];
      yield* Effect.gen(function* () {
        return yield* TestResource("R", { replaceString: "v2" });
      }).pipe(
        stack.deploy,
        hook({
          create: () =>
            Effect.sync(() => {
              order.push("create");
            }),
          update: () => Effect.succeed(undefined),
          delete: () =>
            Effect.sync(() => {
              order.push("delete");
            }),
        }),
      );

      expect(order).toEqual(["create", "delete"]);
    }),
  );

  test.provider(
    "lets a same-identity replacement succeed where create-first would collide",
    (stack) =>
      Effect.gen(function* () {
        // A shared registry of live physical names. The provider's create
        // fails if the (fixed) name is still live — exactly the failure mode
        // of a real fixed-name resource (Docker network "already exists",
        // no-op `volume create`) when create runs before the old is deleted.
        const registry = { live: new Set<string>() };
        const withRegistry = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
          effect.pipe(Effect.provide(Layer.succeed(CollisionRegistry, registry)));

        yield* stack
          .deploy(
            Effect.gen(function* () {
              return yield* DeleteFirstResource("R", { name: "singleton", replaceString: "v1" });
            }),
          )
          .pipe(withRegistry);
        expect(registry.live.has("singleton")).toBe(true);

        // Before the fix this deploy died with a CollisionError because the
        // create of the new "singleton" ran while the old one was still live.
        const result = yield* stack
          .deploy(
            Effect.gen(function* () {
              return yield* DeleteFirstResource("R", { name: "singleton", replaceString: "v2" });
            }),
          )
          .pipe(withRegistry);

        expect(result.name).toEqual("singleton");
        expect(result.replaceString).toEqual("v2");
        // Exactly one live instance remains (old torn down, new created).
        expect(registry.live.size).toBe(1);
        expect(registry.live.has("singleton")).toBe(true);

        const state = yield* getState("R");
        expect(state?.status).toEqual("created");
      }),
  );
});

describe("circularity via bindings", { tags: ["unit", "local"] }, () => {
  const selfBoundStack = (props: { string: string; replaceString?: string; includeD?: boolean }) =>
    Effect.gen(function* () {
      const A = yield* BindingTarget("A", {
        name: "a",
        string: props.string,
        replaceString: props.replaceString,
      });
      yield* A.bind("SelfBinding", { env: { SELF: A.string } });
      const B = yield* TestResource("B", { string: A.string });
      if (props.includeD) {
        const D = yield* TestResource("D", { string: B.string });
        return { A, B, D };
      }
      return { A, B };
    });

  const mutualBindingStack = (props: {
    aString: string;
    aReplaceString?: string;
    bString?: string;
    includeD?: boolean;
  }) =>
    Effect.gen(function* () {
      const A = yield* BindingTarget("A", {
        name: "a",
        string: props.aString,
        replaceString: props.aReplaceString,
      });
      const B = yield* BindingTarget("B", { name: "b", string: props.bString ?? "b-value" });
      yield* A.bind("FromB", { env: { PEER: B.string } });
      yield* B.bind("FromA", { env: { PEER: A.string } });
      if (props.includeD) {
        const D = yield* TestResource("D", { string: Output.interpolate`${A.string}-${B.string}` });
        return { A, B, D };
      }
      return { A, B };
    });

  const propAndBindingCycleStack = () =>
    Effect.gen(function* () {
      const A = yield* BindingTarget("A", { name: "a", string: "a-value" });
      const B = yield* TestResource("B", { string: A.string });
      yield* A.bind("FromB", { env: { PEER: B.string } });
      return { A, B };
    });

  test.provider(
    "create succeeds when props use precreate output and bindings use downstream output",
    (stack) =>
      Effect.gen(function* () {
        const output = yield* stack.deploy(propAndBindingCycleStack());

        expect(output.A.env).toEqual({ PEER: "a-value" });
        expect(output.B.string).toEqual("a-value");
        expectConvergedStatus((yield* getState("A"))?.status);
        expectConvergedStatus((yield* getState("B"))?.status);
      }),
    { timeout: 10_000 },
  );

  describe("self-referential bindings", () => {
    test.provider("create succeeds with self binding", (stack) =>
      Effect.gen(function* () {
        const output = yield* stack.deploy(
          selfBoundStack({ string: "a-value", replaceString: "original" }),
        );

        expect(output.A.env).toEqual({ SELF: "a-value" });
        expect(output.B.string).toEqual("a-value");
        expectConvergedStatus((yield* getState("A"))?.status);
        expectConvergedStatus((yield* getState("B"))?.status);
      }),
    );

    test.provider(
      "replacing state noop replay recovers and creates downstream resources",
      (stack) =>
        Effect.gen(function* () {
          yield* selfBoundStack({ string: "a-value", replaceString: "original" }).pipe(
            stack.deploy,
          );

          const program = selfBoundStack({
            string: "a-value-replaced",
            replaceString: "changed",
            includeD: true,
          });

          yield* program.pipe(stack.deploy, hook(failOn("A", "create")));

          expect((yield* getState<ReplacingResourceState>("A"))?.status).toEqual("replacing");
          expectConvergedStatus((yield* getState("B"))?.status);
          expectNotStarted(yield* getState("D"));

          const output = yield* program.pipe(stack.deploy);
          expectConvergedStatus((yield* getState("A"))?.status);
          expect((yield* getState("B"))?.status).toEqual("updated");
          expectConvergedStatus((yield* getState("D"))?.status);
          expect(output.A.env).toEqual({ SELF: "a-value-replaced" });
          expect(output.D!.string).toEqual("a-value-replaced");
        }),
    );

    test.provider(
      "replacing state update replay updates replacement and creates downstream resources",
      (stack) =>
        Effect.gen(function* () {
          yield* selfBoundStack({ string: "a-value", replaceString: "original" }).pipe(
            stack.deploy,
          );

          yield* selfBoundStack({
            string: "a-value-replaced",
            replaceString: "changed",
            includeD: true,
          }).pipe(stack.deploy, hook(failOn("A", "create")));

          expect((yield* getState<ReplacingResourceState>("A"))?.status).toEqual("replacing");
          expectConvergedStatus((yield* getState("B"))?.status);
          expectNotStarted(yield* getState("D"));

          const output = yield* selfBoundStack({
            string: "a-value-updated-during-recovery",
            replaceString: "changed",
            includeD: true,
          }).pipe(stack.deploy);

          expectConvergedStatus((yield* getState("A"))?.status);
          expect((yield* getState("B"))?.status).toEqual("updated");
          expectConvergedStatus((yield* getState("D"))?.status);
          expect(output.A.env).toEqual({ SELF: "a-value-updated-during-recovery" });
          expect(output.D!.string).toEqual("a-value-updated-during-recovery");
        }),
    );

    test.provider(
      "replaced state noop replay finishes cleanup and creates downstream resources",
      (stack) =>
        Effect.gen(function* () {
          yield* selfBoundStack({ string: "a-value", replaceString: "original" }).pipe(
            stack.deploy,
          );

          const program = selfBoundStack({
            string: "a-value-replaced",
            replaceString: "changed",
            includeD: true,
          });

          yield* program.pipe(stack.deploy, hook(failOn("B", "update")));

          expect((yield* getState<ReplacedResourceState>("A"))?.status).toEqual("replaced");
          expect((yield* getState("B"))?.status).toEqual("updating");
          expectNotStarted(yield* getState("D"));

          const output = yield* program.pipe(stack.deploy);
          expectConvergedStatus((yield* getState("A"))?.status);
          expect((yield* getState("B"))?.status).toEqual("updated");
          expectConvergedStatus((yield* getState("D"))?.status);
          expect(output.A.env).toEqual({ SELF: "a-value-replaced" });
          expect(output.D!.string).toEqual("a-value-replaced");
        }),
    );

    test.provider(
      "replaced state update replay updates replacement and downstream resources",
      (stack) =>
        Effect.gen(function* () {
          yield* selfBoundStack({ string: "a-value", replaceString: "original" }).pipe(
            stack.deploy,
          );

          yield* selfBoundStack({
            string: "a-value-replaced",
            replaceString: "changed",
            includeD: true,
          }).pipe(stack.deploy, hook(failOn("B", "update")));

          expect((yield* getState<ReplacedResourceState>("A"))?.status).toEqual("replaced");
          expect((yield* getState("B"))?.status).toEqual("updating");
          expectNotStarted(yield* getState("D"));

          const output = yield* selfBoundStack({
            string: "a-value-updated-after-replace",
            replaceString: "changed",
            includeD: true,
          }).pipe(stack.deploy);

          expectConvergedStatus((yield* getState("A"))?.status);
          expect((yield* getState("B"))?.status).toEqual("updated");
          expectConvergedStatus((yield* getState("D"))?.status);
          expect(output.A.env).toEqual({ SELF: "a-value-updated-after-replace" });
          expect(output.D!.string).toEqual("a-value-updated-after-replace");
        }),
    );
  });

  describe("mutual A <-> B bindings", () => {
    test.provider("create succeeds with mutual bindings", (stack) =>
      Effect.gen(function* () {
        const output = yield* stack.deploy(mutualBindingStack({ aString: "a-value" }));

        expect(output.A.env).toEqual({ PEER: "b-value" });
        expect(output.B.env).toEqual({ PEER: "a-value" });
        expectConvergedStatus((yield* getState("A"))?.status);
        expectConvergedStatus((yield* getState("B"))?.status);
      }),
    );

    test.provider("destroy succeeds with mutual bindings", (stack) =>
      Effect.gen(function* () {
        yield* mutualBindingStack({ aString: "a-value" }).pipe(stack.deploy);

        yield* stack.destroy();

        expect(yield* getState("A")).toBeUndefined();
        expectNotStarted(yield* getState("B"));
      }),
    );

    describe("from replacing state", () => {
      test.provider("replacing noop recovery creates downstream resources", (stack) =>
        Effect.gen(function* () {
          yield* mutualBindingStack({ aString: "a-value", aReplaceString: "original" }).pipe(
            stack.deploy,
          );

          const program = mutualBindingStack({
            aString: "a-value-replaced",
            aReplaceString: "changed",
            includeD: true,
          });

          yield* program.pipe(stack.deploy, hook(failOn("A", "create")));

          expect((yield* getState<ReplacingResourceState>("A"))?.status).toEqual("replacing");
          expectConvergedStatus((yield* getState("B"))?.status);
          expectNotStarted(yield* getState("D"));

          const output = yield* program.pipe(stack.deploy);
          expectConvergedStatus((yield* getState("A"))?.status);
          expect((yield* getState("B"))?.status).toEqual("updated");
          expectConvergedStatus((yield* getState("D"))?.status);
          expect(output.A.env).toEqual({ PEER: "b-value" });
          expect(output.B.env).toEqual({ PEER: "a-value-replaced" });
          expect(output.D!.string).toEqual("a-value-replaced-b-value");
        }),
      );

      test.provider("replacing update recovery creates downstream resources", (stack) =>
        Effect.gen(function* () {
          yield* mutualBindingStack({ aString: "a-value", aReplaceString: "original" }).pipe(
            stack.deploy,
          );

          yield* mutualBindingStack({
            aString: "a-value-replaced",
            aReplaceString: "changed",
            includeD: true,
          }).pipe(stack.deploy, hook(failOn("A", "create")));

          expect((yield* getState<ReplacingResourceState>("A"))?.status).toEqual("replacing");
          expectConvergedStatus((yield* getState("B"))?.status);
          expectNotStarted(yield* getState("D"));

          const output = yield* mutualBindingStack({
            aString: "a-value-updated-during-recovery",
            aReplaceString: "changed",
            includeD: true,
          }).pipe(stack.deploy);

          expectConvergedStatus((yield* getState("A"))?.status);
          expect((yield* getState("B"))?.status).toEqual("updated");
          expectConvergedStatus((yield* getState("D"))?.status);
          expect(output.A.env).toEqual({ PEER: "b-value" });
          expect(output.B.env).toEqual({ PEER: "a-value-updated-during-recovery" });
          expect(output.D!.string).toEqual("a-value-updated-during-recovery-b-value");
        }),
      );

      test.provider("replacing replace recovery nests another replacement", (stack) =>
        Effect.gen(function* () {
          yield* mutualBindingStack({ aString: "a-value", aReplaceString: "original" }).pipe(
            stack.deploy,
          );

          yield* mutualBindingStack({
            aString: "a-value-replaced",
            aReplaceString: "changed",
            includeD: true,
          }).pipe(stack.deploy, hook(failOn("A", "create")));

          const output = yield* mutualBindingStack({
            aString: "a-value-another-replacement",
            aReplaceString: "another-change",
            includeD: true,
          }).pipe(stack.deploy);

          expectConvergedStatus((yield* getState("A"))?.status);
          expect((yield* getState("B"))?.status).toEqual("updated");
          expectConvergedStatus((yield* getState("D"))?.status);
          expect(output.B.env).toEqual({ PEER: "a-value-another-replacement" });
        }),
      );
    });

    describe("from replaced state", () => {
      test.provider(
        "replaced noop recovery updates downstream then creates downstream resources",
        (stack) =>
          Effect.gen(function* () {
            yield* mutualBindingStack({ aString: "a-value", aReplaceString: "original" }).pipe(
              stack.deploy,
            );

            const program = mutualBindingStack({
              aString: "a-value-replaced",
              aReplaceString: "changed",
              includeD: true,
            });

            yield* program.pipe(stack.deploy, hook(failOn("B", "update")));

            expect((yield* getState<ReplacedResourceState>("A"))?.status).toEqual("replaced");
            expect((yield* getState("B"))?.status).toEqual("updating");