The best way to control Claude Code, Codex and more from any computer or phone

main
ts 6,040 lines 209 KB
Raw
1 import { describe, expect } from "@alchemy.run/test";
2 import * as Test from "@alchemy.run/test/Alchemy";
3 import * as Cause from "effect/Cause";
4 import * as Config from "effect/Config";
5 import * as Context from "effect/Context";
6 import * as Effect from "effect/Effect";
7 import * as Exit from "effect/Exit";
8 import * as Layer from "effect/Layer";
9 import * as Logger from "effect/Logger";
10 import * as Option from "effect/Option";
11 import * as Redacted from "effect/Redacted";
12 import { Action } from "@/Action";
13 import { adopt, AdoptPolicy, Unowned } from "@/AdoptPolicy";
14 import { AuthProviders } from "@/Auth/AuthProvider.ts";
15 import { dedupeBindings, isResolved } from "@/Diff";
16 import { onEvent, type Event } from "@/Events.ts";
17 import type { Input, InputProps } from "@/Input";
18 import * as Namespace from "@/Namespace.ts";
19 import * as Output from "@/Output";
20 import * as Plan from "@/Plan";
21 import { UnsatisfiedResourceCycle } from "@/Plan";
22 import * as Provider from "@/Provider";
23 import { remote } from "@/ProviderMode.ts";
24 import { renamedFrom } from "@/Rename.ts";
25 import { Resource, type ResourceBinding } from "@/Resource";
26 import { packEnvValue } from "@/RuntimeContext.ts";
27 import * as Stack from "@/Stack";
28 import { Stage } from "@/Stage";
29 import {
30 InMemoryService,
31 inMemoryState,
32 State,
33 type ResourceState,
34 type ResourceStatus,
35 } from "@/State";
36 import { hashInput } from "@/Util/sha256";
37 import {
38 AliasedWidget,
39 aliasedWidgetProvider,
40 ArtifactProbe,
41 BindingTarget,
42 Bucket,
43 capturedConfigHost,
44 Function,
45 inDev,
46 KindStablesResource,
47 ModalResource,
48 NoPrecreateBindingTarget,
49 OverrideStablesResource,
50 ProbeBinding,
51 Queue,
52 ResourceFailure,
53 StaticStablesResource,
54 TestLayers,
55 TestResource,
56 TestResourceHooks,
57 type TestResourceProps,
58 } from "./test.resources";
59
60 const TEST_STACK = "test";
61 const TEST_STAGE = "test";
62
63 // Fresh in-memory state per test run so seeded resources from one test
64 // don't leak into another in the same file.
65 const freshState = Layer.effect(
66 State,
67 Effect.sync(() => InMemoryService({})),
68 );
69
70 const { test } = Test.make({ providers: TestLayers(), state: freshState });
71
72 // Resolve stack name/stage from ambient Stack if present (for test.provider)
73 // otherwise fall back to the file-level defaults (for plain test()).
74 const resolveStackId = Effect.gen(function* () {
75 const ambient = yield* Effect.serviceOption(Stack.Stack);
76 return Option.match(ambient, {
77 onNone: () => ({ name: TEST_STACK, stage: TEST_STAGE }),
78 onSome: (s) => ({ name: s.name, stage: s.stage }),
79 });
80 });
81
82 const seed = (resources: Record<string, ResourceState>) =>
83 Effect.gen(function* () {
84 const { name, stage } = yield* resolveStackId;
85 const state = yield* yield* State;
86 for (const [fqn, value] of Object.entries(resources)) {
87 yield* state.set({ stack: name, stage, fqn, value });
88 }
89 });
90
91 const instanceId = "852f6ec2e19b66589825efe14dca2971";
92
93 const makePlan = <A, Err = never, Req = never>(
94 effect: Effect.Effect<A, Err, Req>,
95 options?: Plan.FilteredPlanOptions,
96 ): Effect.Effect<Plan.Plan<A | undefined>, Err, State> =>
97 // @ts-expect-error - Stack.make's typing erases R unsoundly here
98 Effect.gen(function* () {
99 const { name, stage } = yield* resolveStackId;
100 // @ts-expect-error
101 return yield* effect.pipe(
102 // @ts-expect-error
103 Stack.make({ name, providers: Layer.empty, state: inMemoryState() }),
104 Effect.provideService(Stage, stage),
105 Effect.flatMap((stackSpec: any) => Plan.make(stackSpec, options)),
106 Effect.provide(TestLayers()),
107 );
108 });
109
110 const makePlanWithCustomStack =
111 (stackSpec: any) =>
112 <A, Err = never, Req = never>(
113 effect: Effect.Effect<A, Err, Req>,
114 ): Effect.Effect<Plan.Plan<A>, Err, State> =>
115 // @ts-expect-error
116 Effect.gen(function* () {
117 const { name, stage } = yield* resolveStackId;
118 // @ts-expect-error
119 return yield* effect.pipe(
120 // @ts-expect-error
121 Stack.make({ name, providers: Layer.empty, state: inMemoryState(), stack: stackSpec }),
122 Effect.provideService(Stage, stage),
123 Effect.flatMap(Plan.make),
124 Effect.provide(TestLayers()),
125 );
126 });
127
128 describe("Action output convergence", { tags: ["unit", "local"] }, () => {
129 const seedAction = (
130 id: string,
131 input: Record<string, unknown>,
132 output: unknown,
133 status: "ran" | "running" = "ran",
134 ) =>
135 Effect.gen(function* () {
136 const { name, stage } = yield* resolveStackId;
137 const state = yield* yield* State;
138 const row = {
139 kind: "action" as const,
140 fqn: id,
141 logicalId: id,
142 namespace: undefined,
143 actionType: "Compute",
144 inputHash: yield* hashInput(input),
145 input,
146 downstream: ["Host"],
147 };
148 yield* state.set({
149 stack: name,
150 stage,
151 fqn: id,
152 value: status === "ran" ? { ...row, status, output } : { ...row, status },
153 });
154 });
155
156 const seedHost = (value: string) =>
157 seed({
158 Host: {
159 instanceId,
160 providerVersion: 0,
161 logicalId: "Host",
162 fqn: "Host",
163 namespace: undefined,
164 resourceType: "Test.Function",
165 status: "created",
166 props: { name: "host", env: { RESULT: value } },
167 attr: { name: "host", env: { RESULT: value }, functionArn: "arn:test:host" },
168 bindings: [],
169 downstream: [],
170 },
171 });
172
173 test(
174 "unchanged Action output in host env produces repeated noop plans without running the body",
175 Effect.gen(function* () {
176 let calls = 0;
177 const Compute = Action("Compute", (_: { revision: string }) =>
178 Effect.sync(() => {
179 calls++;
180 return { value: "v1" };
181 }),
182 );
183 yield* seedAction("Compute", { revision: "one" }, { value: "v1" });
184 yield* seedHost("v1");
185 const program = Effect.gen(function* () {
186 const result = yield* Compute({ revision: "one" });
187 return yield* Function("Host", { name: "host", env: { RESULT: result.value } });
188 });
189 for (const _ of [1, 2]) {
190 const plan = yield* program.pipe(makePlan);
191 expect(plan.actions.Compute.action).toBe("noop");
192 expect(plan.actions.Compute.downstream).toContain("Host");
193 expect(plan.resources.Host.action).toBe("noop");
194 expect(calls).toBe(0);
195 }
196 }),
197 );
198
199 test(
200 "a new consumer receives the persisted output of a noop Action and retains its dependency edge",
201 Effect.gen(function* () {
202 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
203 yield* seedAction("Compute", {}, { value: "v1" });
204 const plan = yield* Effect.gen(function* () {
205 const result = yield* Compute({});
206 return yield* Function("Host", { env: { RESULT: result.value } });
207 }).pipe(makePlan);
208 expect(plan.actions.Compute.action).toBe("noop");
209 expect(plan.actions.Compute.downstream).toContain("Host");
210 expect(plan.resources.Host).toMatchObject({
211 action: "create",
212 props: { env: { RESULT: "v1" } },
213 });
214 }),
215 );
216
217 test(
218 "unchanged Action output in binding data does not dirty the host",
219 Effect.gen(function* () {
220 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
221 yield* seedAction("Compute", {}, { value: "v1" });
222 yield* seed({
223 Host: {
224 instanceId,
225 providerVersion: 0,
226 logicalId: "Host",
227 fqn: "Host",
228 namespace: undefined,
229 resourceType: "Test.BindingTarget",
230 status: "created",
231 props: { name: "host" },
232 attr: { name: "host", string: "", env: { RESULT: "v1" }, replaceString: undefined },
233 bindings: [{ sid: "Result", data: { env: { RESULT: "v1" } } }],
234 downstream: [],
235 },
236 });
237 const plan = yield* Effect.gen(function* () {
238 const result = yield* Compute({});
239 const host = yield* BindingTarget("Host", { name: "host" });
240 yield* host.bind("Result", { env: { RESULT: result.value } });
241 return host;
242 }).pipe(makePlan);
243 expect(plan.actions.Compute.action).toBe("noop");
244 expect(plan.actions.Compute.downstream).toContain("Host");
245 expect(plan.resources.Host.action).toBe("noop");
246 expect(plan.resources.Host.bindings).toEqual([
247 { sid: "Result", action: "noop", data: { env: { RESULT: "v1" } } },
248 ]);
249 }),
250 );
251
252 for (const scenario of ["changed input", "force", "unfinished prior run"] as const) {
253 test(
254 `${scenario} keeps the Action output unresolved instead of substituting stale state`,
255 Effect.gen(function* () {
256 const Compute = Action("Compute", (input: { revision: string }) =>
257 Effect.succeed({ value: input.revision }),
258 );
259 yield* seedAction(
260 "Compute",
261 { revision: "one" },
262 { value: "old" },
263 scenario === "unfinished prior run" ? "running" : "ran",
264 );
265 yield* seedHost("old");
266 const plan = yield* Effect.gen(function* () {
267 const result = yield* Compute({ revision: scenario === "changed input" ? "two" : "one" });
268 return yield* Function("Host", { name: "host", env: { RESULT: result.value } });
269 }).pipe((program) => makePlan(program, { force: scenario === "force" }));
270 expect(plan.actions.Compute.action).toBe("run");
271 expect(plan.resources.Host.action).toBe("update");
272 const host = plan.resources.Host;
273 if (host.action !== "update") throw new Error("Expected a host update");
274 expect(Output.hasOutputs(host.props.env.RESULT)).toBe(true);
275 expect(plan.actions.Compute.downstream).toContain("Host");
276 }),
277 );
278 }
279
280 for (const value of [undefined, null, false, 0, ""] as const) {
281 test(
282 `persisted ${String(value)} is a valid Action result, not a missing output`,
283 Effect.gen(function* () {
284 const Compute = Action("Compute", (_: {}) => Effect.succeed(value));
285 yield* seedAction("Compute", {}, value);
286 yield* seedHost(String(value));
287 const plan = yield* Effect.gen(function* () {
288 const result = yield* Compute({});
289 return yield* Function("Host", {
290 name: "host",
291 env: { RESULT: Output.map(result, (value) => String(value)) },
292 });
293 }).pipe(makePlan);
294 expect(plan.actions.Compute.action).toBe("noop");
295 expect(plan.resources.Host.action).toBe("noop");
296 }),
297 );
298 }
299
300 for (const changed of [false, true]) {
301 test(
302 `Action chains ${changed ? "invalidate downstream consumers when root input changes" : "converge when all inputs are unchanged"}`,
303 Effect.gen(function* () {
304 const Compute = Action("Compute", (input: { value: string }) =>
305 Effect.succeed({ value: input.value }),
306 );
307 yield* seedAction("First", { value: "v1" }, { value: "v1" });
308 yield* seedAction("Second", { value: "v1" }, { value: "v1" });
309 yield* seedHost("v1");
310 const plan = yield* Effect.gen(function* () {
311 const first = yield* Compute("First", { value: changed ? "v2" : "v1" });
312 const second = yield* Compute("Second", { value: first.value });
313 return yield* Function("Host", { name: "host", env: { RESULT: second.value } });
314 }).pipe(makePlan);
315 expect(plan.actions.First.action).toBe(changed ? "run" : "noop");
316 expect(plan.actions.Second.action).toBe(changed ? "run" : "noop");
317 expect(plan.resources.Host.action).toBe(changed ? "update" : "noop");
318 expect(plan.actions.First.downstream).toContain("Second");
319 expect(plan.actions.Second.downstream).toContain("Host");
320 }),
321 );
322 }
323
324 test(
325 "changing only the Action body preserves the existing input-based invalidation contract",
326 Effect.gen(function* () {
327 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "new-body" }));
328 yield* seedAction("Compute", {}, { value: "old-body" });
329 const plan = yield* Effect.gen(function* () {
330 const result = yield* Compute({});
331 return yield* Function("Host", { env: { RESULT: result.value } });
332 }).pipe(makePlan);
333 expect(plan.actions.Compute.action).toBe("noop");
334 expect(plan.resources.Host).toMatchObject({
335 action: "create",
336 props: { env: { RESULT: "old-body" } },
337 });
338 }),
339 );
340
341 test(
342 "a literal environment converges while an unrelated Action remains noop",
343 Effect.gen(function* () {
344 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
345 yield* seedAction("Compute", {}, { value: "v1" });
346 yield* seedHost("v1");
347 const plan = yield* Effect.gen(function* () {
348 yield* Compute({});
349 return yield* Function("Host", { name: "host", env: { RESULT: "v1" } });
350 }).pipe(makePlan);
351 expect(plan.actions.Compute.action).toBe("noop");
352 expect(plan.resources.Host.action).toBe("noop");
353 }),
354 );
355
356 test(
357 "a noop Action does not suppress changes to other consumer props",
358 Effect.gen(function* () {
359 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
360 yield* seedAction("Compute", {}, { value: "v1" });
361 yield* seedHost("v1");
362 const plan = yield* Effect.gen(function* () {
363 const result = yield* Compute({});
364 return yield* Function("Host", { name: "changed", env: { RESULT: result.value } });
365 }).pipe(makePlan);
366 expect(plan.actions.Compute.action).toBe("noop");
367 expect(plan.resources.Host.action).toBe("update");
368 }),
369 );
370
371 test(
372 "an unchanged Action output does not hide a replacement-sensitive prop change",
373 Effect.gen(function* () {
374 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
375 yield* seedAction("Compute", {}, { value: "v1" });
376 yield* seed({
377 Host: {
378 instanceId,
379 providerVersion: 0,
380 logicalId: "Host",
381 fqn: "Host",
382 namespace: undefined,
383 resourceType: "Test.BindingTarget",
384 status: "created",
385 props: { name: "host", string: "v1", replaceString: "old" },
386 attr: { name: "host", string: "v1", env: {}, replaceString: "old" },
387 bindings: [],
388 downstream: [],
389 },
390 });
391 const plan = yield* Effect.gen(function* () {
392 const result = yield* Compute({});
393 return yield* BindingTarget("Host", {
394 name: "host",
395 string: result.value,
396 replaceString: "new",
397 });
398 }).pipe(makePlan);
399 expect(plan.actions.Compute.action).toBe("noop");
400 expect(plan.resources.Host.action).toBe("replace");
401 }),
402 );
403
404 for (const stable of [false, true]) {
405 test.provider(
406 `resource-backed Action inputs ${stable ? "reuse a stable property" : "invalidate a changing property"}`,
407 (stack) =>
408 Effect.gen(function* () {
409 const Compute = Action("Compute", (input: { value: string }) => Effect.succeed(input));
410 const program = (value: string) =>
411 Effect.gen(function* () {
412 const source = yield* TestResource("Source", { string: value });
413 const result = yield* Compute({
414 value: stable ? source.stableString : source.string,
415 });
416 return yield* Function("Host", { env: { RESULT: result.value } });
417 });
418 yield* stack.deploy(program("v1"));
419 const plan = yield* stack.plan(program("v2"));
420 expect(plan.resources.Source.action).toBe("update");
421 expect(plan.actions.Compute.action).toBe(stable ? "noop" : "run");
422 expect(plan.resources.Host.action).toBe(stable ? "noop" : "update");
423 expect(plan.resources.Source.downstream).toContain("Compute");
424 expect(plan.actions.Compute.downstream).toContain("Host");
425 }),
426 );
427 }
428
429 test(
430 "partial stable attributes cannot prove that a whole-resource Action input is unchanged",
431 Effect.gen(function* () {
432 const source = { stableString: "Source", stableArray: ["Source"] };
433 yield* seed({
434 Source: {
435 instanceId,
436 providerVersion: 0,
437 logicalId: "Source",
438 fqn: "Source",
439 namespace: undefined,
440 resourceType: "Test.TestResource",
441 status: "created",
442 props: { string: "v1" },
443 attr: source,
444 bindings: [],
445 downstream: ["Compute"],
446 },
447 });
448 yield* seedAction("Compute", { source }, { value: "v1" });
449 yield* seedHost("v1");
450 const Compute = Action("Compute", (input: { source: { string?: string } }) =>
451 Effect.succeed({ value: input.source.string ?? "v1" }),
452 );
453 const plan = yield* Effect.gen(function* () {
454 const source = yield* TestResource("Source", { string: "v2" });
455 const result = yield* Compute({ source: Output.of(source) });
456 return yield* Function("Host", { name: "host", env: { RESULT: result.value } });
457 }).pipe(makePlan);
458 expect(plan.resources.Source.action).toBe("update");
459 expect(plan.actions.Compute.action).toBe("run");
460 expect(plan.resources.Host.action).toBe("update");
461 }),
462 );
463
464 test(
465 "cyclic Action inputs remain unresolved instead of waiting on their own cached plans",
466 Effect.gen(function* () {
467 const Compute = Action("Compute", (input: { value: string }) => Effect.succeed(input));
468 yield* seedAction("First", { value: "v1" }, { value: "v1" });
469 yield* seedAction("Second", { value: "v1" }, { value: "v1" });
470 const plan = yield* Effect.gen(function* () {
471 const input: { value: Input<string> } = { value: "v1" };
472 const first = yield* Compute("First", input);
473 const second = yield* Compute("Second", { value: first.value });
474 input.value = second.value;
475 return second;
476 }).pipe(makePlan);
477 expect(plan.actions.First.action).toBe("run");
478 expect(plan.actions.Second.action).toBe("run");
479 }),
480 { timeout: 1000 },
481 );
482
483 test(
484 "a resource prop and Action input cycle does not deadlock output resolution",
485 Effect.gen(function* () {
486 const Compute = Action("Compute", (input: { value: string }) => Effect.succeed(input));
487 yield* seedAction("Compute", { value: "v1" }, { value: "v1" });
488 yield* seedHost("v1");
489 const plan = yield* Effect.gen(function* () {
490 const input: { value: Input<string> } = { value: "v1" };
491 const result = yield* Compute(input);
492 const host = yield* Function("Host", { name: "host", env: { RESULT: result.value } });
493 input.value = host.env.RESULT;
494 return host;
495 }).pipe(makePlan);
496 expect(plan.actions.Compute.action).toBe("run");
497 expect(plan.resources.Host.action).toBe("update");
498 }),
499 { timeout: 1000 },
500 );
501
502 test(
503 "a new Action retains its binding dependency without changing host props",
504 Effect.gen(function* () {
505 const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
506 const plan = yield* Effect.gen(function* () {
507 const result = yield* Compute({});
508 const host = yield* BindingTarget("Host", { name: "host" });
509 yield* host.bind("Result", { env: { RESULT: result.value } });
510 return host;
511 }).pipe(makePlan);
512 expect(plan.actions.Compute.downstream).toContain("Host");
513 expect(plan.resources.Host).toMatchObject({ action: "create", props: { name: "host" } });
514 }),
515 );
516 });
517
518 test(
519 "artifacts are isolated by FQN during plan diff for namespaced resources",
520 Effect.gen(function* () {
521 yield* seed({
522 "Left/Shared": {
523 instanceId: "left-instance",
524 providerVersion: 0,
525 logicalId: "Shared",
526 fqn: "Left/Shared",
527 namespace: { Id: "Left" },
528 resourceType: "Test.ArtifactProbe",
529 status: "created",
530 props: { value: "left-v1" },
531 attr: { value: "left-v1", artifactValue: undefined },
532 bindings: [],
533 downstream: [],
534 },
535 "Right/Shared": {
536 instanceId: "right-instance",
537 providerVersion: 0,
538 logicalId: "Shared",
539 fqn: "Right/Shared",
540 namespace: { Id: "Right" },
541 resourceType: "Test.ArtifactProbe",
542 status: "created",
543 props: { value: "right-v1" },
544 attr: { value: "right-v1", artifactValue: undefined },
545 bindings: [],
546 downstream: [],
547 },
548 });
549 const Site = (id: string, props: { value: string }) =>
550 Effect.gen(function* () {
551 return yield* ArtifactProbe("Shared", { value: props.value });
552 }).pipe(Namespace.push(id));
553
554 const plan = yield* Effect.gen(function* () {
555 const left = yield* Site("Left", { value: "left-v2" });
556 const right = yield* Site("Right", { value: "right-v2" });
557 return { left, right };
558 }).pipe(makePlan);
559
560 expect(plan.resources["Left/Shared"]?.action).toEqual("update");
561 expect(plan.resources["Right/Shared"]?.action).toEqual("update");
562 }),
563 { tags: ["unit", "local"] },
564 );
565
566 test(
567 "create all resources when plan is empty",
568 Effect.gen(function* () {
569 expect(
570 yield* Effect.gen(function* () {
571 const bucket = yield* Bucket("MyBucket", { name: "test-bucket" });
572 const queue = yield* Queue("MyQueue", { name: "test-queue" });
573
574 return { queueUrl: queue.queueUrl, bucketArn: bucket.bucketArn };
575 }).pipe(makePlan),
576 ).toMatchObject({
577 resources: {
578 MyBucket: {
579 action: "create",
580 bindings: [],
581 props: { name: "test-bucket" },
582 state: undefined,
583 },
584 MyQueue: {
585 action: "create",
586 bindings: [],
587 props: { name: "test-queue" },
588 state: undefined,
589 },
590 },
591 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
592 });
593 }),
594 { tags: ["unit", "local"] },
595 );
596
597 test(
598 "reports each diffed resource and action as events",
599 Effect.gen(function* () {
600 yield* seed({
601 A: {
602 instanceId,
603 providerVersion: 0,
604 logicalId: "A",
605 fqn: "A",
606 namespace: undefined,
607 resourceType: "Test.BindingTarget",
608 status: "created",
609 props: { name: "target" },
610 attr: { name: "target", env: {} },
611 bindings: [],
612 downstream: [],
613 },
614 });
615 const Announce = Action("Announce", (_: { table: string }) => Effect.succeed(1));
616 const events: Array<Event> = [];
617 yield* Effect.gen(function* () {
618 const target = yield* BindingTarget("A", { name: "target" });
619 yield* target.bind("TestBinding", { env: { FEATURE_FLAG: "on" } });
620 yield* Queue("MyQueue", { name: "test-queue" });
621 yield* Announce({ table: "users" });
622 }).pipe(
623 makePlan,
624 onEvent((event) =>
625 Effect.sync(() => {
626 events.push(event);
627 }),
628 ),
629 );
630
631 // Phase markers land before any node event: state loads, then diffing.
632 expect(events.filter((event) => event.type === "plan.phase").map(({ phase }) => phase)).toEqual(
633 ["loading-state", "computing-plan"],
634 );
635 expect(events[0]).toMatchObject({ type: "plan.phase", phase: "loading-state" });
636 expect(events[1]).toMatchObject({ type: "plan.phase", phase: "computing-plan" });
637
638 // Each resource diff announces its start before the planned completion.
639 expect(
640 events
641 .filter((event) => event.type === "plan.resource.started")
642 .map(({ logicalId }) => logicalId)
643 .sort(),
644 ).toEqual(["A", "MyQueue"]);
645
646 const nodes = events.filter(
647 (event) => event.type === "plan.resource.completed" || event.type === "plan.action.completed",
648 );
649 const byId = Object.fromEntries(nodes.map((event) => [event.logicalId, event]));
650 // resource rows carry their binding rows across the wire
651 expect(byId.A).toMatchObject({
652 type: "plan.resource.completed",
653 action: "update",
654 bindings: [{ sid: "TestBinding", action: "create" }],
655 total: 2,
656 });
657 expect(byId.MyQueue).toMatchObject({
658 type: "plan.resource.completed",
659 action: "create",
660 bindings: [],
661 total: 2,
662 });
663 // stack actions get their own events
664 expect(byId.Announce).toMatchObject({
665 type: "plan.action.completed",
666 actionType: "Announce",
667 action: "run",
668 completed: 1,
669 total: 1,
670 });
671 expect(
672 events
673 .filter((event) => event.type === "plan.resource.completed")
674 .map(({ completed }) => completed)
675 .sort(),
676 ).toEqual([1, 2]);
677 }),
678 { tags: ["unit", "local"] },
679 );
680
681 test(
682 "destroy plans report deletions as events",
683 Effect.gen(function* () {
684 yield* seed({
685 MyBucket: {
686 instanceId,
687 providerVersion: 0,
688 logicalId: "MyBucket",
689 fqn: "MyBucket",
690 namespace: undefined,
691 resourceType: "Test.Bucket",
692 status: "created",
693 props: { name: "test-bucket" },
694 attr: { name: "test-bucket" },
695 bindings: [],
696 downstream: [],
697 },
698 });
699 const events: Array<Event> = [];
700 const { name, stage } = yield* resolveStackId;
701 const plan = yield* Plan.destroy({ name, stage }).pipe(
702 onEvent((event) =>
703 Effect.sync(() => {
704 events.push(event);
705 }),
706 ),
707 Effect.provide(TestLayers()),
708 );
709
710 expect(plan.deletions.MyBucket).toMatchObject({ action: "delete" });
711 expect(events.filter((event) => event.type === "plan.phase").map(({ phase }) => phase)).toEqual(
712 ["loading-state", "computing-plan"],
713 );
714 const nodes = events.filter((event) => event.type === "plan.resource.completed");
715 expect(nodes).toHaveLength(1);
716 expect(nodes[0]).toMatchObject({
717 type: "plan.resource.completed",
718 fqn: "MyBucket",
719 logicalId: "MyBucket",
720 resourceType: "Test.Bucket",
721 action: "delete",
722 bindings: [],
723 completed: 1,
724 total: 1,
725 });
726 }),
727 { tags: ["unit", "local"] },
728 );
729
730 test(
731 "update the changed resources and no-op un-changed resources",
732 Effect.gen(function* () {
733 yield* seed({
734 MyBucket: {
735 instanceId,
736 providerVersion: 0,
737 logicalId: "MyBucket",
738 fqn: "MyBucket",
739 namespace: undefined,
740 resourceType: "Test.Bucket",
741 status: "created",
742 props: { name: "test-bucket" },
743 attr: { name: "test-bucket" },
744 bindings: [],
745 downstream: [],
746 },
747 });
748 expect(
749 yield* makePlan(
750 Effect.gen(function* () {
751 yield* Bucket("MyBucket", { name: "test-bucket" });
752 yield* Queue("MyQueue", { name: "test-queue" });
753 }),
754 ),
755 ).toMatchObject({
756 resources: {
757 MyBucket: { action: "noop", bindings: [], state: { status: "created" } },
758 MyQueue: {
759 action: "create",
760 bindings: [],
761 props: { name: "test-queue" },
762 state: undefined,
763 },
764 },
765 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
766 });
767 }),
768 { tags: ["unit", "local"] },
769 );
770
771 test(
772 "plan downstream resources when a stable kind shadows an output discriminator",
773 Effect.gen(function* () {
774 yield* seed({
775 Database: {
776 instanceId,
777 providerVersion: 0,
778 logicalId: "Database",
779 fqn: "Database",
780 namespace: undefined,
781 resourceType: "Test.KindStablesResource",
782 status: "created",
783 props: { value: "v1" },
784 attr: { kind: "postgresql", value: "v1", upstreamKind: undefined },
785 bindings: [],
786 downstream: [],
787 },
788 });
789
790 const plan = yield* Effect.gen(function* () {
791 const database = yield* KindStablesResource("Database", { value: "v2" });
792 yield* KindStablesResource("Role", { value: "role", upstream: database });
793 }).pipe(makePlan);
794
795 expect(plan.resources.Database!.action).toBe("update");
796 expect(plan.resources.Role!.action).toBe("create");
797 }),
798 { tags: ["unit", "local"] },
799 );
800
801 test(
802 "force changes noop resources into updates",
803 Effect.gen(function* () {
804 yield* seed({
805 MyBucket: {
806 instanceId,
807 providerVersion: 0,
808 logicalId: "MyBucket",
809 fqn: "MyBucket",
810 namespace: undefined,
811 resourceType: "Test.Bucket",
812 status: "created",
813 props: { name: "test-bucket" },
814 attr: { name: "test-bucket" },
815 bindings: [],
816 downstream: [],
817 },
818 });
819 expect(
820 yield* makePlan(
821 Effect.gen(function* () {
822 yield* Bucket("MyBucket", { name: "test-bucket" });
823 }),
824 { force: true },
825 ),
826 ).toMatchObject({
827 resources: {
828 MyBucket: {
829 action: "update",
830 bindings: [],
831 props: { name: "test-bucket" },
832 state: { status: "created" },
833 },
834 },
835 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
836 });
837 }),
838 { tags: ["unit", "local"] },
839 );
840
841 test(
842 "no-op resources with undefined props",
843 Effect.gen(function* () {
844 yield* seed({
845 MyQueue: {
846 instanceId,
847 providerVersion: 0,
848 logicalId: "MyQueue",
849 fqn: "MyQueue",
850 namespace: undefined,
851 resourceType: "Test.Queue",
852 status: "created",
853 props: undefined as any,
854 attr: { name: "MyQueue", queueUrl: "https://test.queue.com/MyQueue" },
855 bindings: [],
856 downstream: [],
857 },
858 });
859 expect(
860 yield* makePlan(
861 Effect.gen(function* () {
862 yield* Queue("MyQueue");
863 }),
864 ),
865 ).toMatchObject({
866 resources: { MyQueue: { action: "noop", bindings: [], state: { status: "created" } } },
867 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
868 });
869 }),
870 { tags: ["unit", "local"] },
871 );
872
873 test(
874 "no-op resources when object prop key order changes",
875 Effect.gen(function* () {
876 yield* seed({
877 MyFunction: {
878 instanceId,
879 providerVersion: 0,
880 logicalId: "MyFunction",
881 fqn: "MyFunction",
882 namespace: undefined,
883 resourceType: "Test.Function",
884 status: "created",
885 props: { name: "test-function", env: { A: "1", B: "2" } },
886 attr: {
887 name: "test-function",
888 env: { A: "1", B: "2" },
889 functionArn: "arn:test:function:MyFunction",
890 },
891 bindings: [],
892 downstream: [],
893 },
894 });
895 expect(
896 yield* makePlan(
897 Effect.gen(function* () {
898 yield* Function("MyFunction", { name: "test-function", env: { B: "2", A: "1" } });
899 }),
900 ),
901 ).toMatchObject({
902 resources: { MyFunction: { action: "noop", bindings: [], state: { status: "created" } } },
903 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
904 });
905 }),
906 { tags: ["unit", "local"] },
907 );
908
909 test(
910 "plan retained resources as orphaned",
911 Effect.gen(function* () {
912 yield* seed({
913 MyBucket: {
914 instanceId,
915 providerVersion: 0,
916 logicalId: "MyBucket",
917 fqn: "MyBucket",
918 namespace: undefined,
919 resourceType: "Test.Bucket",
920 status: "created",
921 props: { name: "test-bucket" },
922 attr: { name: "test-bucket" },
923 bindings: [],
924 downstream: [],
925 removalPolicy: "retain",
926 },
927 MyQueue: {
928 instanceId,
929 providerVersion: 0,
930 logicalId: "MyQueue",
931 fqn: "MyQueue",
932 namespace: undefined,
933 resourceType: "Test.Queue",
934 status: "created",
935 props: { name: "test-queue" },
936 attr: { name: "test-queue" },
937 bindings: [],
938 downstream: [],
939 },
940 });
941 expect(
942 yield* makePlan(
943 Effect.gen(function* () {
944 yield* Queue("MyQueue", { name: "test-queue" });
945 }),
946 ),
947 ).toMatchObject({
948 resources: { MyQueue: { action: "noop", bindings: [], state: { status: "created" } } },
949 deletions: {
950 MyBucket: {
951 action: "orphaned",
952 bindings: [],
953 state: { status: "created", attr: { name: "test-bucket" } },
954 resource: { LogicalId: "MyBucket", Type: "Test.Bucket", Props: { name: "test-bucket" } },
955 },
956 },
957 });
958 }),
959 { tags: ["unit", "local"] },
960 );
961
962 test(
963 "allow deleting a resource after a surviving consumer removes the dependency",
964 Effect.gen(function* () {
965 yield* seed({
966 Secret: {
967 instanceId,
968 providerVersion: 0,
969 logicalId: "Secret",
970 fqn: "Secret",
971 namespace: undefined,
972 resourceType: "Test.TestResource",
973 status: "created",
974 props: { string: "secret-value" },
975 attr: {
976 string: "secret-value",
977 stringArray: [],
978 stableString: "Secret",
979 stableArray: ["Secret"],
980 replaceString: undefined,
981 },
982 bindings: [],
983 downstream: ["Worker"],
984 },
985 Worker: {
986 instanceId,
987 providerVersion: 0,
988 logicalId: "Worker",
989 fqn: "Worker",
990 namespace: undefined,
991 resourceType: "Test.Function",
992 status: "created",
993 props: { name: "worker", env: { SECRET: "secret-value" } },
994 attr: {
995 name: "worker",
996 env: { SECRET: "secret-value" },
997 functionArn: "arn:aws:lambda:us-west-2:084828582823:function:Worker",
998 },
999 bindings: [],
1000 downstream: [],
1001 },
1002 });
1003 expect(
1004 yield* makePlan(
1005 Effect.gen(function* () {
1006 yield* Function("Worker", { name: "worker" });
1007 }),
1008 ),
1009 ).toMatchObject({
1010 resources: { Worker: { action: "update", props: { name: "worker" }, bindings: [] } },
1011 deletions: {
1012 Secret: { action: "delete", state: { status: "created", downstream: ["Worker"] } },
1013 },
1014 });
1015 }),
1016 { tags: ["unit", "local"] },
1017 );
1018
1019 test(
1020 "reject deleting a resource when a surviving consumer still references it",
1021 Effect.gen(function* () {
1022 yield* seed({
1023 Secret: {
1024 instanceId,
1025 providerVersion: 0,
1026 logicalId: "Secret",
1027 fqn: "Secret",
1028 namespace: undefined,
1029 resourceType: "Test.TestResource",
1030 status: "created",
1031 props: { string: "secret-value" },
1032 attr: {
1033 string: "secret-value",
1034 stringArray: [],
1035 stableString: "Secret",
1036 stableArray: ["Secret"],
1037 replaceString: undefined,
1038 },
1039 bindings: [],
1040 downstream: ["Worker"],
1041 },
1042 Worker: {
1043 instanceId,
1044 providerVersion: 0,
1045 logicalId: "Worker",
1046 fqn: "Worker",
1047 namespace: undefined,
1048 resourceType: "Test.Function",
1049 status: "created",
1050 props: { name: "worker", env: { SECRET: "secret-value" } },
1051 attr: {
1052 name: "worker",
1053 env: { SECRET: "secret-value" },
1054 functionArn: "arn:aws:lambda:us-west-2:084828582823:function:Worker",
1055 },
1056 bindings: [],
1057 downstream: [],
1058 },
1059 });
1060 const malformedStack = {
1061 name: TEST_STACK,
1062 stage: TEST_STAGE,
1063 resources: {},
1064 bindings: {},
1065 output: undefined,
1066 };
1067
1068 const exit = yield* Effect.exit(
1069 Effect.gen(function* () {
1070 const secret = yield* TestResource("Secret", { string: "secret-value" });
1071 yield* Function("Worker", { name: "worker", env: { SECRET: secret.string } });
1072 const stack = yield* Stack.Stack;
1073 delete stack.resources.Secret;
1074 }).pipe(makePlanWithCustomStack(malformedStack)),
1075 );
1076
1077 expect(Exit.isFailure(exit)).toBe(true);
1078 if (Exit.isFailure(exit)) {
1079 const reason = exit.cause.reasons.find(Cause.isFailReason);
1080 expect(reason).toBeDefined();
1081 expect(reason!.error).toEqual(
1082 new Plan.DeleteResourceHasDownstreamDependencies({
1083 message: "Resource Secret has downstream dependencies",
1084 resourceId: "Secret",
1085 dependencies: ["Worker"],
1086 }),
1087 );
1088 }
1089 }),
1090 { tags: ["unit", "local"] },
1091 );
1092
1093 // #1831: values a Platform's Init captures reach the provider only through
1094 // `props.env`. `CapturedConfigHost`'s diff always returns `noop`, so these
1095 // actions come from the engine's own comparison of the captured values.
1096 describe("Platform Init-captured config", { tags: ["unit", "local"] }, () => {
1097 const seedHost = (mode: string) =>
1098 seed({
1099 Host: {
1100 instanceId,
1101 providerVersion: 0,
1102 logicalId: "Host",
1103 fqn: "Host",
1104 namespace: undefined,
1105 resourceType: "Test.CapturedConfigHost",
1106 status: "created",
1107 props: { main: "index.ts", env: { CAPTURED_MODE: packEnvValue(Redacted.make(mode)) } },
1108 attr: { mode },
1109 bindings: [],
1110 downstream: [],
1111 },
1112 });
1113
1114 test(
1115 "an unchanged captured value keeps the provider's noop",
1116 Effect.gen(function* () {
1117 yield* seedHost("a");
1118 const plan = yield* capturedConfigHost("a").pipe(makePlan);
1119 expect(plan.resources.Host.action).toBe("noop");
1120 }),
1121 );
1122
1123 test(
1124 "a changed captured value plans an update over the provider's noop",
1125 Effect.gen(function* () {
1126 yield* seedHost("a");
1127 const plan = yield* capturedConfigHost("b").pipe(makePlan);
1128 expect(plan.resources.Host.action).toBe("update");
1129 }),
1130 );
1131 });
1132
1133 describe("replace resource when replaceString changes", { tags: ["unit", "local"] }, () => {
1134 const stateResources: Record<string, ResourceState> = {
1135 A: {
1136 instanceId,
1137 providerVersion: 0,
1138 logicalId: "A",
1139 fqn: "A",
1140 namespace: undefined,
1141 resourceType: "Test.TestResource",
1142 status: "created",
1143 props: { replaceString: "A" },
1144 attr: {},
1145 downstream: [],
1146 bindings: [],
1147 },
1148 };
1149
1150 test(
1151 "noop and replace when replaceString is fully resolved at plan time",
1152 Effect.gen(function* () {
1153 yield* seed(stateResources);
1154 expect(
1155 yield* Effect.gen(function* () {
1156 yield* TestResource("A", { replaceString: "A" });
1157 }).pipe(makePlan),
1158 ).toMatchObject({
1159 resources: { A: { action: "noop" } },
1160 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1161 });
1162
1163 expect(
1164 yield* Effect.gen(function* () {
1165 yield* TestResource("A", { replaceString: "B" });
1166 }).pipe(makePlan),
1167 ).toMatchObject({
1168 resources: { A: { action: "replace", props: { replaceString: "B" } } },
1169 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1170 });
1171 }),
1172 );
1173
1174 test(
1175 "force preserves replaces",
1176 Effect.gen(function* () {
1177 yield* seed(stateResources);
1178 expect(
1179 yield* Effect.gen(function* () {
1180 yield* TestResource("A", { replaceString: "B" });
1181 }).pipe((effect) => makePlan(effect, { force: true })),
1182 ).toMatchObject({
1183 resources: { A: { action: "replace", props: { replaceString: "B" } } },
1184 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1185 });
1186 }),
1187 );
1188
1189 test(
1190 "update when replaceString depends on unresolved output (diff short-circuits)",
1191 Effect.gen(function* () {
1192 yield* seed(stateResources);
1193 let B: TestResource;
1194 expect(
1195 yield* Effect.gen(function* () {
1196 B = yield* TestResource("B", { string: "A" });
1197 yield* TestResource("A", { replaceString: B.string });
1198 }).pipe(makePlan),
1199 ).toMatchObject({
1200 resources: {
1201 A: {
1202 action: "update",
1203 props: {
1204 replaceString: expect.objectContaining({
1205 kind: "PropExpr",
1206 identifier: "string",
1207 expr: expect.objectContaining({ kind: "ResourceExpr", src: B! }),
1208 }),
1209 },
1210 },
1211 },
1212 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1213 });
1214 }),
1215 );
1216 });
1217
1218 test(
1219 "update resource when a binding is added without prop changes",
1220 Effect.gen(function* () {
1221 yield* seed({
1222 A: {
1223 instanceId,
1224 providerVersion: 0,
1225 logicalId: "A",
1226 fqn: "A",
1227 namespace: undefined,
1228 resourceType: "Test.BindingTarget",
1229 status: "created",
1230 props: { name: "target" },
1231 attr: { name: "target", env: {} },
1232 bindings: [],
1233 downstream: [],
1234 },
1235 });
1236 expect(
1237 yield* Effect.gen(function* () {
1238 const target = yield* BindingTarget("A", { name: "target" });
1239 yield* target.bind("TestBinding", { env: { FEATURE_FLAG: "on" } });
1240 }).pipe(makePlan),
1241 ).toMatchObject({
1242 resources: {
1243 A: {
1244 action: "update",
1245 bindings: [
1246 { action: "create", sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } },
1247 ],
1248 state: { status: "created" },
1249 },
1250 },
1251 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1252 });
1253 }),
1254 { tags: ["unit", "local"] },
1255 );
1256
1257 test(
1258 "update resource when a binding is removed without prop changes",
1259 Effect.gen(function* () {
1260 yield* seed({
1261 A: {
1262 instanceId,
1263 providerVersion: 0,
1264 logicalId: "A",
1265 fqn: "A",
1266 namespace: undefined,
1267 resourceType: "Test.BindingTarget",
1268 status: "created",
1269 props: { name: "target" },
1270 attr: { name: "target", env: { FEATURE_FLAG: "on" } },
1271 bindings: [{ sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } }],
1272 downstream: [],
1273 },
1274 });
1275 expect(
1276 yield* Effect.gen(function* () {
1277 yield* BindingTarget("A", { name: "target" });
1278 }).pipe(makePlan),
1279 ).toMatchObject({
1280 resources: {
1281 A: {
1282 action: "update",
1283 bindings: [
1284 { action: "delete", sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } },
1285 ],
1286 state: { status: "created" },
1287 },
1288 },
1289 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1290 });
1291 }),
1292 { tags: ["unit", "local"] },
1293 );
1294
1295 test.provider(
1296 "binding removals do not keep reappearing after apply",
1297 (scratch) =>
1298 Effect.gen(function* () {
1299 const state = yield* yield* State;
1300 yield* state.set({
1301 stack: scratch.name,
1302 stage: scratch.stage,
1303 fqn: "A",
1304 value: {
1305 instanceId,
1306 providerVersion: 0,
1307 logicalId: "A",
1308 fqn: "A",
1309 namespace: undefined,
1310 resourceType: "Test.BindingTarget",
1311 status: "created",
1312 props: { name: "target" },
1313 attr: { name: "target", env: { FEATURE_FLAG: "on" } },
1314 bindings: [{ sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } }],
1315 downstream: [],
1316 },
1317 });
1318
1319 yield* scratch.deploy(
1320 Effect.gen(function* () {
1321 yield* BindingTarget("A", { name: "target" });
1322 }),
1323 );
1324
1325 expect(
1326 yield* state.get({ stack: scratch.name, stage: scratch.stage, fqn: "A" }),
1327 ).toMatchObject({ bindings: [] });
1328
1329 expect(
1330 yield* Effect.gen(function* () {
1331 yield* BindingTarget("A", { name: "target" });
1332 }).pipe(makePlan),
1333 ).toMatchObject({
1334 resources: { A: { action: "noop", bindings: [] } },
1335 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1336 });
1337 }),
1338 { tags: ["unit", "local"] },
1339 );
1340
1341 describe("duplicate bindings are collapsed by sid before diff", { tags: ["unit", "local"] }, () => {
1342 test(
1343 "dedupeBindings keeps the last occurrence of each sid",
1344 Effect.sync(() => {
1345 const deduped = dedupeBindings([
1346 { sid: "Shared", data: { env: { K: "first" } } },
1347 { sid: "Other", data: { env: { K: "x" } } },
1348 { sid: "Shared", data: { env: { K: "last" } } },
1349 ]);
1350
1351 // The duplicated sid takes the last value (matching `diffBindings`'
1352 // `Map`-based collapse) and the result is sid-sorted so binding rows
1353 // are deterministic regardless of registration order.
1354 expect(deduped).toEqual([
1355 { sid: "Other", data: { env: { K: "x" } } },
1356 { sid: "Shared", data: { env: { K: "last" } } },
1357 ]);
1358 }),
1359 );
1360
1361 test(
1362 "diff observes a single binding when the same sid is bound twice",
1363 Effect.gen(function* () {
1364 yield* seed({
1365 A: {
1366 instanceId,
1367 providerVersion: 0,
1368 logicalId: "A",
1369 fqn: "A",
1370 namespace: undefined,
1371 resourceType: "Test.BindingTarget",
1372 status: "created",
1373 props: { name: "target" },
1374 attr: { name: "target", env: {} },
1375 bindings: [],
1376 downstream: [],
1377 },
1378 });
1379
1380 // Capture the exact binding list the provider's `diff` receives.
1381 const observed: ResourceBinding[][] = [];
1382
1383 const plan = yield* Effect.gen(function* () {
1384 const target = yield* BindingTarget("A", { name: "target" });
1385 // The same sid is recorded twice — mirrors a single KV namespace
1386 // bound to two consumers that both attach it to the same target,
1387 // which pushes a duplicate into `stack.bindings[fqn]`.
1388 yield* target.bind("Shared", { env: { FEATURE_FLAG: "on" } });
1389 yield* target.bind("Shared", { env: { FEATURE_FLAG: "on" } });
1390 }).pipe(
1391 makePlan,
1392 Effect.provideService(TestResourceHooks, {
1393 diff: (_id, newBindings) =>
1394 Effect.sync(() => {
1395 observed.push(newBindings);
1396 }),
1397 }),
1398 );
1399
1400 // Before the fix, `diff` saw the raw duplicate pair (length 2) while
1401 // `reconcile` saw a deduped list — an inconsistency that made hashing
1402 // unstable. Every diff invocation must now see the collapsed list.
1403 expect(observed.length).toBeGreaterThan(0);
1404 for (const seen of observed) {
1405 expect(seen).toHaveLength(1);
1406 expect(seen[0]).toMatchObject({ sid: "Shared", data: { env: { FEATURE_FLAG: "on" } } });
1407 }
1408
1409 // The plan node likewise collapses to a single create binding.
1410 expect(plan.resources.A).toMatchObject({
1411 action: "update",
1412 bindings: [{ action: "create", sid: "Shared", data: { env: { FEATURE_FLAG: "on" } } }],
1413 });
1414 }),
1415 );
1416 });
1417
1418 describe("construct namespaces", { tags: ["unit", "local"] }, () => {
1419 test(
1420 "namespaced construct bindings resolve into the plan graph",
1421 Effect.gen(function* () {
1422 const Site = (id: string, _props: {}) =>
1423 Effect.gen(function* () {
1424 const bucket = yield* BindingTarget("Bucket", { name: "bucket" });
1425 const distribution = yield* BindingTarget("Distribution", { name: "distribution" });
1426 yield* bucket.bind("Policy", {
1427 env: { BUCKET: bucket.string, DISTRIBUTION: distribution.string },
1428 });
1429 return { bucket, distribution };
1430 }).pipe(Namespace.push(id));
1431
1432 const plan = yield* Effect.gen(function* () {
1433 yield* Site("MarketingSite", {});
1434 }).pipe(makePlan);
1435
1436 expect(plan).toMatchObject({
1437 resources: {
1438 "MarketingSite/Bucket": {
1439 action: "create",
1440 bindings: [
1441 {
1442 action: "create",
1443 sid: "Policy",
1444 data: {
1445 env: {
1446 BUCKET: expect.objectContaining({
1447 kind: "PropExpr",
1448 identifier: "string",
1449 expr: expect.objectContaining({
1450 kind: "ResourceExpr",
1451 src: plan.resources["MarketingSite/Bucket"]!.resource,
1452 }),
1453 }),
1454 DISTRIBUTION: expect.objectContaining({
1455 kind: "PropExpr",
1456 identifier: "string",
1457 expr: expect.objectContaining({
1458 kind: "ResourceExpr",
1459 src: plan.resources["MarketingSite/Distribution"]!.resource,
1460 }),
1461 }),
1462 },
1463 },
1464 },
1465 ],
1466 },
1467 "MarketingSite/Distribution": { action: "create", bindings: [] },
1468 },
1469 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1470 });
1471 }),
1472 );
1473
1474 test(
1475 "same child logical ids in different constructs do not collide",
1476 Effect.gen(function* () {
1477 const Site = (id: string, props: { name: string }) =>
1478 Effect.gen(function* () {
1479 return yield* Bucket("Bucket", { name: props.name });
1480 }).pipe(Namespace.push(id));
1481
1482 const plan = yield* Effect.gen(function* () {
1483 yield* Site("MarketingSite", { name: "marketing-bucket" });
1484 yield* Site("DocsSite", { name: "docs-bucket" });
1485 }).pipe(makePlan);
1486
1487 expect(plan).toMatchObject({
1488 resources: {
1489 "MarketingSite/Bucket": { action: "create", props: { name: "marketing-bucket" } },
1490 "DocsSite/Bucket": { action: "create", props: { name: "docs-bucket" } },
1491 },
1492 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1493 });
1494 }),
1495 );
1496
1497 test(
1498 "binding-only cycles inside a construct do not become downstream edges",
1499 Effect.gen(function* () {
1500 const Site = (id: string, _props: {}) =>
1501 Effect.gen(function* () {
1502 const A = yield* BindingTarget("A", { string: "a-value" });
1503 const B = yield* BindingTarget("B", { string: "b-value" });
1504
1505 yield* A.bind("FromB", { env: { PEER: B.string } });
1506 yield* B.bind("FromA", { env: { PEER: A.string } });
1507
1508 return { A, B };
1509 }).pipe(Namespace.push(id));
1510
1511 const plan = yield* Effect.gen(function* () {
1512 yield* Site("MarketingSite", {});
1513 }).pipe(makePlan);
1514
1515 expect(plan.resources["MarketingSite/A"]?.downstream).toEqual([]);
1516 expect(plan.resources["MarketingSite/B"]?.downstream).toEqual([]);
1517 expect(plan.deletions).toEqual({});
1518 }),
1519 );
1520 });
1521
1522 const createTestResourceState = (options: {
1523 logicalId: string;
1524 status: ResourceStatus;
1525 props: TestResourceProps;
1526 attr?: {};
1527 }) =>
1528 ({
1529 instanceId,
1530 providerVersion: 0,
1531 ...options,
1532 resourceType: "Test.TestResource",
1533 attr: options.attr ?? {},
1534 downstream: [],
1535 bindings: [],
1536 fqn: options.logicalId,
1537 namespace: undefined,
1538 }) as ResourceState;
1539
1540 const createReplacingState = (options: {
1541 logicalId: string;
1542 props: TestResourceProps;
1543 old: ResourceState;
1544 attr?: {};
1545 }) =>
1546 ({
1547 ...createTestResourceState({
1548 logicalId: options.logicalId,
1549 status: "replacing",
1550 props: options.props,
1551 attr: options.attr,
1552 }),
1553 old: options.old,
1554 deleteFirst: false,
1555 }) as Extract<ResourceState, { status: "replacing" }>;
1556
1557 const createReplacedState = (options: {
1558 logicalId: string;
1559 props: TestResourceProps;
1560 old: ResourceState;
1561 attr?: {};
1562 }) =>
1563 ({
1564 ...createTestResourceState({
1565 logicalId: options.logicalId,
1566 status: "replaced",
1567 props: options.props,
1568 attr: options.attr,
1569 }),
1570 old: options.old,
1571 deleteFirst: false,
1572 }) as Extract<ResourceState, { status: "replaced" }>;
1573
1574 const testSimple = (
1575 title: string,
1576 testCase: {
1577 state: {
1578 status: ResourceStatus;
1579 props: TestResourceProps;
1580 attr?: {};
1581 old?: Partial<ResourceState>;
1582 };
1583 props: TestResourceProps;
1584 plan?: any;
1585 fail?: string;
1586 },
1587 ) =>
1588 test(
1589 title,
1590 Effect.gen(function* () {
1591 yield* seed({ A: createTestResourceState({ ...testCase.state, logicalId: "A" }) });
1592 {
1593 const plan = Effect.gen(function* () {
1594 yield* TestResource("A", testCase.props);
1595 }).pipe(makePlan);
1596
1597 if (testCase.fail) {
1598 const result = plan.pipe(
1599 Effect.map(() => false),
1600 // @ts-expect-error
1601 Effect.catchTag(testCase.fail, () => Effect.succeed(true)),
1602 Effect.catch(() => Effect.succeed(false)),
1603 ) as Effect.Effect<boolean>;
1604 if (!result) {
1605 expect.fail(`Expected error '${testCase.fail}`);
1606 }
1607 } else {
1608 expect(yield* plan).toMatchObject({
1609 resources: { A: testCase.plan },
1610 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1611 });
1612 }
1613 }
1614 }),
1615 { tags: ["unit", "local"] },
1616 );
1617
1618 describe("prior crash in 'creating' state", () => {
1619 testSimple("create if props unchanged", {
1620 state: { status: "creating", props: { string: "A" } },
1621 props: { string: "A" },
1622 plan: { action: "create", props: { string: "A" } },
1623 });
1624
1625 testSimple("create if changed props can be updated", {
1626 state: { status: "creating", props: { string: "A" } },
1627 props: { string: "B" },
1628 plan: { action: "create", props: { string: "B" } },
1629 });
1630
1631 testSimple("replace if changed props cannot be updated", {
1632 state: { status: "creating", props: { replaceString: "A" } },
1633 props: { replaceString: "B" },
1634 plan: {
1635 action: "replace",
1636 props: { replaceString: "B" },
1637 state: { status: "creating", props: { replaceString: "A" } },
1638 },
1639 });
1640 });
1641
1642 describe("prior crash in 'updating' state", () => {
1643 testSimple("update if props unchanged", {
1644 state: { status: "updating", props: { string: "A" } },
1645 props: { string: "A" },
1646 plan: {
1647 action: "update",
1648 props: { string: "A" },
1649 state: { status: "updating", props: { string: "A" } },
1650 },
1651 });
1652
1653 testSimple("update if changed props can be updated", {
1654 state: { status: "updating", props: { string: "A" } },
1655 props: { string: "B" },
1656 plan: {
1657 action: "update",
1658 props: { string: "B" },
1659 state: { status: "updating", props: { string: "A" } },
1660 },
1661 });
1662
1663 testSimple("replace if changed props can not be updated", {
1664 state: { status: "updating", props: { replaceString: "A" } },
1665 props: { replaceString: "B" },
1666 plan: {
1667 action: "replace",
1668 props: { replaceString: "B" },
1669 state: { status: "updating", props: { replaceString: "A" } },
1670 },
1671 });
1672 });
1673
1674 describe("pending replacement deletion plans", { tags: ["unit", "local"] }, () => {
1675 for (const status of ["replacing", "replaced"] as const) {
1676 test(
1677 `preserves the complete ${status} chain and all generation dependencies`,
1678 Effect.gen(function* () {
1679 const oldest: ResourceState = {
1680 status: "created",
1681 fqn: "R",
1682 logicalId: "R",
1683 namespace: undefined,
1684 instanceId: "oldest",
1685 resourceType: "Test.ModalResource",
1686 providerVersion: 0,
1687 props: { value: "one" },
1688 attr: { value: "one", runtime: "live" },
1689 providerMode: "live",
1690 downstream: ["OldDependent"],
1691 bindings: [],
1692 };
1693 const middle: ResourceState = {
1694 ...oldest,
1695 status: "replacing",
1696 instanceId: "middle",
1697 props: { value: "two" },
1698 attr: undefined,
1699 providerMode: "local",
1700 downstream: ["MiddleDependent"],
1701 deleteFirst: false,
1702 old: oldest,
1703 };
1704 const pending: ResourceState = {
1705 ...oldest,
1706 status,
1707 instanceId: "newest",
1708 props: { value: "three" },
1709 attr: { value: "three", runtime: "live" },
1710 downstream: ["NewDependent"],
1711 deleteFirst: false,
1712 old: middle,
1713 };
1714 yield* seed({ R: pending });
1715 const plan = yield* makePlan(Effect.void);
1716 expect(plan.deletions.R?.action).toBe("delete");
1717 expect(plan.deletions.R?.mode).toBe("live");
1718 expect(plan.deletions.R?.state).toEqual(pending);
1719 expect(plan.deletions.R?.downstream).toEqual([
1720 "NewDependent",
1721 "MiddleDependent",
1722 "OldDependent",
1723 ]);
1724 const state = yield* yield* State;
1725 expect(yield* state.get({ stack: TEST_STACK, stage: TEST_STAGE, fqn: "R" })).toEqual(
1726 pending,
1727 );
1728 }),
1729 );
1730 }
1731 });
1732
1733 describe("prior crash in 'replacing' state", () => {
1734 const priorStates = ["created", "creating", "updated", "updating"] as const;
1735
1736 const testUnchanged = ({ old }: { old: { status: ResourceStatus } }) =>
1737 testSimple(
1738 `"continue 'replace' if props are unchanged and previous state is '${old.status}'"`,
1739 {
1740 state: { status: "replacing", props: { string: "A" }, old },
1741 props: { string: "A" },
1742 plan: {
1743 action: "replace",
1744 props: { string: "A" },
1745 state: { status: "replacing", props: { string: "A" }, old },
1746 },
1747 },
1748 );
1749
1750 priorStates.forEach((status) => testUnchanged({ old: { status } }));
1751
1752 const testMinorChange = ({ old }: { old: { status: ResourceStatus } }) =>
1753 testSimple(
1754 `"continue 'replace' if props can be updated and previous state is '${old.status}'"`,
1755 {
1756 state: { status: "replacing", props: { string: "A" }, old },
1757 props: { string: "B" },
1758 plan: {
1759 action: "replace",
1760 props: { string: "B" },
1761 state: { status: "replacing", props: { string: "A" }, old },
1762 },
1763 },
1764 );
1765
1766 priorStates.forEach((status) => testMinorChange({ old: { status } }));
1767
1768 const testReplacement = (title: string, { old, plan }: { old: ResourceState; plan: any }) =>
1769 testSimple(title, {
1770 state: { status: "replacing", props: { replaceString: "A" }, old },
1771 props: { replaceString: "B" },
1772 plan,
1773 });
1774
1775 (["replaced", "replacing"] as const).forEach((status) =>
1776 testReplacement(
1777 `continue 'replace' if trying to replace a partially replaced resource in state '${status}'`,
1778 {
1779 old:
1780 status === "replaced"
1781 ? createReplacedState({
1782 logicalId: "A_old1",
1783 props: { replaceString: "A1" },
1784 old: createTestResourceState({
1785 logicalId: "A_old0",
1786 status: "created",
1787 props: { replaceString: "A0" },
1788 }),
1789 })
1790 : createReplacingState({
1791 logicalId: "A_old1",
1792 props: { replaceString: "A1" },
1793 old: createTestResourceState({
1794 logicalId: "A_old0",
1795 status: "created",
1796 props: { replaceString: "A0" },
1797 }),
1798 }),
1799 plan: {
1800 action: "replace",
1801 props: { replaceString: "B" },
1802 state: {
1803 status: "replacing",
1804 props: { replaceString: "A" },
1805 old: expect.objectContaining({
1806 status,
1807 props: { replaceString: "A1" },
1808 old: expect.objectContaining({ status: "created", props: { replaceString: "A0" } }),
1809 }),
1810 },
1811 },
1812 },
1813 ),
1814 );
1815 });
1816
1817 describe("prior crash in 'replaced' state", () => {
1818 (["replaced", "replacing"] as const).forEach((status) =>
1819 testSimple(
1820 `continue 'replace' if a replaced resource must be replaced again and previous state is '${status}'`,
1821 {
1822 state: {
1823 status: "replaced",
1824 props: { replaceString: "A1" },
1825 old:
1826 status === "replaced"
1827 ? createReplacedState({
1828 logicalId: "A_old0",
1829 props: { replaceString: "A0" },
1830 old: createTestResourceState({
1831 logicalId: "A_old-1",
1832 status: "created",
1833 props: { replaceString: "A-1" },
1834 }),
1835 })
1836 : createReplacingState({
1837 logicalId: "A_old0",
1838 props: { replaceString: "A0" },
1839 old: createTestResourceState({
1840 logicalId: "A_old-1",
1841 status: "created",
1842 props: { replaceString: "A-1" },
1843 }),
1844 }),
1845 },
1846 props: { replaceString: "B" },
1847 plan: {
1848 action: "replace",
1849 props: { replaceString: "B" },
1850 state: {
1851 status: "replaced",
1852 props: { replaceString: "A1" },
1853 old: expect.objectContaining({
1854 status,
1855 props: { replaceString: "A0" },
1856 old: expect.objectContaining({ status: "created", props: { replaceString: "A-1" } }),
1857 }),
1858 },
1859 },
1860 },
1861 ),
1862 );
1863 });
1864
1865 describe("prior crash in 'deleting' state", () => {
1866 testSimple("create the resource if props are unchanged and the previous state is 'deleting'", {
1867 state: { status: "deleting", props: { string: "A" } },
1868 props: { string: "A" },
1869 plan: { action: "create", props: { string: "A" } },
1870 });
1871 });
1872
1873 test(
1874 "lazy Output queue.queueUrl to Function.env",
1875 Effect.gen(function* () {
1876 let MyQueue: Queue;
1877 let MyFunction: Function;
1878 const plan = yield* Effect.gen(function* () {
1879 MyQueue = yield* Queue("MyQueue");
1880 MyFunction = yield* Function("MyFunction", {
1881 name: "test-function",
1882 env: { QUEUE_URL: MyQueue.queueUrl },
1883 });
1884 }).pipe(makePlan);
1885 expect(plan).toMatchObject({
1886 resources: {
1887 MyFunction: {
1888 action: "create",
1889 bindings: [],
1890 resource: MyFunction!,
1891 props: {
1892 name: "test-function",
1893 env: {
1894 QUEUE_URL: expect.objectContaining({
1895 kind: "PropExpr",
1896 identifier: "queueUrl",
1897 expr: expect.objectContaining({ kind: "ResourceExpr", src: MyQueue! }),
1898 }),
1899 },
1900 },
1901 state: undefined,
1902 },
1903 },
1904 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1905 });
1906 }),
1907 { tags: ["unit", "local"] },
1908 );
1909
1910 test(
1911 "detect that queueUrl will change and pass through the PropExpr instead of old output",
1912 Effect.gen(function* () {
1913 yield* seed({
1914 MyQueue: {
1915 instanceId,
1916 providerVersion: 0,
1917 logicalId: "MyQueue",
1918 fqn: "MyQueue",
1919 namespace: undefined,
1920 resourceType: "Test.Queue",
1921 status: "created",
1922 props: { name: "test-queue-old" },
1923 attr: { queueUrl: "https://test.queue.com/test-queue-old" },
1924 downstream: [],
1925 bindings: [],
1926 },
1927 });
1928 let MyQueue: Queue;
1929 let MyFunction: Function;
1930 const plan = yield* Effect.gen(function* () {
1931 MyQueue = yield* Queue("MyQueue");
1932 MyFunction = yield* Function("MyFunction", {
1933 name: "test-function",
1934 env: { QUEUE_URL: MyQueue.queueUrl },
1935 });
1936 }).pipe(makePlan);
1937 expect(plan).toMatchObject({
1938 resources: {
1939 MyFunction: {
1940 action: "create",
1941 bindings: [],
1942 resource: MyFunction!,
1943 props: {
1944 name: "test-function",
1945 env: {
1946 QUEUE_URL: expect.objectContaining({
1947 kind: "PropExpr",
1948 identifier: "queueUrl",
1949 expr: expect.objectContaining({ kind: "ResourceExpr", src: MyQueue! }),
1950 }),
1951 },
1952 },
1953 state: undefined,
1954 },
1955 },
1956 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1957 });
1958 }),
1959 { tags: ["unit", "local"] },
1960 );
1961
1962 describe("Outputs should resolve to old values", { tags: ["unit", "local"] }, () => {
1963 const stateResources: Record<string, ResourceState> = {
1964 A: {
1965 instanceId,
1966 providerVersion: 0,
1967 logicalId: "A",
1968 fqn: "A",
1969 namespace: undefined,
1970 resourceType: "Test.TestResource",
1971 status: "created",
1972 props: { string: "test-string", stringArray: ["test-string"] },
1973 attr: { string: "test-string", stringArray: ["test-string"] },
1974 downstream: [],
1975 bindings: [],
1976 },
1977 };
1978
1979 const expected = (props: Input.Resolve<InputProps<TestResourceProps>>) => ({
1980 resources: {
1981 A: { action: "noop", bindings: [] },
1982 B: { action: "create", bindings: [], props: props },
1983 },
1984 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
1985 });
1986
1987 const subtest = <const I extends InputProps<TestResourceProps>>(
1988 description: string,
1989 input: (resource: TestResource) => I,
1990 attr: Input.Resolve<I>,
1991 ) =>
1992 test(
1993 description,
1994 Effect.gen(function* () {
1995 yield* seed(stateResources);
1996 expect(
1997 yield* Effect.gen(function* () {
1998 const A = yield* TestResource("A", {
1999 string: "test-string",
2000 stringArray: ["test-string"],
2001 });
2002 yield* TestResource("B", input(A));
2003 }).pipe(makePlan),
2004 ).toMatchObject(expected(attr));
2005 }),
2006 );
2007
2008 subtest("string", (A) => ({ string: A.string }), { string: "test-string" });
2009
2010 subtest(
2011 "string.apply(string => undefined)",
2012 (A) => ({ string: A.string.pipe(Output.map(() => undefined)) }),
2013 { string: undefined },
2014 );
2015
2016 subtest(
2017 "string.effect(string => Effect.succeed(undefined))",
2018 (A) => ({ string: A.string.pipe(Output.mapEffect(() => Effect.succeed(undefined))) }),
2019 { string: undefined },
2020 );
2021
2022 subtest(
2023 "string.flatMap(() => Output.literal(undefined))",
2024 (A) => ({ string: A.string.pipe(Output.flatMap(() => Output.literal(undefined))) }),
2025 { string: undefined },
2026 );
2027
2028 subtest(
2029 "string.flatMap(string => A.stringArray.map(([first]) => first))",
2030 (A) => ({
2031 string: A.string.pipe(
2032 Output.flatMap(() =>
2033 A.stringArray.pipe(Output.map((stringArray) => stringArray[0]!.toUpperCase())),
2034 ),
2035 ),
2036 }),
2037 { string: "TEST-STRING" },
2038 );
2039
2040 subtest(
2041 "stringArray[0].toUpperCase()",
2042 (A) => ({
2043 string: A.stringArray.pipe(Output.map((stringArray) => stringArray[0]!.toUpperCase())),
2044 }),
2045 { string: "TEST-STRING" },
2046 );
2047
2048 subtest("resource object", (A) => ({ object: A as any }), {
2049 object: { string: "test-string" },
2050 } as any);
2051 });
2052
2053 describe(
2054 "raw Resource refs in props are tracked as upstream dependencies",
2055 { tags: ["unit", "local"] },
2056 () => {
2057 test(
2058 "raw Resource passed directly as a prop value populates the upstream's downstream",
2059 Effect.gen(function* () {
2060 const plan = yield* Effect.gen(function* () {
2061 const A = yield* TestResource("A", { string: "a-value" });
2062 yield* TestResource("B", { object: A as any });
2063 }).pipe(makePlan);
2064
2065 expect(plan.resources.A!.downstream).toEqual(["B"]);
2066 expect(plan.resources.B!.downstream).toEqual([]);
2067 }),
2068 );
2069
2070 test(
2071 "raw Resources nested in arrays/objects are tracked as upstream dependencies",
2072 Effect.gen(function* () {
2073 const plan = yield* Effect.gen(function* () {
2074 const A = yield* TestResource("A", { string: "a-value" });
2075 const B = yield* TestResource("B", { string: "b-value" });
2076 yield* TestResource("C", { stringArray: [A] as any, object: { ref: B } as any });
2077 }).pipe(makePlan);
2078
2079 expect(plan.resources.A!.downstream).toEqual(["C"]);
2080 expect(plan.resources.B!.downstream).toEqual(["C"]);
2081 expect(plan.resources.C!.downstream).toEqual([]);
2082 }),
2083 );
2084 },
2085 );
2086
2087 describe(
2088 "stable properties should not cause downstream changes",
2089 { tags: ["unit", "local"] },
2090 () => {
2091 const subtest = (
2092 description: string,
2093 input: (A: TestResource) => InputProps<TestResourceProps>,
2094 ) => {
2095 // @ts-expect-error - get the keys
2096 const props = input(Output.of({}));
2097 test(
2098 description,
2099 Effect.gen(function* () {
2100 yield* seed({
2101 A: {
2102 instanceId,
2103 providerVersion: 0,
2104 logicalId: "A",
2105 fqn: "A",
2106 namespace: undefined,
2107 resourceType: "Test.TestResource",
2108 status: "created",
2109 props: { string: "test-string-old" },
2110 attr: { string: "test-string-old", stableString: "A", stableArray: ["A"] },
2111 downstream: [],
2112 bindings: [],
2113 },
2114 B: {
2115 instanceId,
2116 providerVersion: 0,
2117 logicalId: "B",
2118 fqn: "B",
2119 namespace: undefined,
2120 resourceType: "Test.TestResource",
2121 status: "created",
2122 props: Object.fromEntries(
2123 Object.entries({ string: "A", stringArray: ["A"] }).filter(([key]) => key in props),
2124 ),
2125 attr: { stableString: "A" },
2126 downstream: [],
2127 bindings: [],
2128 },
2129 });
2130 expect(
2131 yield* Effect.gen(function* () {
2132 const A = yield* TestResource("A", { string: "test-string" });
2133 yield* TestResource("B", input(A));
2134 }).pipe(makePlan),
2135 ).toMatchObject({
2136 resources: {
2137 A: { action: "update", props: { string: "test-string" } },
2138 B: { action: "noop" },
2139 },
2140 deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
2141 });
2142 }),
2143 );
2144 };
2145
2146 subtest("A.stableString", (A) => ({ string: A.stableString }));
2147
2148 subtest("A.stableString.apply((string) => string.toUpperCase())", (A) => ({
2149 string: A.stableString.pipe(Output.map((string) => string.toUpperCase())),
2150 }));
2151
2152 subtest("A.stableString.effect((string) => Effect.succeed(string.toUpperCase()))", (A) => ({
2153 string: A.stableString.pipe(
2154 Output.mapEffect((string) => Effect.succeed(string.toUpperCase())),
2155 ),
2156 }));
2157
2158 subtest("A.stableString.flatMap((string) => Output.literal(string.toUpperCase()))", (A) => ({
2159 string: A.stableString.pipe(Output.flatMap((string) => Output.literal(string.toUpperCase()))),
2160 }));
2161
2162 subtest("A.stableArray", (A) => ({ stringArray: A.stableArray }));
2163
2164 subtest("A.stableArray[0]", (A) => ({
2165 string: A.stableArray.pipe(Output.map((stableArray) => stableArray[0]!)),
2166 }));
2167
2168 subtest("A.stableArray[0].apply((string) => string.toUpperCase())", (A) => ({
2169 string: A.stableArray.pipe(Output.map((stableArray) => stableArray[0]!.toUpperCase())),
2170 }));
2171
2172 subtest("A.stableArray[0].effect((string) => Effect.succeed(string.toUpperCase()))", (A) => ({
2173 string: A.stableArray.pipe(
2174 Output.mapEffect((stableArray) => Effect.succeed(stableArray[0]!.toUpperCase())),
2175 ),
2176 }));
2177 },
2178 );
2179
2180 describe(
2181 "whole-resource refs resolve to the upstream's stable attributes",
2182 { tags: ["unit", "local"] },
2183 () => {
2184 // Regression: when a resource is referenced *whole* (e.g. `object: A`)
2185 // rather than via a single prop (`A.stableString`), and the upstream is
2186 // being updated in place, `resolveResource` returns a `ResourceExpr`
2187 // carrying only the stable attributes. Previously `resolveInput` handed
2188 // that `ResourceExpr` to the downstream verbatim, so its `news` looked
2189 // unresolved (`isResolved(news) === false`) and the stable values never
2190 // reached the downstream `diff`. This forced the Neon `Branch` to manually
2191 // extract `project.projectId` as a workaround. The engine materializes the
2192 // known stable attributes into a plain object for the DIFF-facing `news`
2193 // so the stable values flow into the diff and the downstream can no-op.
2194 //
2195 // The plan node's `props`, however, must keep the reference as an
2196 // evaluable `ResourceExpr`: Apply re-resolves `node.props` against the
2197 // upstream's fresh post-reconcile attributes, and a materialized
2198 // stables-only snapshot would permanently hide every non-stable attribute
2199 // from the downstream's `reconcile` (e.g. a Lambda Alias promoting a
2200 // freshly-published Lambda Version would never see the new version
2201 // number — #993's alias promotion bug).
2202 const seedUpdatingUpstream = () =>
2203 seed({
2204 A: {
2205 instanceId,
2206 providerVersion: 0,
2207 logicalId: "A",
2208 fqn: "A",
2209 namespace: undefined,
2210 resourceType: "Test.TestResource",
2211 status: "created",
2212 props: { string: "old-value" },
2213 attr: { string: "old-value", stableString: "A", stableArray: ["A"] },
2214 downstream: [],
2215 bindings: [],
2216 },
2217 });
2218
2219 test(
2220 "the node's whole-resource ref stays an evaluable Expr carrying the stable attributes",
2221 Effect.gen(function* () {
2222 yield* seedUpdatingUpstream();
2223
2224 let A: TestResource;
2225 const plan = yield* Effect.gen(function* () {
2226 // A is updated in place: `string` changes, but `stableString` /
2227 // `stableArray` are declared stable by its diff.
2228 A = yield* TestResource("A", { string: "new-value" });
2229 // B (created fresh) references the WHOLE upstream resource, not a
2230 // single prop — so its plan node carries the resolved `props`.
2231 yield* TestResource("B", { object: A as any });
2232 }).pipe(makePlan);
2233
2234 expect(plan.resources.A!.action).toBe("update");
2235
2236 const bProps = (plan.resources.B as any).props as TestResourceProps;
2237 // The node's props keep the whole-resource ref as an evaluable
2238 // `ResourceExpr` (so Apply resolves the upstream's FRESH attributes
2239 // after its reconcile), with the stable attributes riding along for
2240 // plan-time consumers.
2241 expect(Output.isExpr(bProps.object)).toBe(true);
2242 expect(Output.isResourceExpr(bProps.object)).toBe(true);
2243 expect((bProps.object as any as Output.ResourceExpr<any>).stables).toEqual({
2244 stableString: "A",
2245 stableArray: ["A"],
2246 });
2247 }),
2248 );
2249
2250 test(
2251 "a whole-resource ref to an updating upstream does not drag the downstream into an update",
2252 Effect.gen(function* () {
2253 yield* seedUpdatingUpstream();
2254 yield* seed({
2255 B: {
2256 instanceId,
2257 providerVersion: 0,
2258 logicalId: "B",
2259 fqn: "B",
2260 namespace: undefined,
2261 resourceType: "Test.TestResource",
2262 status: "created",
2263 // B's prior props captured the upstream's stable attributes —
2264 // exactly what a materialized whole-resource ref resolves to.
2265 props: { object: { stableString: "A", stableArray: ["A"] } as any },
2266 attr: { string: "B", stableString: "B", stableArray: ["B"] },
2267 downstream: [],
2268 bindings: [],
2269 },
2270 });
2271
2272 let A: TestResource;
2273 const plan = yield* Effect.gen(function* () {
2274 A = yield* TestResource("A", { string: "new-value" });
2275 yield* TestResource("B", { object: A as any });
2276 }).pipe(makePlan);
2277
2278 expect(plan.resources.A!.action).toBe("update");
2279 // Only stable attributes flow in and they are unchanged, so the
2280 // downstream no-ops instead of being dragged into a needless update.
2281 expect(plan.resources.B!.action).toBe("noop");
2282 }),
2283 );
2284
2285 // The binding path mirrors the props split: `diffBindings` compares the
2286 // materialized (stables-only) view, but the node's binding rows carry the
2287 // apply-faithful payload so `Output.evaluate(node.bindings, outputs)`
2288 // re-resolves the upstream's fresh post-reconcile attributes.
2289 const seedHostWithFullPayload = () =>
2290 seed({
2291 Host: {
2292 instanceId,
2293 providerVersion: 0,
2294 logicalId: "Host",
2295 fqn: "Host",
2296 namespace: undefined,
2297 resourceType: "Test.BindingTarget",
2298 status: "created",
2299 props: { name: "host" },
2300 attr: { name: "host", string: "Host", env: {}, replaceString: undefined },
2301 downstream: [],
2302 // Terminal commits persist the payload the provider reconciled
2303 // with — the upstream's FULL attributes (#874), not the plan-time
2304 // stables-only projection.
2305 bindings: [
2306 {
2307 sid: "FromA",
2308 data: { env: { A: { string: "old-value", stableString: "A", stableArray: ["A"] } } },
2309 },
2310 ],
2311 },
2312 });
2313
2314 const hostProgram = (upstreamString: string) =>
2315 Effect.gen(function* () {
2316 const A = yield* TestResource("A", { string: upstreamString });
2317 const host = yield* BindingTarget("Host", { name: "host" });
2318 // The binding data embeds the WHOLE upstream resource.
2319 yield* host.bind("FromA", { env: { A } } as any);
2320 });
2321
2322 test(
2323 "the node's binding payload keeps the whole-resource ref as an evaluable Expr carrying the stable attributes",
2324 Effect.gen(function* () {
2325 yield* seedUpdatingUpstream();
2326
2327 const plan = yield* hostProgram("new-value").pipe(makePlan);
2328
2329 expect(plan.resources.A!.action).toBe("update");
2330
2331 const rows = (plan.resources.Host as any).bindings;
2332 expect(rows).toHaveLength(1);
2333 expect(rows[0].sid).toBe("FromA");
2334 const payload = rows[0].data.env.A;
2335 expect(Output.isResourceExpr(payload)).toBe(true);
2336 expect((payload as Output.ResourceExpr<any>).stables).toEqual({
2337 stableString: "A",
2338 stableArray: ["A"],
2339 });
2340 }),
2341 );
2342
2343 test(
2344 "an updating upstream marks the binding row 'update' from the materialized comparison while the payload stays evaluable",
2345 Effect.gen(function* () {
2346 yield* seedUpdatingUpstream();
2347 yield* seedHostWithFullPayload();
2348
2349 const plan = yield* hostProgram("new-value").pipe(makePlan);
2350
2351 expect(plan.resources.A!.action).toBe("update");
2352 // The host's own props are unchanged; the binding drift alone drags
2353 // it into the update that re-delivers A's fresh attributes.
2354 expect(plan.resources.Host!.action).toBe("update");
2355
2356 const rows = (plan.resources.Host as any).bindings;
2357 expect(rows).toHaveLength(1);
2358 // Action from the materialized comparison (persisted full attrs vs
2359 // stables-only projection)...
2360 expect(rows[0].action).toBe("update");
2361 // ...payload from the apply-faithful resolution.
2362 expect(Output.isResourceExpr(rows[0].data.env.A)).toBe(true);
2363 }),
2364 );
2365
2366 test(
2367 "an unchanged upstream's full persisted binding payload no-ops instead of churning",
2368 Effect.gen(function* () {
2369 yield* seedUpdatingUpstream();
2370 yield* seedHostWithFullPayload();
2371
2372 // Same props as seeded — A no-ops, so it resolves to its full
2373 // persisted attrs and the materialized binding payload matches the
2374 // persisted row exactly.
2375 const plan = yield* hostProgram("old-value").pipe(makePlan);
2376
2377 expect(plan.resources.A!.action).toBe("noop");
2378 expect(plan.resources.Host!.action).toBe("noop");
2379 const rows = (plan.resources.Host as any).bindings;
2380 expect(rows[0].action).toBe("noop");
2381 // Nothing left to re-evaluate — the payload is the plain full attrs.
2382 expect(Output.isExpr(rows[0].data.env.A)).toBe(false);
2383 expect(rows[0].data.env.A.string).toBe("old-value");
2384 }),
2385 );
2386 },
2387 );
2388
2389 describe("diff.stables overrides provider.stables", { tags: ["unit", "local"] }, () => {
2390 // `A` is an OverrideStablesResource: provider `stables` is
2391 // ["providerStable", "sharedStable"], but its `diff` returns
2392 // ["diffStable", "sharedStable"] on a `string` change. The two lists
2393 // disagree, so this exercises the override (not merge) semantics.
2394 const seedUpstreamAndDownstream = (downstreamOldString: string) =>
2395 seed({
2396 A: {
2397 instanceId,
2398 providerVersion: 0,
2399 logicalId: "A",
2400 fqn: "A",
2401 namespace: undefined,
2402 resourceType: "Test.OverrideStablesResource",
2403 status: "created",
2404 props: { string: "old" },
2405 attr: {
2406 string: "old",
2407 providerStable: "provider-A",
2408 diffStable: "diff-A",
2409 sharedStable: "shared-A",
2410 },
2411 downstream: [],
2412 bindings: [],
2413 },
2414 B: {
2415 instanceId,
2416 providerVersion: 0,
2417 logicalId: "B",
2418 fqn: "B",
2419 namespace: undefined,
2420 resourceType: "Test.TestResource",
2421 status: "created",
2422 props: { string: downstreamOldString },
2423 attr: { string: downstreamOldString, stableString: "B", stableArray: ["B"] },
2424 downstream: [],
2425 bindings: [],
2426 },
2427 });
2428
2429 const subtest = (
2430 description: string,
2431 accessor: (A: OverrideStablesResource) => any,
2432 downstreamOldString: string,
2433 expectedBAction: "update" | "noop",
2434 ) =>
2435 test(
2436 description,
2437 Effect.gen(function* () {
2438 yield* seedUpstreamAndDownstream(downstreamOldString);
2439 const plan = yield* Effect.gen(function* () {
2440 const A = yield* OverrideStablesResource("A", { string: "new" });
2441 yield* TestResource("B", { string: accessor(A) });
2442 }).pipe(makePlan);
2443
2444 // A always updates: its `string` prop changed.
2445 expect(plan.resources.A!.action).toBe("update");
2446 expect(plan.resources.B!.action).toBe(expectedBAction);
2447 }),
2448 );
2449
2450 // `providerStable` is in `provider.stables` but OMITTED from the
2451 // `diff.stables` returned for this update. Because `diff.stables` now
2452 // overrides `provider.stables`, it is treated as changed and the
2453 // downstream re-plans (update). Under the old merge it would wrongly
2454 // stay stable and the downstream would no-op.
2455 subtest(
2456 "provider-only stable omitted by diff is treated as changed downstream",
2457 (A) => A.providerStable,
2458 "provider-A",
2459 "update",
2460 );
2461
2462 // `diffStable` is only in `diff.stables` -> stays stable -> downstream no-op.
2463 subtest("diff-only stable keeps downstream stable", (A) => A.diffStable, "diff-A", "noop");
2464
2465 // `sharedStable` is in both lists -> stays stable -> downstream no-op.
2466 subtest("shared stable keeps downstream stable", (A) => A.sharedStable, "shared-A", "noop");
2467
2468 // #1832: `--force` upgrades A's noop to an update. The stables carried on
2469 // A's noop diff must survive that upgrade — otherwise only
2470 // `provider.stables` reach downstream diffs and identity-sensitive
2471 // consumers (e.g. a PlanetScale role reading `database.name`) falsely
2472 // plan a replacement on every forced deploy.
2473 test(
2474 "--force keeps the stables a noop diff returns",
2475 Effect.gen(function* () {
2476 yield* seed({
2477 A: {
2478 instanceId,
2479 providerVersion: 0,
2480 logicalId: "A",
2481 fqn: "A",
2482 namespace: undefined,
2483 resourceType: "Test.OverrideStablesResource",
2484 status: "created",
2485 props: { string: "old" },
2486 attr: {
2487 string: "old",
2488 providerStable: "provider-A",
2489 diffStable: "diff-A",
2490 sharedStable: "shared-A",
2491 },
2492 downstream: [],
2493 bindings: [],
2494 },
2495 B: {
2496 instanceId,
2497 providerVersion: 0,
2498 logicalId: "B",
2499 fqn: "B",
2500 namespace: undefined,
2501 resourceType: "Test.TestResource",
2502 status: "created",
2503 props: { string: "diff-A", stringArray: ["provider-A"] },
2504 attr: { string: "diff-A", stableString: "B", stableArray: ["B"] },
2505 downstream: [],
2506 bindings: [],
2507 },
2508 });
2509 const plan = yield* Effect.gen(function* () {
2510 const A = yield* OverrideStablesResource("A", { string: "old" });
2511 yield* TestResource("B", {
2512 string: A.diffStable,
2513 stringArray: [A.providerStable],
2514 });
2515 }).pipe((program) => makePlan(program, { force: true }));
2516
2517 expect(plan.resources.A!.action).toBe("update");
2518 expect(plan.resources.B!.action).toBe("update");
2519 const bProps = (plan.resources.B as any).props;
2520 // The noop diff's `diffStable` resolves to the persisted value...
2521 expect(bProps.string).toBe("diff-A");
2522 // ...while `providerStable` (omitted by the diff's stables) is left
2523 // for apply to re-evaluate against the forced reconcile's output.
2524 expect(Output.isExpr(bProps.stringArray[0])).toBe(true);
2525 }),
2526 );
2527 });
2528
2529 describe("unsatisfied cycle detection", { tags: ["unit", "local"] }, () => {
2530 const extractCycleDefect = <A, E>(
2531 exit: Exit.Exit<A, E>,
2532 ): UnsatisfiedResourceCycle | undefined => {
2533 if (!Exit.isFailure(exit)) return undefined;
2534 const die = exit.cause.reasons.find(Cause.isDieReason);
2535 return die?.defect as UnsatisfiedResourceCycle | undefined;
2536 };
2537
2538 test(
2539 "binding cycle between resources without precreate dies",
2540 Effect.gen(function* () {
2541 const exit = yield* makePlan(
2542 Effect.gen(function* () {
2543 const A = yield* NoPrecreateBindingTarget("A", { string: "a-value" });
2544 const B = yield* NoPrecreateBindingTarget("B", { string: "b-value" });
2545
2546 yield* A.bind("FromB", { env: { PEER: B.string } });
2547 yield* B.bind("FromA", { env: { PEER: A.string } });
2548
2549 return { A, B };
2550 }),
2551 ).pipe(Effect.exit);
2552
2553 const err = extractCycleDefect(exit);
2554 expect(err).toBeDefined();
2555 expect(err!._tag).toBe("UnsatisfiedResourceCycle");
2556 expect(err!.cycle.sort()).toEqual(["A", "B"]);
2557 expect(err!.missingPrecreate.sort()).toEqual(["A", "B"]);
2558 }),
2559 );
2560
2561 test(
2562 "binding cycle with all precreate resources succeeds",
2563 Effect.gen(function* () {
2564 const exit = yield* makePlan(
2565 Effect.gen(function* () {
2566 const A = yield* BindingTarget("A", { string: "a-value" });
2567 const B = yield* BindingTarget("B", { string: "b-value" });
2568
2569 yield* A.bind("FromB", { env: { PEER: B.string } });
2570 yield* B.bind("FromA", { env: { PEER: A.string } });
2571
2572 return { A, B };
2573 }),
2574 ).pipe(Effect.exit);
2575
2576 expect(Exit.isSuccess(exit)).toBe(true);
2577 }),
2578 );
2579
2580 test(
2581 "mixed cycle succeeds when precreate resource breaks it",
2582 Effect.gen(function* () {
2583 const exit = yield* makePlan(
2584 Effect.gen(function* () {
2585 const A = yield* BindingTarget("A", { string: "a-value" });
2586 const B = yield* NoPrecreateBindingTarget("B", { string: A.string });
2587
2588 yield* A.bind("FromB", { env: { PEER: B.string } });
2589
2590 return { A, B };
2591 }),
2592 ).pipe(Effect.exit);
2593
2594 expect(Exit.isSuccess(exit)).toBe(true);
2595 }),
2596 );
2597
2598 test(
2599 "three-node binding cycle dies when none have precreate",
2600 Effect.gen(function* () {
2601 const exit = yield* makePlan(
2602 Effect.gen(function* () {
2603 const A = yield* NoPrecreateBindingTarget("A", { string: "a" });
2604 const B = yield* NoPrecreateBindingTarget("B", { string: "b" });
2605 const C = yield* NoPrecreateBindingTarget("C", { string: "c" });
2606
2607 yield* A.bind("FromC", { env: { PEER: C.string } });
2608 yield* B.bind("FromA", { env: { PEER: A.string } });
2609 yield* C.bind("FromB", { env: { PEER: B.string } });
2610
2611 return { A, B, C };
2612 }),
2613 ).pipe(Effect.exit);
2614
2615 const err = extractCycleDefect(exit);
2616 expect(err).toBeDefined();
2617 expect(err!._tag).toBe("UnsatisfiedResourceCycle");
2618 expect(err!.cycle.sort()).toEqual(["A", "B", "C"]);
2619 expect(err!.missingPrecreate.sort()).toEqual(["A", "B", "C"]);
2620 }),
2621 );
2622
2623 test(
2624 "acyclic binding graph succeeds even without precreate",
2625 Effect.gen(function* () {
2626 const exit = yield* makePlan(
2627 Effect.gen(function* () {
2628 const A = yield* NoPrecreateBindingTarget("A", { string: "a-value" });
2629 const B = yield* NoPrecreateBindingTarget("B", { string: A.string });
2630
2631 yield* B.bind("FromA", { env: { PEER: A.string } });
2632
2633 return { A, B };
2634 }),
2635 ).pipe(Effect.exit);
2636
2637 expect(Exit.isSuccess(exit)).toBe(true);
2638 }),
2639 );
2640 });
2641
2642 describe(
2643 "unresolved plan inputs in diff should conservatively update",
2644 { tags: ["unit", "local"] },
2645 () => {
2646 test(
2647 "update when upstream resource is new and downstream news contains exprs",
2648 Effect.gen(function* () {
2649 yield* seed({
2650 B: {
2651 instanceId,
2652 providerVersion: 0,
2653 logicalId: "B",
2654 fqn: "B",
2655 namespace: undefined,
2656 resourceType: "Test.TestResource",
2657 status: "created",
2658 props: { string: "old-value" },
2659 attr: { string: "old-value", stableString: "B", stableArray: ["B"] },
2660 downstream: [],
2661 bindings: [],
2662 },
2663 });
2664 const plan = yield* Effect.gen(function* () {
2665 const A = yield* TestResource("A", { string: "hello" });
2666 yield* TestResource("B", { string: A.string });
2667 }).pipe(makePlan);
2668
2669 expect(plan.resources.A.action).toBe("create");
2670 expect(plan.resources.B.action).toBe("update");
2671 }),
2672 );
2673 },
2674 );
2675
2676 describe("Config props are resolved through plan", { tags: ["unit", "local"] }, () => {
2677 test(
2678 "a Config prop is resolved to its concrete value in the plan",
2679 Effect.gen(function* () {
2680 const plan = yield* Effect.gen(function* () {
2681 yield* TestResource("A", { string: Config.succeed("resolved-config-value") as any });
2682 }).pipe(makePlan);
2683
2684 const node: any = plan.resources.A!;
2685 expect(node.action).toBe("create");
2686 const props = node.props as TestResourceProps;
2687 expect(Config.isConfig(props.string)).toBe(false);
2688 expect(props.string).toBe("resolved-config-value");
2689 }),
2690 );
2691
2692 test(
2693 "a Config resolving to a Redacted keeps it wrapped in the plan",
2694 Effect.gen(function* () {
2695 const plan = yield* Effect.gen(function* () {
2696 yield* TestResource("A", {
2697 string: "x",
2698 redacted: Config.succeed(Redacted.make("hunter2")) as any,
2699 });
2700 }).pipe(makePlan);
2701
2702 const node: any = plan.resources.A!;
2703 expect(node.action).toBe("create");
2704 const props = node.props as TestResourceProps;
2705 expect(Redacted.isRedacted(props.redacted)).toBe(true);
2706 expect(Redacted.value(props.redacted!)).toBe("hunter2");
2707 }),
2708 );
2709
2710 test(
2711 "a Config nested inside an object prop is resolved in the plan",
2712 Effect.gen(function* () {
2713 const plan = yield* Effect.gen(function* () {
2714 yield* TestResource("A", { object: { string: Config.succeed("nested") as any } });
2715 }).pipe(makePlan);
2716
2717 const node: any = plan.resources.A!;
2718 expect(node.action).toBe("create");
2719 const props = node.props as TestResourceProps;
2720 expect(props.object).toEqual({ string: "nested" });
2721 }),
2722 );
2723 });
2724
2725 describe("Redacted props/outputs are preserved through plan", { tags: ["unit", "local"] }, () => {
2726 test(
2727 "Redacted prop on a new resource is preserved as a Redacted in the plan",
2728 Effect.gen(function* () {
2729 const plan = yield* Effect.gen(function* () {
2730 yield* TestResource("A", { string: "x", redacted: Redacted.make("hunter2") });
2731 }).pipe(makePlan);
2732
2733 const node: any = plan.resources.A!;
2734 expect(node.action).toBe("create");
2735 const props = node.props as TestResourceProps;
2736 expect(Redacted.isRedacted(props.redacted)).toBe(true);
2737 expect(Redacted.value(props.redacted!)).toBe("hunter2");
2738 }),
2739 );
2740
2741 test(
2742 "Redacted prop nested inside an array is preserved through the plan",
2743 Effect.gen(function* () {
2744 const plan = yield* Effect.gen(function* () {
2745 yield* TestResource("A", {
2746 string: "x",
2747 redactedArray: [Redacted.make("a"), Redacted.make("b")],
2748 });
2749 }).pipe(makePlan);
2750
2751 const node: any = plan.resources.A!;
2752 expect(node.action).toBe("create");
2753 const props = node.props as TestResourceProps;
2754 expect(props.redactedArray).toBeDefined();
2755 expect(props.redactedArray!.length).toBe(2);
2756 expect(Redacted.isRedacted(props.redactedArray![0]!)).toBe(true);
2757 expect(Redacted.isRedacted(props.redactedArray![1]!)).toBe(true);
2758 expect(Redacted.value(props.redactedArray![0]!)).toBe("a");
2759 expect(Redacted.value(props.redactedArray![1]!)).toBe("b");
2760 }),
2761 );
2762
2763 test(
2764 "no-op when prior state has the same Redacted value",
2765 Effect.gen(function* () {
2766 yield* seed({
2767 A: {
2768 instanceId,
2769 providerVersion: 0,
2770 logicalId: "A",
2771 fqn: "A",
2772 namespace: undefined,
2773 resourceType: "Test.TestResource",
2774 status: "created",
2775 props: { string: "x", redacted: Redacted.make("hunter2") },
2776 attr: {
2777 string: "x",
2778 stringArray: [],
2779 stableString: "A",
2780 stableArray: ["A"],
2781 replaceString: undefined,
2782 redacted: Redacted.make("hunter2"),
2783 redactedArray: undefined,
2784 },
2785 downstream: [],
2786 bindings: [],
2787 },
2788 });
2789 const plan = yield* Effect.gen(function* () {
2790 yield* TestResource("A", { string: "x", redacted: Redacted.make("hunter2") });
2791 }).pipe(makePlan);
2792
2793 expect(plan.resources.A!.action).toBe("noop");
2794 }),
2795 );
2796
2797 test(
2798 "update when Redacted prop value changes",
2799 Effect.gen(function* () {
2800 yield* seed({
2801 A: {
2802 instanceId,
2803 providerVersion: 0,
2804 logicalId: "A",
2805 fqn: "A",
2806 namespace: undefined,
2807 resourceType: "Test.TestResource",
2808 status: "created",
2809 props: { string: "x", redacted: Redacted.make("old") },
2810 attr: {
2811 string: "x",
2812 stringArray: [],
2813 stableString: "A",
2814 stableArray: ["A"],
2815 replaceString: undefined,
2816 redacted: Redacted.make("old"),
2817 redactedArray: undefined,
2818 },
2819 downstream: [],
2820 bindings: [],
2821 },
2822 });
2823 const plan = yield* Effect.gen(function* () {
2824 yield* TestResource("A", { string: "x", redacted: Redacted.make("new") });
2825 }).pipe(makePlan);
2826
2827 expect(plan.resources.A!.action).toBe("update");
2828 const node: any = plan.resources.A!;
2829 const props = node.props as TestResourceProps;
2830 expect(Redacted.isRedacted(props.redacted)).toBe(true);
2831 expect(Redacted.value(props.redacted!)).toBe("new");
2832 }),
2833 );
2834
2835 test(
2836 "Redacted output flowing into a downstream resource preserves its redaction",
2837 Effect.gen(function* () {
2838 yield* seed({
2839 A: {
2840 instanceId,
2841 providerVersion: 0,
2842 logicalId: "A",
2843 fqn: "A",
2844 namespace: undefined,
2845 resourceType: "Test.TestResource",
2846 status: "created",
2847 props: { string: "x", redacted: Redacted.make("hunter2") },
2848 attr: {
2849 string: "x",
2850 stringArray: [],
2851 stableString: "A",
2852 stableArray: ["A"],
2853 replaceString: undefined,
2854 redacted: Redacted.make("hunter2"),
2855 redactedArray: undefined,
2856 },
2857 downstream: [],
2858 bindings: [],
2859 },
2860 });
2861 const plan = yield* Effect.gen(function* () {
2862 const A = yield* TestResource("A", { string: "x", redacted: Redacted.make("hunter2") });
2863 yield* TestResource("B", { string: "y", redacted: A.redacted as any });
2864 }).pipe(makePlan);
2865
2866 const bNode: any = plan.resources.B!;
2867 const bProps = bNode.props as TestResourceProps;
2868 expect(Redacted.isRedacted(bProps.redacted)).toBe(true);
2869 expect(Redacted.value(bProps.redacted!)).toBe("hunter2");
2870 }),
2871 );
2872 });
2873
2874 describe("engine-level adoption", { tags: ["unit", "local"] }, () => {
2875 // Build a plan, optionally with an explicit AdoptPolicy and a read hook
2876 // that simulates a pre-existing cloud resource.
2877 const ownedAttrs: TestResource["Attributes"] = {
2878 string: "hello",
2879 stringArray: [],
2880 stableString: "Adopted",
2881 stableArray: ["Adopted"],
2882 replaceString: undefined,
2883 redacted: undefined,
2884 redactedArray: undefined,
2885 };
2886
2887 const makeAdoptPlan = <A>(
2888 effect: Effect.Effect<A, any, any>,
2889 opts: {
2890 adopt?: boolean;
2891 readHook?: (id: string) => Effect.Effect<TestResource["Attributes"] | undefined, any>;
2892 },
2893 ): Effect.Effect<Plan.Plan<A>, any, State> =>
2894 Effect.gen(function* () {
2895 const { name, stage } = yield* resolveStackId;
2896 const hooksLayer = opts.readHook
2897 ? Layer.succeed(TestResourceHooks, { read: opts.readHook })
2898 : Layer.empty;
2899 const adoptLayer =
2900 opts.adopt === undefined ? Layer.empty : Layer.succeed(AdoptPolicy, opts.adopt);
2901 return yield* (effect as Effect.Effect<A, any, any>).pipe(
2902 Stack.make({ name, providers: Layer.empty, state: inMemoryState() } as any) as any,
2903 Effect.provideService(Stage, stage),
2904 Effect.flatMap((stackSpec: any) => Plan.make(stackSpec)),
2905 Effect.provide(TestLayers()),
2906 Effect.provide(hooksLayer),
2907 Effect.provide(adoptLayer),
2908 ) as Effect.Effect<Plan.Plan<A>, any, State>;
2909 }) as Effect.Effect<Plan.Plan<A>, any, State>;
2910
2911 const creatingWithoutAttrs = {
2912 instanceId,
2913 providerVersion: 0,
2914 logicalId: "Recovering",
2915 fqn: "Recovering",
2916 namespace: undefined,
2917 resourceType: "Test.TestResource",
2918 status: "creating" as const,
2919 props: { string: "hello" },
2920 attr: undefined,
2921 downstream: [],
2922 bindings: [],
2923 } satisfies ResourceState;
2924
2925 test.provider("cold adoption reconciles with olds undefined", (scratch) =>
2926 Effect.gen(function* () {
2927 let creates = 0;
2928 let updates = 0;
2929 const hooks = {
2930 read: () => Effect.succeed(ownedAttrs),
2931 create: () =>
2932 Effect.sync(() => {
2933 creates++;
2934 }),
2935 update: () =>
2936 Effect.sync(() => {
2937 updates++;
2938 }),
2939 };
2940
2941 yield* scratch
2942 .deploy(
2943 Effect.gen(function* () {
2944 yield* TestResource("Adopted", { string: "hello" });
2945 }),
2946 )
2947 .pipe(Effect.provideService(TestResourceHooks, hooks));
2948
2949 expect(creates).toBe(1);
2950 expect(updates).toBe(0);
2951
2952 const state = yield* yield* State;
2953 expect(
2954 yield* state.get({ stack: scratch.name, stage: scratch.stage, fqn: "Adopted" }),
2955 ).toMatchObject({ status: "updated", props: { string: "hello" } });
2956 }),
2957 );
2958
2959 test.provider("cold adoption keeps olds undefined after a failed first reconcile", (scratch) =>
2960 Effect.gen(function* () {
2961 let creates = 0;
2962 let updates = 0;
2963 const hooks = {
2964 read: () => Effect.succeed(ownedAttrs),
2965 create: () =>
2966 Effect.suspend(() => {
2967 creates++;
2968 return creates === 1
2969 ? Effect.fail(new Error("first adoption reconcile failed"))
2970 : Effect.void;
2971 }),
2972 update: () =>
2973 Effect.sync(() => {
2974 updates++;
2975 }),
2976 };
2977 const program = () =>
2978 Effect.gen(function* () {
2979 yield* TestResource("Adopted", { string: "hello" });
2980 });
2981
2982 const first = yield* scratch
2983 .deploy(program())
2984 .pipe(Effect.provideService(TestResourceHooks, hooks), Effect.exit);
2985 expect(Exit.isFailure(first)).toBe(true);
2986 expect(creates).toBe(1);
2987 expect(updates).toBe(0);
2988
2989 const state = yield* yield* State;
2990 expect(
2991 yield* state.get({ stack: scratch.name, stage: scratch.stage, fqn: "Adopted" }),
2992 ).toMatchObject({ status: "updating", adopting: true });
2993
2994 yield* scratch.deploy(program()).pipe(Effect.provideService(TestResourceHooks, hooks));
2995
2996 expect(creates).toBe(2);
2997 expect(updates).toBe(0);
2998 const completed = yield* state.get({
2999 stack: scratch.name,
3000 stage: scratch.stage,
3001 fqn: "Adopted",
3002 });
3003 expect(completed).toMatchObject({ status: "updated" });
3004 expect((completed as any)?.adopting).toBeUndefined();
3005 }),
3006 );
3007
3008 test(
3009 "recovered Unowned attrs require explicit adoption",
3010 Effect.gen(function* () {
3011 yield* seed({ Recovering: creatingWithoutAttrs });
3012
3013 const exit = yield* makeAdoptPlan(
3014 Effect.gen(function* () {
3015 yield* TestResource("Recovering", { string: "hello" });
3016 }),
3017 { adopt: false, readHook: () => Effect.succeed(Unowned(ownedAttrs)) },
3018 ).pipe(Effect.exit);
3019
3020 expect(Exit.isFailure(exit)).toBe(true);
3021 if (Exit.isFailure(exit)) {
3022 const reason = exit.cause.reasons.find(Cause.isFailReason);
3023 expect((reason?.error as any)?._tag).toBe("OwnedBySomeoneElse");
3024 expect((reason?.error as any)?.resourceType).toBe("Test.TestResource");
3025 }
3026 }),
3027 );
3028
3029 test(
3030 "explicit adoption strips Unowned from recovered attrs",
3031 Effect.gen(function* () {
3032 yield* seed({ Recovering: creatingWithoutAttrs });
3033
3034 const plan = yield* makeAdoptPlan(
3035 Effect.gen(function* () {
3036 yield* TestResource("Recovering", { string: "hello" });
3037 }),
3038 { adopt: true, readHook: () => Effect.succeed(Unowned(ownedAttrs)) },
3039 );
3040
3041 const recovered = plan.resources.Recovering!;
3042 expect(recovered.action).toBe("create");
3043 expect(Unowned.is((recovered.state as any).attr)).toBe(false);
3044 expect(Object.getOwnPropertySymbols((recovered.state as any).attr)).toEqual([]);
3045 }),
3046 );
3047
3048 test(
3049 "recovered attrs still diff immutable desired changes",
3050 Effect.gen(function* () {
3051 yield* seed({ Recovering: { ...creatingWithoutAttrs, props: { replaceString: "old" } } });
3052
3053 const plan = yield* makeAdoptPlan(
3054 Effect.gen(function* () {
3055 yield* TestResource("Recovering", { replaceString: "new" });
3056 }),
3057 { readHook: () => Effect.succeed({ ...ownedAttrs, replaceString: "old" }) },
3058 );
3059
3060 expect(plan.resources.Recovering).toMatchObject({
3061 action: "replace",
3062 props: { replaceString: "new" },
3063 state: { status: "creating", attr: { replaceString: "old" } },
3064 });
3065 }),
3066 );
3067
3068 test(
3069 "owned read result is silently adopted (no AdoptPolicy needed) and forced to update",
3070 Effect.gen(function* () {
3071 const plan = yield* makeAdoptPlan(
3072 Effect.gen(function* () {
3073 yield* TestResource("Adopted", { string: "hello" });
3074 }),
3075 { readHook: () => Effect.succeed(ownedAttrs) },
3076 );
3077
3078 // Cold-start adoption is surfaced explicitly while the provider re-syncs
3079 // tags / config against `news` — even when read returns plain
3080 // (owned) attrs, the cloud resource may carry drift the engine
3081 // can't detect from `props` alone.
3082 expect(plan.resources.Adopted!.action).toBe("adopted");
3083 expect(plan.resources.Adopted).toMatchObject({
3084 adopting: true,
3085 state: { status: "created", attr: { string: "hello" } },
3086 });
3087
3088 // Planning no longer persists the adopted state (issue #793): it rides
3089 // on the plan node and is only committed to the store at apply time.
3090 const node = plan.resources.Adopted!;
3091 expect(node.state?.status).toBe("created");
3092 expect((node.state as any)?.attr).toMatchObject({ string: "hello" });
3093
3094 const state = yield* yield* State;
3095 expect(
3096 yield* state.get({ stack: TEST_STACK, stage: TEST_STAGE, fqn: "Adopted" }),
3097 ).toBeUndefined();
3098 }),
3099 );
3100
3101 test(
3102 "Unowned read result + adopt enabled -> takeover forces an update",
3103 Effect.gen(function* () {
3104 const plan = yield* makeAdoptPlan(
3105 Effect.gen(function* () {
3106 yield* TestResource("Adopted", { string: "hello" });
3107 }),
3108 { adopt: true, readHook: () => Effect.succeed(Unowned(ownedAttrs)) },
3109 );
3110
3111 // Takeover of an Unowned resource is planned as `adopted` so the provider's
3112 // update path can rewrite ownership tags / config to match this
3113 // logical id (a plain noop would leave the resource looking
3114 // foreign-owned to subsequent deploys).
3115 expect(plan.resources.Adopted!.action).toBe("adopted");
3116 expect(plan.resources.Adopted).toMatchObject({
3117 adopting: true,
3118 state: { status: "created" },
3119 });
3120
3121 // The adopted state rides on the plan node, not the store (issue #793).
3122 const node = plan.resources.Adopted!;
3123 expect(node.state?.status).toBe("created");
3124
3125 // The Unowned brand must be fully scrubbed from anything that
3126 // reaches the plan node (and, at apply, the state store) — both via
3127 // the public `Unowned.is` check *and* via direct symbol inspection
3128 // (in case someone accidentally uses `Symbol.for` rather than
3129 // `Unowned.is`).
3130 const adoptedAttr = (node.state as any)?.attr as object;
3131 expect(Unowned.is(adoptedAttr)).toBe(false);
3132 expect(Object.getOwnPropertySymbols(adoptedAttr).length).toBe(0);
3133 expect(JSON.stringify(adoptedAttr)).not.toContain("Unowned");
3134
3135 // Planning wrote nothing to the store.
3136 const state = yield* yield* State;
3137 expect(
3138 yield* state.get({ stack: TEST_STACK, stage: TEST_STAGE, fqn: "Adopted" }),
3139 ).toBeUndefined();
3140 }),
3141 );
3142
3143 test(
3144 "Unowned read result + adopt disabled -> OwnedBySomeoneElse",
3145 Effect.gen(function* () {
3146 const exit = yield* makeAdoptPlan(
3147 Effect.gen(function* () {
3148 yield* TestResource("Foreign", { string: "hello" });
3149 }),
3150 { adopt: false, readHook: () => Effect.succeed(Unowned(ownedAttrs)) },
3151 ).pipe(Effect.exit);
3152
3153 expect(Exit.isFailure(exit)).toBe(true);
3154 if (Exit.isFailure(exit)) {
3155 const reason = exit.cause.reasons.find(Cause.isFailReason);
3156 expect((reason?.error as any)?._tag).toBe("OwnedBySomeoneElse");
3157 expect((reason?.error as any)?.resourceType).toBe("Test.TestResource");
3158 }
3159 }),
3160 );
3161
3162 test(
3163 "read returns undefined -> ordinary create",
3164 Effect.gen(function* () {
3165 const plan = yield* makeAdoptPlan(
3166 Effect.gen(function* () {
3167 yield* TestResource("Fresh", { string: "hello" });
3168 }),
3169 { readHook: () => Effect.succeed(undefined) },
3170 );
3171
3172 expect(plan.resources.Fresh!.action).toBe("create");
3173 expect(plan.resources.Fresh!.state).toBeUndefined();
3174 }),
3175 );
3176
3177 test(
3178 "Unowned read result + resource-scoped adopt(true) -> takeover even when the stack default is disabled",
3179 Effect.gen(function* () {
3180 const plan = yield* makeAdoptPlan(
3181 Effect.gen(function* () {
3182 yield* TestResource("Adopted", { string: "hello" }).pipe(adopt(true));
3183 }),
3184 {
3185 // Stack/CLI default is OFF — only the per-resource scope opts in.
3186 adopt: false,
3187 readHook: () => Effect.succeed(Unowned(ownedAttrs)),
3188 },
3189 );
3190
3191 expect(plan.resources.Adopted!.action).toBe("adopted");
3192 expect(plan.resources.Adopted).toMatchObject({
3193 adopting: true,
3194 state: { status: "created" },
3195 });
3196
3197 // Adopted state rides on the plan node; planning persists nothing
3198 // (issue #793).
3199 const node = plan.resources.Adopted!;
3200 expect(node.state?.status).toBe("created");
3201
3202 const state = yield* yield* State;
3203 expect(
3204 yield* state.get({ stack: TEST_STACK, stage: TEST_STAGE, fqn: "Adopted" }),
3205 ).toBeUndefined();
3206 }),
3207 );
3208
3209 test(
3210 "Unowned read result + resource-scoped adopt(false) -> OwnedBySomeoneElse even when the stack default is enabled",
3211 Effect.gen(function* () {
3212 const exit = yield* makeAdoptPlan(
3213 Effect.gen(function* () {
3214 yield* TestResource("Foreign", { string: "hello" }).pipe(adopt(false));
3215 }),
3216 {
3217 // Stack/CLI default is ON, but the resource opts out.
3218 adopt: true,
3219 readHook: () => Effect.succeed(Unowned(ownedAttrs)),
3220 },
3221 ).pipe(Effect.exit);
3222
3223 expect(Exit.isFailure(exit)).toBe(true);
3224 if (Exit.isFailure(exit)) {
3225 const reason = exit.cause.reasons.find(Cause.isFailReason);
3226 expect((reason?.error as any)?._tag).toBe("OwnedBySomeoneElse");
3227 expect((reason?.error as any)?.resourceType).toBe("Test.TestResource");
3228 }
3229 }),
3230 );
3231
3232 test(
3233 "providers without a `read` method skip the adoption probe entirely",
3234 Effect.gen(function* () {
3235 // Bucket has no `read` implementation. The engine should fall back
3236 // to a normal `create` action without any side effects.
3237 const plan = yield* makeAdoptPlan(
3238 Effect.gen(function* () {
3239 yield* Bucket("FreshBucket", { name: "fresh" });
3240 }),
3241 { adopt: true },
3242 );
3243
3244 expect(plan.resources.FreshBucket!.action).toBe("create");
3245 }),
3246 );
3247
3248 // A replacement targets a new physical identity. Plan never probes it (its
3249 // props may still resolve during apply); it hands apply the effective
3250 // adoption policy as `deferredAdoption` so the probe runs before mutation.
3251 const replaceable = (fqn: string, overrides?: Partial<ResourceState>): ResourceState =>
3252 ({
3253 instanceId,
3254 providerVersion: 0,
3255 logicalId: fqn,
3256 fqn,
3257 namespace: undefined,
3258 resourceType: "Test.TestResource",
3259 status: "created",
3260 props: { replaceString: "old" },
3261 attr: { ...ownedAttrs, replaceString: "old" },
3262 downstream: [],
3263 bindings: [],
3264 ...overrides,
3265 }) as ResourceState;
3266
3267 const trackedReads = () => {
3268 const reads: string[] = [];
3269 const readHook = (id: string) =>
3270 Effect.sync(() => {
3271 reads.push(id);
3272 return undefined;
3273 });
3274 return { reads, readHook };
3275 };
3276
3277 const policies = [
3278 { global: undefined, scoped: undefined, adopt: false },
3279 { global: true, scoped: undefined, adopt: true },
3280 { global: false, scoped: true, adopt: true },
3281 { global: true, scoped: false, adopt: false },
3282 ] as const;
3283 for (const { global, scoped, adopt: expected } of policies) {
3284 test(
3285 `a replacement defers admission to apply (global=${global}, scoped=${scoped})`,
3286 Effect.gen(function* () {
3287 yield* seed({ R: replaceable("R") });
3288 const { reads, readHook } = trackedReads();
3289 const plan = yield* makeAdoptPlan(
3290 Effect.gen(function* () {
3291 const r = TestResource("R", { replaceString: "new" });
3292 yield* scoped === undefined ? r : r.pipe(adopt(scoped));
3293 }),
3294 { adopt: global, readHook },
3295 );
3296 expect(reads).toEqual([]);
3297 expect(plan.resources.R).toMatchObject({
3298 action: "replace",
3299 deferredAdoption: { adopt: expected },
3300 });
3301 }),
3302 );
3303 }
3304
3305 test(
3306 "updates and noops never defer admission",
3307 Effect.gen(function* () {
3308 yield* seed({
3309 Updated: replaceable("Updated", { props: { string: "a" } }),
3310 Unchanged: replaceable("Unchanged", { props: { string: "a" } }),
3311 });
3312 const plan = yield* makeAdoptPlan(
3313 Effect.gen(function* () {
3314 yield* TestResource("Updated", { string: "b" });
3315 yield* TestResource("Unchanged", { string: "a" });
3316 }),
3317 {},
3318 );
3319 expect(plan.resources.Updated!.action).toBe("update");
3320 expect(plan.resources.Unchanged!.action).toBe("noop");
3321 expect((plan.resources.Updated as any).deferredAdoption).toBeUndefined();
3322 expect((plan.resources.Unchanged as any).deferredAdoption).toBeUndefined();
3323 }),
3324 );
3325
3326 test(
3327 "a replacement of a provider without `read` has nothing to admit",
3328 Effect.gen(function* () {
3329 yield* seed({
3330 R: replaceable("R", {
3331 resourceType: "Test.StaticStablesResource",
3332 attr: { string: "s", tags: {}, stableId: "id", stableArn: "arn", replaceString: "old" },
3333 }),
3334 });
3335 const plan = yield* makeAdoptPlan(
3336 Effect.gen(function* () {
3337 yield* StaticStablesResource("R", { replaceString: "new" });
3338 }),
3339 {},
3340 );
3341 expect(plan.resources.R!.action).toBe("replace");
3342 expect((plan.resources.R as any).deferredAdoption).toBeUndefined();
3343 }),
3344 );
3345
3346 test(
3347 "a replacement of a reused FQN never probes its predecessor's identity",
3348 Effect.gen(function* () {
3349 yield* seed({ R: replaceable("R", { adoptionBlocked: "migrated-fqn" }) });
3350 const plan = yield* makeAdoptPlan(
3351 Effect.gen(function* () {
3352 yield* TestResource("R", { replaceString: "new" });
3353 }),
3354 { adopt: true },
3355 );
3356 expect(plan.resources.R).toMatchObject({
3357 action: "replace",
3358 adoptionBlocked: "migrated-fqn",
3359 });
3360 expect((plan.resources.R as any).deferredAdoption).toBeUndefined();
3361 }),
3362 );
3363 });
3364
3365 // A delete-first replacement in a cycle deletes its previous generation before
3366 // precreate. While its identity is unresolved, ownership cannot be checked
3367 // first, so plan refuses it unless adoption is allowed.
3368 describe("cyclic delete-first admission", { tags: ["unit", "local"] }, () => {
3369 interface Cyclic extends Resource<
3370 "Test.CyclicDeleteFirst",
3371 { name: string },
3372 { name: string },
3373 { self: string }
3374 > {}
3375 const Cyclic = Resource<Cyclic>("Test.CyclicDeleteFirst");
3376 /** `Cyclic` without `read`: it has no ownership to check. */
3377 interface Unread extends Resource<
3378 "Test.CyclicDeleteFirstUnread",
3379 { name: string },
3380 { name: string },
3381 { self: string }
3382 > {}
3383 const Unread = Resource<Unread>("Test.CyclicDeleteFirstUnread");
3384 /** `Cyclic` with `observe`: it checks ownership before precreate. */
3385 interface Observed extends Resource<
3386 "Test.CyclicDeleteFirstObserved",
3387 { name: string },
3388 { name: string },
3389 { self: string }
3390 > {}
3391 const Observed = Resource<Observed>("Test.CyclicDeleteFirstObserved");
3392 class Knobs extends Context.Service<
3393 Knobs,
3394 {
3395 /** The diff's action for a changed name. */
3396 action: "replace" | "update";
3397 deleteFirst: boolean;
3398 /** Reconcile fails after precreate, leaving a `replacing` row with attrs. */
3399 crash: boolean;
3400 reads: string[];
3401 }
3402 >()("CyclicDeleteFirstKnobs") {}
3403 const diff = Effect.fn(function* ({
3404 olds,
3405 news,
3406 }: {
3407 olds: { name: string };
3408 news: Input<{ name: string }>;
3409 }) {
3410 if (isResolved(news) && olds.name === news.name) return undefined;
3411 const knobs = yield* Knobs;
3412 return knobs.action === "update"
3413 ? ({ action: "update" } as const)
3414 : ({ action: "replace", deleteFirst: knobs.deleteFirst } as const);
3415 });
3416 const precreate = Effect.fn(function* ({ news }: { news: InputProps<{ name: string }> }) {
3417 return { name: typeof news.name === "string" ? news.name : "pending" };
3418 });
3419 const reconcile = Effect.fn(function* ({ news }: { news: { name: string } }) {
3420 if ((yield* Knobs).crash) return yield* new ResourceFailure();
3421 return { name: news.name };
3422 });
3423 const providers = Layer.mergeAll(
3424 Provider.succeed(Cyclic, {
3425 diff,
3426 read: Effect.fn(function* ({ olds }) {
3427 (yield* Knobs).reads.push(String(olds?.name));
3428 return undefined;
3429 }),
3430 precreate,
3431 reconcile,
3432 delete: () => Effect.void,
3433 }),
3434 Provider.succeed(Unread, { diff, precreate, reconcile, delete: () => Effect.void }),
3435 Provider.succeed(Observed, {
3436 diff,
3437 read: () => Effect.succeed(undefined),
3438 observe: () => Effect.succeed(undefined),
3439 precreate,
3440 reconcile,
3441 delete: () => Effect.void,
3442 }),
3443 ).pipe(
3444 Layer.provideMerge(
3445 Layer.effect(
3446 Knobs,
3447 Effect.sync(() => ({
3448 action: "replace" as const,
3449 deleteFirst: false,
3450 crash: false,
3451 reads: [] as string[],
3452 })),
3453 ),
3454 ),
3455 );
3456 const { test } = Test.make({
3457 providers: Layer.mergeAll(providers, TestLayers()),
3458 state: freshState,
3459 });
3460
3461 /**
3462 * `Subject`'s name comes from `Name`, which is updated in the same deploy.
3463 * In a cycle, `Name` is a peer bound back to `Subject`, so the name is
3464 * still unresolved when `Subject` precreates; with `outside`, or outside a
3465 * cycle, `Name` is an ordinary upstream.
3466 */
3467 const subject = (
3468 name: string,
3469 opts: {
3470 cycle?: boolean;
3471 outside?: boolean;
3472 resolved?: boolean;
3473 unread?: boolean;
3474 observed?: boolean;
3475 adopt?: boolean;
3476 } = {},
3477 ) =>
3478 Effect.gen(function* () {
3479 const cycle = opts.cycle ?? true;
3480 const peer =
3481 cycle && !opts.outside ? yield* BindingTarget("Name", { string: name }) : undefined;
3482 const source = peer ?? (yield* TestResource("Name", { string: name }));
3483 const props = { name: opts.resolved ? name : source.string };
3484 const scoped = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
3485 opts.adopt === undefined ? effect : effect.pipe(adopt(opts.adopt));
3486 const resource = opts.unread
3487 ? yield* scoped(Unread("Subject", props))
3488 : opts.observed
3489 ? yield* scoped(Observed("Subject", props))
3490 : yield* scoped(Cyclic("Subject", props));
3491 if (cycle) yield* resource.bind("Self", { self: resource.name });
3492 if (peer) yield* peer.bind("Subject", { env: { SUBJECT: resource.name } });
3493 return resource;
3494 });
3495
3496 const setup = Effect.fn(function* (
3497 stack: Test.ScratchStack,
3498 opts?: { unread?: boolean; observed?: boolean },
3499 ) {
3500 const knobs = yield* Knobs;
3501 yield* stack.destroy();
3502 Object.assign(knobs, { action: "replace", deleteFirst: false, crash: false });
3503 yield* stack.deploy(subject("old", opts));
3504 knobs.deleteFirst = true;
3505 knobs.reads.length = 0;
3506 return knobs;
3507 });
3508
3509 const refusing = [
3510 { global: undefined, scoped: undefined },
3511 { global: true, scoped: false },
3512 ] as const;
3513 for (const { global, scoped } of refusing) {
3514 test.provider(
3515 `refuses an unresolved cyclic delete-first replacement (global=${global}, scoped=${scoped})`,
3516 (stack) =>
3517 Effect.gen(function* () {
3518 const knobs = yield* setup(stack);
3519 const error = yield* stack
3520 .plan(subject("fresh", { adopt: scoped }))
3521 .pipe(
3522 global === undefined
3523 ? (effect) => effect
3524 : Effect.provideService(AdoptPolicy, global),
3525 Effect.flip,
3526 );
3527 expect(error).toMatchObject({
3528 _tag: "UnverifiableReplacement",
3529 resourceType: "Test.CyclicDeleteFirst",
3530 logicalId: "Subject",
3531 });
3532 expect(knobs.reads).toEqual([]);
3533 yield* stack.destroy();
3534 }),
3535 );
3536 }
3537
3538 const admitting = [
3539 { global: true, scoped: undefined },
3540 { global: false, scoped: true },
3541 ] as const;
3542 for (const { global, scoped } of admitting) {
3543 test.provider(
3544 `adoption lets an unresolved cyclic delete-first replacement through (global=${global}, scoped=${scoped})`,
3545 (stack) =>
3546 Effect.gen(function* () {
3547 yield* setup(stack);
3548 const plan = yield* stack
3549 .plan(subject("fresh", { adopt: scoped }))
3550 .pipe(Effect.provideService(AdoptPolicy, global));
3551 expect(plan.resources.Subject).toMatchObject({
3552 action: "replace",
3553 deleteFirst: true,
3554 deferredAdoption: { adopt: true },
3555 });
3556 yield* stack.destroy();
3557 }),
3558 );
3559 }
3560
3561 const unaffected = [
3562 {
3563 label: "a create-first replacement",
3564 prepare: (knobs: Knobs["Service"]) => (knobs.deleteFirst = false),
3565 program: subject("fresh"),
3566 deleteFirst: false,
3567 },
3568 {
3569 label: "a resolved name, admitted in apply before the delete",
3570 prepare: () => {},
3571 program: subject("fresh", { resolved: true }),
3572 deleteFirst: true,
3573 },
3574 {
3575 label: "a name from outside the cycle, admitted in apply before the delete",
3576 prepare: () => {},
3577 program: subject("fresh", { outside: true }),
3578 deleteFirst: true,
3579 },
3580 {
3581 label: "a replacement outside a cycle, which deletes after its upstreams resolve",
3582 prepare: () => {},
3583 program: subject("fresh", { cycle: false }),
3584 deleteFirst: true,
3585 },
3586 ];
3587 for (const { label, prepare, program, deleteFirst } of unaffected) {
3588 test.provider(`plans ${label}`, (stack) =>
3589 Effect.gen(function* () {
3590 prepare(yield* setup(stack));
3591 const plan = yield* stack.plan(program);
3592 expect(plan.resources.Subject).toMatchObject({ action: "replace", deleteFirst });
3593 yield* stack.destroy();
3594 }),
3595 );
3596 }
3597
3598 test.provider(
3599 "plans a provider with `observe`, which checks ownership before the delete",
3600 (stack) =>
3601 Effect.gen(function* () {
3602 yield* setup(stack, { observed: true });
3603 const plan = yield* stack.plan(subject("fresh", { observed: true }));
3604 expect(plan.resources.Subject).toMatchObject({
3605 action: "replace",
3606 deleteFirst: true,
3607 deferredAdoption: { adopt: false },
3608 });
3609 yield* stack.destroy();
3610 }),
3611 );
3612
3613 test.provider("plans a provider without `read`, which has no ownership to check", (stack) =>
3614 Effect.gen(function* () {
3615 yield* setup(stack, { unread: true });
3616 const plan = yield* stack.plan(subject("fresh", { unread: true }));
3617 expect(plan.resources.Subject).toMatchObject({ action: "replace", deleteFirst: true });
3618 expect((plan.resources.Subject as any).deferredAdoption).toBeUndefined();
3619 yield* stack.destroy();
3620 }),
3621 );
3622
3623 /** Leaves `Subject` mid-replacement, holding its precreated identity. */
3624 const interrupted = Effect.fn(function* (stack: Test.ScratchStack) {
3625 const knobs = yield* setup(stack);
3626 knobs.crash = true;
3627 yield* stack
3628 .deploy(subject("fresh").pipe(adopt(true)))
3629 .pipe(Effect.catchTag("ResourceFailure", () => Effect.void));
3630 knobs.crash = false;
3631 return knobs;
3632 });
3633
3634 test.provider("resumes a replacement that already holds its precreated identity", (stack) =>
3635 Effect.gen(function* () {
3636 const knobs = yield* interrupted(stack);
3637 knobs.action = "update";
3638 // `Name` changes again, so the identity is unresolved at plan time.
3639 const plan = yield* stack.plan(subject("again"));
3640 expect(plan.resources.Subject).toMatchObject({
3641 action: "replace",
3642 state: { status: "replacing", attr: { name: "pending" } },
3643 });
3644 expect((plan.resources.Subject as any).restart).toBeUndefined();
3645 yield* stack.destroy();
3646 }),
3647 );
3648
3649 test.provider("refuses restarting a replacement onto an unresolved identity", (stack) =>
3650 Effect.gen(function* () {
3651 yield* interrupted(stack);
3652 const error = yield* stack.plan(subject("again")).pipe(Effect.flip);
3653 expect(error).toMatchObject({ _tag: "UnverifiableReplacement" });
3654 yield* stack.destroy();
3655 }),
3656 );
3657 });
3658
3659 describe("RefExpr resolution", { tags: ["unit", "local"] }, () => {
3660 const seedAt = (stack: string, stage: string, resources: Record<string, ResourceState>) =>
3661 Effect.gen(function* () {
3662 const state = yield* yield* State;
3663 for (const [fqn, value] of Object.entries(resources)) {
3664 yield* state.set({ stack, stage, fqn, value });
3665 }
3666 });
3667
3668 const sharedAttr = {
3669 string: "shared-string",
3670 stringArray: ["shared"],
3671 stableString: "shared-stable",
3672 stableArray: ["shared-stable"],
3673 replaceString: undefined,
3674 redacted: undefined,
3675 redactedArray: undefined,
3676 };
3677
3678 const sharedResourceState = {
3679 instanceId,
3680 providerVersion: 0,
3681 logicalId: "Shared",
3682 fqn: "Shared",
3683 namespace: undefined,
3684 resourceType: "Test.TestResource",
3685 status: "created" as ResourceStatus,
3686 props: { string: "shared-string" },
3687 attr: sharedAttr,
3688 bindings: [],
3689 downstream: [],
3690 } as ResourceState;
3691
3692 test(
3693 "resolves a cross-stage Ref to the seeded resource's attributes",
3694 Effect.gen(function* () {
3695 yield* seedAt(TEST_STACK, "other", { Shared: sharedResourceState });
3696 const plan = yield* Effect.gen(function* () {
3697 const shared = yield* TestResource.ref("Shared", { stage: "other" });
3698 yield* TestResource("Consumer", { string: shared.string });
3699 }).pipe(makePlan);
3700
3701 expect(plan.resources.Consumer?.action).toBe("create");
3702 expect((plan.resources.Consumer as any)?.props).toMatchObject({ string: "shared-string" });
3703 }),
3704 );
3705
3706 test(
3707 "resolves a cross-stack Ref using the explicit stack option",
3708 Effect.gen(function* () {
3709 yield* seedAt("other-stack", TEST_STAGE, { Shared: sharedResourceState });
3710 const plan = yield* Effect.gen(function* () {
3711 const shared = yield* TestResource.ref("Shared", { stack: "other-stack" });
3712 yield* TestResource("Consumer", { string: shared.string });
3713 }).pipe(makePlan);
3714
3715 expect((plan.resources.Consumer as any)?.props).toMatchObject({ string: "shared-string" });
3716 }),
3717 );
3718
3719 test(
3720 "Ref to a resource in the current stack/stage is resolved",
3721 Effect.gen(function* () {
3722 yield* seed({ Shared: sharedResourceState });
3723 const plan = yield* Effect.gen(function* () {
3724 const shared = yield* TestResource.ref("Shared");
3725 yield* TestResource("Consumer", { string: shared.string });
3726 }).pipe(makePlan);
3727
3728 expect((plan.resources.Consumer as any)?.props).toMatchObject({ string: "shared-string" });
3729 }),
3730 );
3731
3732 test(
3733 "missing Ref target dies with InvalidReferenceError",
3734 Effect.gen(function* () {
3735 const exit = yield* Effect.exit(
3736 Effect.gen(function* () {
3737 const shared = yield* TestResource.ref("Ghost", { stage: "other" });
3738 yield* TestResource("Consumer", { string: shared.string });
3739 }).pipe(makePlan),
3740 );
3741 expect(Exit.isFailure(exit)).toBe(true);
3742 if (Exit.isFailure(exit)) {
3743 const err = Cause.squash(exit.cause) as Output.InvalidReferenceError;
3744 expect(err._tag).toBe("InvalidReferenceError");
3745 expect(err.resourceId).toBe("Ghost");
3746 expect(err.stage).toBe("other");
3747 }
3748 }),
3749 );
3750 });
3751
3752 // A ref to a resource the same program declares, in the current stack and
3753 // stage, is a dependency exactly like a direct reference: an edge in the plan
3754 // DAG (create waits for the target, delete runs the dependent first) and an
3755 // unknown value while the target is created or changes. Every other ref keeps
3756 // reading persisted state and carries no edge.
3757 describe("same-stack refs to declared resources", { tags: ["unit", "local"] }, () => {
3758 const seedAt = (stack: string, stage: string, resources: Record<string, ResourceState>) =>
3759 Effect.gen(function* () {
3760 const state = yield* yield* State;
3761 for (const [fqn, value] of Object.entries(resources)) {
3762 yield* state.set({ stack, stage, fqn, value });
3763 }
3764 });
3765
3766 const row = (
3767 fqn: string,
3768 props: TestResourceProps,
3769 attr: Partial<TestResource["Attributes"]> = {},
3770 downstream: string[] = [],
3771 ): ResourceState =>
3772 ({
3773 instanceId,
3774 providerVersion: 0,
3775 logicalId: fqn.split("/").at(-1)!,
3776 fqn,
3777 namespace: undefined,
3778 resourceType: "Test.TestResource",
3779 status: "created" as ResourceStatus,
3780 props,
3781 attr: {
3782 string: props.string ?? fqn,
3783 stringArray: [],
3784 stableString: "stable",
3785 stableArray: [],
3786 replaceString: props.replaceString,
3787 redacted: undefined,
3788 redactedArray: undefined,
3789 ...attr,
3790 },
3791 bindings: [],
3792 downstream,
3793 }) as ResourceState;
3794
3795 // The same consumer written with a ref and with a direct reference.
3796 const viaRef = (sharedProps: TestResourceProps) =>
3797 Effect.gen(function* () {
3798 yield* TestResource("Shared", sharedProps);
3799 const shared = yield* TestResource.ref("Shared");
3800 yield* TestResource("Consumer", { string: shared.string });
3801 });
3802 const viaDirect = (sharedProps: TestResourceProps) =>
3803 Effect.gen(function* () {
3804 const shared = yield* TestResource("Shared", sharedProps);
3805 yield* TestResource("Consumer", { string: shared.string });
3806 });
3807
3808 test(
3809 "a ref to a resource created in the same deploy plans like a direct reference",
3810 Effect.gen(function* () {
3811 const plan = yield* viaRef({ string: "shared-string" }).pipe(makePlan);
3812
3813 expect(plan.resources.Shared!.action).toBe("create");
3814 expect(plan.resources.Consumer!.action).toBe("create");
3815 expect(plan.resources.Shared!.downstream).toContain("Consumer");
3816 expect(plan.resources.Consumer!.downstream).not.toContain("Shared");
3817 // Unknown until Shared is created, instead of an InvalidReferenceError.
3818 expect(Output.isExpr((plan.resources.Consumer as any).props.string)).toBe(true);
3819 }),
3820 );
3821
3822 const scenarios: [
3823 name: string,
3824 seeded: Record<string, ResourceState>,
3825 shared: TestResourceProps,
3826 ][] = [
3827 ["both new", {}, { string: "shared-string" }],
3828 [
3829 "nothing changes",
3830 {
3831 Shared: row("Shared", { string: "shared-string" }, {}, ["Consumer"]),
3832 Consumer: row("Consumer", { string: "shared-string" }),
3833 },
3834 { string: "shared-string" },
3835 ],
3836 [
3837 "the target updates",
3838 {
3839 Shared: row("Shared", { string: "shared-string" }, {}, ["Consumer"]),
3840 Consumer: row("Consumer", { string: "shared-string" }),
3841 },
3842 { string: "shared-string-v2" },
3843 ],
3844 [
3845 "the target is replaced",
3846 {
3847 Shared: row("Shared", { string: "shared-string", replaceString: "a" }, {}, ["Consumer"]),
3848 Consumer: row("Consumer", { string: "shared-string" }),
3849 },
3850 { string: "shared-string", replaceString: "b" },
3851 ],
3852 ];
3853
3854 for (const [name, seeded, shared] of scenarios) {
3855 test(
3856 `plans the same actions, props and edges as a direct reference when ${name}`,
3857 Effect.gen(function* () {
3858 yield* seed(seeded);
3859 const direct = yield* viaDirect(shared).pipe(makePlan);
3860 const ref = yield* viaRef(shared).pipe(makePlan);
3861
3862 for (const fqn of ["Shared", "Consumer"] as const) {
3863 expect(ref.resources[fqn]!.action).toBe(direct.resources[fqn]!.action);
3864 expect(ref.resources[fqn]!.downstream).toEqual(direct.resources[fqn]!.downstream);
3865 }
3866 // A noop node carries no props; a changing one carries the resolved
3867 // (or still unknown) value the consumer reads.
3868 if (direct.resources.Consumer!.action !== "noop") {
3869 const consumerString = (plan: typeof ref) =>
3870 (plan.resources.Consumer as any).props.string;
3871 expect(Output.isExpr(consumerString(ref))).toBe(Output.isExpr(consumerString(direct)));
3872 if (!Output.isExpr(consumerString(direct))) {
3873 expect(consumerString(ref)).toEqual(consumerString(direct));
3874 }
3875 }
3876 }),
3877 );
3878 }
3879
3880 test(
3881 "a ref naming the current stack and stage explicitly is an edge",
3882 Effect.gen(function* () {
3883 const plan = yield* Effect.gen(function* () {
3884 yield* TestResource("Shared", { string: "shared-string" });
3885 const shared = yield* TestResource.ref("Shared", { stack: TEST_STACK, stage: TEST_STAGE });
3886 yield* TestResource("Consumer", { string: shared.string });
3887 }).pipe(makePlan);
3888
3889 expect(plan.resources.Shared!.downstream).toContain("Consumer");
3890 }),
3891 );
3892
3893 test(
3894 "a ref to another stage is not an edge, even when this program declares the same id",
3895 Effect.gen(function* () {
3896 yield* seedAt(TEST_STACK, "other", {
3897 Shared: row("Shared", { string: "other-stage-string" }),
3898 });
3899 const plan = yield* Effect.gen(function* () {
3900 yield* TestResource("Shared", { string: "this-stage-string" });
3901 const shared = yield* TestResource.ref("Shared", { stage: "other" });
3902 yield* TestResource("Consumer", { string: shared.string });
3903 }).pipe(makePlan);
3904
3905 expect(plan.resources.Shared!.downstream).not.toContain("Consumer");
3906 expect((plan.resources.Consumer as any).props).toMatchObject({
3907 string: "other-stage-string",
3908 });
3909 }),
3910 );
3911
3912 test(
3913 "a ref to another stack is not an edge, even when this program declares the same id",
3914 Effect.gen(function* () {
3915 yield* seedAt("other-stack", TEST_STAGE, {
3916 Shared: row("Shared", { string: "other-stack-string" }),
3917 });
3918 const plan = yield* Effect.gen(function* () {
3919 yield* TestResource("Shared", { string: "this-stack-string" });
3920 const shared = yield* TestResource.ref("Shared", { stack: "other-stack" });
3921 yield* TestResource("Consumer", { string: shared.string });
3922 }).pipe(makePlan);
3923
3924 expect(plan.resources.Shared!.downstream).not.toContain("Consumer");
3925 expect((plan.resources.Consumer as any).props).toMatchObject({
3926 string: "other-stack-string",
3927 });
3928 }),
3929 );
3930
3931 test(
3932 "a ref to a resource only in state (not declared) reads state and is not an edge",
3933 Effect.gen(function* () {
3934 yield* seed({ Shared: row("Shared", { string: "state-only-string" }) });
3935 const plan = yield* Effect.gen(function* () {
3936 const shared = yield* TestResource.ref("Shared");
3937 yield* TestResource("Consumer", { string: shared.string });
3938 }).pipe(makePlan);
3939
3940 expect(plan.resources.Shared).toBeUndefined();
3941 expect((plan.resources.Consumer as any).props).toMatchObject({
3942 string: "state-only-string",
3943 });
3944 }),
3945 );
3946
3947 test(
3948 "a resource's ref to itself reads its persisted state and is not an edge",
3949 Effect.gen(function* () {
3950 yield* seed({ Self: row("Self", { string: "self-v1" }) });
3951 const plan = yield* Effect.gen(function* () {
3952 const self = yield* TestResource.ref("Self");
3953 yield* TestResource("Self", { string: "self-v2", stringArray: [self.string] });
3954 }).pipe(makePlan);
3955
3956 expect(plan.resources.Self!.action).toBe("update");
3957 expect(plan.resources.Self!.downstream).not.toContain("Self");
3958 expect((plan.resources.Self as any).props).toMatchObject({ stringArray: ["self-v1"] });
3959 }),
3960 );
3961
3962 test(
3963 "a ref is matched by the target's full FQN, not its logical id",
3964 Effect.gen(function* () {
3965 const plan = yield* Effect.gen(function* () {
3966 yield* TestResource("Shared", { string: "nested" }).pipe(Namespace.push("Ns"));
3967 const shared = yield* TestResource.ref("Ns/Shared");
3968 yield* TestResource("Consumer", { string: shared.string });
3969 }).pipe(makePlan);
3970 expect(plan.resources["Ns/Shared"]!.downstream).toContain("Consumer");
3971
3972 const bare = yield* Effect.exit(
3973 Effect.gen(function* () {
3974 yield* TestResource("Shared", { string: "nested" }).pipe(Namespace.push("Ns"));
3975 const shared = yield* TestResource.ref("Shared");
3976 yield* TestResource("Consumer", { string: shared.string });
3977 }).pipe(makePlan),
3978 );
3979 // `Shared` names no declared resource: it stays a state lookup.
3980 expect(Exit.isFailure(bare)).toBe(true);
3981 if (Exit.isFailure(bare)) {
3982 expect((Cause.squash(bare.cause) as Output.InvalidReferenceError)._tag).toBe(
3983 "InvalidReferenceError",
3984 );
3985 }
3986 }),
3987 );
3988
3989 test(
3990 "a ref used only in a binding is a binding edge",
3991 Effect.gen(function* () {
3992 const plan = yield* Effect.gen(function* () {
3993 yield* TestResource("Shared", { string: "shared-string" });
3994 const shared = yield* TestResource.ref("Shared");
3995 const host = yield* BindingTarget("Host", { name: "host" });
3996 yield* host.bind("Shared", { env: { SHARED: shared.string } });
3997 }).pipe(makePlan);
3998
3999 expect(plan.resources.Shared!.downstream).toContain("Host");
4000 }),
4001 );
4002
4003 test(
4004 "a ref in an Action's input is an edge to the Action",
4005 Effect.gen(function* () {
4006 const Compute = Action("Compute", (_: { name: string }) => Effect.succeed({ value: "v" }));
4007 const plan = yield* Effect.gen(function* () {
4008 yield* TestResource("Shared", { string: "shared-string" });
4009 const shared = yield* TestResource.ref("Shared");
4010 yield* Compute({ name: shared.string });
4011 }).pipe(makePlan);
4012
4013 expect(plan.resources.Shared!.downstream).toContain("Compute");
4014 }),
4015 );
4016 });
4017
4018 describe("StackRefExpr resolution", { tags: ["unit", "local"] }, () => {
4019 const setStackOutput = (stack: string, stage: string, value: unknown) =>
4020 Effect.gen(function* () {
4021 const state = yield* yield* State;
4022 yield* state.setOutput({ stack, stage, value });
4023 });
4024
4025 test(
4026 "resolves an Output.stackRef to the persisted stack output",
4027 Effect.gen(function* () {
4028 yield* setStackOutput("Backend", TEST_STAGE, { url: "https://api.example.com" });
4029 const plan = yield* Effect.gen(function* () {
4030 const backend = yield* Output.stackRef<{ url: string }>("Backend");
4031 yield* TestResource("Consumer", { string: (backend as any).url });
4032 }).pipe(makePlan);
4033
4034 expect(plan.resources.Consumer?.action).toBe("create");
4035 expect((plan.resources.Consumer as any)?.props).toMatchObject({
4036 string: "https://api.example.com",
4037 });
4038 }),
4039 );
4040
4041 test(
4042 "resolves an explicit stage on the stackRef",
4043 Effect.gen(function* () {
4044 yield* setStackOutput("Backend", "prod", { url: "https://prod.example.com" });
4045 const plan = yield* Effect.gen(function* () {
4046 const backend = yield* Output.stackRef<{ url: string }>("Backend", { stage: "prod" });
4047 yield* TestResource("Consumer", { string: (backend as any).url });
4048 }).pipe(makePlan);
4049
4050 expect((plan.resources.Consumer as any)?.props).toMatchObject({
4051 string: "https://prod.example.com",
4052 });
4053 }),
4054 );
4055
4056 test(
4057 "missing stack output dies with InvalidReferenceError",
4058 Effect.gen(function* () {
4059 const exit = yield* Effect.exit(
4060 Effect.gen(function* () {
4061 const backend = yield* Output.stackRef<{ url: string }>("Backend", { stage: "ghost" });
4062 yield* TestResource("Consumer", { string: (backend as any).url });
4063 }).pipe(makePlan),
4064 );
4065 expect(Exit.isFailure(exit)).toBe(true);
4066 if (Exit.isFailure(exit)) {
4067 const err = Cause.squash(exit.cause) as Output.InvalidReferenceError;
4068 expect(err._tag).toBe("InvalidReferenceError");
4069 expect(err.stack).toBe("Backend");
4070 expect(err.stage).toBe("ghost");
4071 }
4072 }),
4073 );
4074 });
4075
4076 describe("type aliases", { tags: ["unit", "local"] }, () => {
4077 // State rows persisted before a type rename carry the legacy name
4078 // ("Test.Widget"). Provider lookup must fall back to the canonical type
4079 // ("Test.Widgets.Widget") via the alias declared on the resource.
4080 const legacyWidgetState = (fqn: string): ResourceState => ({
4081 instanceId,
4082 providerVersion: 0,
4083 logicalId: fqn,
4084 fqn,
4085 namespace: undefined,
4086 resourceType: "Test.Widget",
4087 status: "created",
4088 props: { name: "widget" },
4089 attr: { name: "widget" },
4090 bindings: [],
4091 downstream: [],
4092 });
4093
4094 test(
4095 "orphan persisted under a legacy type name plans a delete via alias",
4096 Effect.gen(function* () {
4097 yield* seed({ LegacyOrphan: legacyWidgetState("LegacyOrphan") });
4098 expect(
4099 yield* makePlan(Effect.void).pipe(Effect.provide(aliasedWidgetProvider())),
4100 ).toMatchObject({
4101 deletions: {
4102 LegacyOrphan: {
4103 action: "delete",
4104 resource: { LogicalId: "LegacyOrphan", Type: "Test.Widget" },
4105 },
4106 },
4107 });
4108 }),
4109 );
4110
4111 test(
4112 "declared resource with legacy-typed state plans as a noop update",
4113 Effect.gen(function* () {
4114 yield* seed({ MyWidget: legacyWidgetState("MyWidget") });
4115 const plan = yield* makePlan(
4116 Effect.gen(function* () {
4117 yield* AliasedWidget("MyWidget", { name: "widget" });
4118 }),
4119 ).pipe(Effect.provide(aliasedWidgetProvider()));
4120 expect(plan).toMatchObject({
4121 resources: { MyWidget: { action: "noop", state: { resourceType: "Test.Widget" } } },
4122 });
4123 expect(Object.keys(plan.deletions)).toEqual([]);
4124 }),
4125 );
4126
4127 describe("via provider collection", () => {
4128 class AliasPlanProviders extends Provider.ProviderCollection<AliasPlanProviders>()(
4129 "Test.AliasPlanProviders",
4130 ) {}
4131
4132 // The bare provider layer is consumed while building the collection and
4133 // is NOT exported — lookup can only succeed through the collection.
4134 const widgetCollection = () =>
4135 Layer.effect(AliasPlanProviders, Provider.collection([AliasedWidget])).pipe(
4136 Layer.provide(aliasedWidgetProvider()),
4137 );
4138
4139 test(
4140 "orphan persisted under a legacy type name plans a delete via alias",
4141 Effect.gen(function* () {
4142 yield* seed({ LegacyOrphan: legacyWidgetState("LegacyOrphan") });
4143 expect(yield* makePlan(Effect.void).pipe(Effect.provide(widgetCollection()))).toMatchObject(
4144 {
4145 deletions: {
4146 LegacyOrphan: {
4147 action: "delete",
4148 resource: { LogicalId: "LegacyOrphan", Type: "Test.Widget" },
4149 },
4150 },
4151 },
4152 );
4153 }),
4154 );
4155 });
4156 });
4157
4158 describe("zombie rows", { tags: ["unit", "local"] }, () => {
4159 // A state row whose resource type has no registered provider (the type
4160 // was removed from the program, or renamed without an alias) is FATAL:
4161 // the program and state disagree, and without the provider the row's
4162 // physical resource cannot be deleted anyway. Planning dies with a typed
4163 // MissingProviderError naming the row and the remediation (see
4164 // destroy-robustness.test.ts for the deploy/destroy behavior).
4165 test(
4166 "a row whose resource type has no provider fails the plan",
4167 Effect.gen(function* () {
4168 yield* seed({
4169 Ghost: {
4170 instanceId,
4171 providerVersion: 0,
4172 logicalId: "Ghost",
4173 fqn: "Ghost",
4174 namespace: undefined,
4175 resourceType: "Test.Vanished",
4176 status: "created",
4177 props: { name: "ghost" },
4178 attr: { name: "ghost" },
4179 bindings: [],
4180 downstream: [],
4181 },
4182 });
4183 const exit = yield* makePlan(
4184 Effect.gen(function* () {
4185 yield* Bucket("Survivor", { name: "survivor" });
4186 }),
4187 ).pipe(Effect.exit);
4188
4189 expect(Exit.isFailure(exit)).toBe(true);
4190 const defect = Exit.isFailure(exit)
4191 ? exit.cause.reasons.find(
4192 (r) => Cause.isDieReason(r) && r.defect instanceof Provider.MissingProviderError,
4193 )
4194 : undefined;
4195 expect(defect && Cause.isDieReason(defect)).toBe(true);
4196 if (defect && Cause.isDieReason(defect)) {
4197 const error = defect.defect as Provider.MissingProviderError;
4198 expect(error.resourceType).toBe("Test.Vanished");
4199 expect(error.fqn).toBe("Ghost");
4200 expect(error.message).toContain("aliases");
4201 }
4202 }),
4203 );
4204 });
4205
4206 describe("read is never handed unresolved persisted props", { tags: ["unit", "local"] }, () => {
4207 // A failed create persists `creating` state carrying the RAW plan-time
4208 // props, which may contain unresolved Output expressions (e.g. a prop
4209 // referencing an upstream resource that was never created). Providers
4210 // derive identity from `olds` inside `read` when `output` is undefined,
4211 // so the engine must skip the read probe entirely rather than hand it
4212 // unresolved exprs (see the isResolved guards in Plan.ts).
4213
4214 const creatingWithUnresolvedProps = (fqn: string): ResourceState => ({
4215 instanceId,
4216 providerVersion: 0,
4217 logicalId: fqn,
4218 fqn,
4219 namespace: undefined,
4220 resourceType: "Test.TestResource",
4221 status: "creating",
4222 props: {
4223 // an unresolved Output expression, exactly as persisted by a create
4224 // that failed before its upstream dependencies resolved
4225 string: Output.literal("unresolved") as any,
4226 },
4227 attr: undefined,
4228 bindings: [],
4229 downstream: [],
4230 });
4231
4232 const trackReads = () => {
4233 const reads: string[] = [];
4234 const layer = Layer.succeed(TestResourceHooks, {
4235 read: (id: string) =>
4236 Effect.sync(() => {
4237 reads.push(id);
4238 return undefined;
4239 }),
4240 });
4241 return { reads, layer };
4242 };
4243
4244 test(
4245 "destroy after failed create with unresolved props skips read and deletes with attr undefined",
4246 Effect.gen(function* () {
4247 yield* seed({ Zombie: creatingWithUnresolvedProps("Zombie") });
4248 const { reads, layer } = trackReads();
4249 const plan = yield* makePlan(Effect.void).pipe(Effect.provide(layer));
4250 expect(reads).not.toContain("Zombie");
4251 expect(plan.deletions.Zombie).toMatchObject({ action: "delete" });
4252 expect((plan.deletions.Zombie as any).state.attr).toBeUndefined();
4253 }),
4254 );
4255
4256 test(
4257 "creating-state recovery with unresolved persisted props skips the read probe and re-drives create",
4258 Effect.gen(function* () {
4259 yield* seed({ Half: creatingWithUnresolvedProps("Half") });
4260 const { reads, layer } = trackReads();
4261 const plan = yield* makePlan(
4262 Effect.gen(function* () {
4263 yield* TestResource("Half", { string: "resolved-now" });
4264 }),
4265 ).pipe(Effect.provide(layer));
4266 expect(reads).not.toContain("Half");
4267 expect(plan.resources.Half!.action).toBe("create");
4268 }),
4269 );
4270
4271 test(
4272 "destroy of a creating row defers read recovery to apply even with resolved props",
4273 Effect.gen(function* () {
4274 // Plan never probes a deleted attr-less row — resolved or not. Apply's
4275 // `deleteResource` owns the authoritative read-then-delete recovery
4276 // (it also covers replaced-chain old generations that never pass
4277 // through plan); see the apply.test.ts destroy-recovery cases.
4278 yield* seed({
4279 Zombie: { ...creatingWithUnresolvedProps("Zombie"), props: { string: "resolved" } },
4280 });
4281 const { reads, layer } = trackReads();
4282 const plan = yield* makePlan(Effect.void).pipe(Effect.provide(layer));
4283 expect(reads).not.toContain("Zombie");
4284 expect(plan.deletions.Zombie).toMatchObject({ action: "delete" });
4285 expect((plan.deletions.Zombie as any).state.attr).toBeUndefined();
4286 }),
4287 );
4288
4289 test(
4290 "a recovery read that crashes degrades to re-driving the create instead of killing the plan",
4291 Effect.gen(function* () {
4292 // Stripped-at-commit props: an unresolved Output persisted as a hole
4293 // still passes `isResolved`, so the read probe DOES run — and a
4294 // provider that dereferences the hole crashes with a defect (e.g. a
4295 // SchemaError deep in its SDK client, see #995). The plan must
4296 // contain the defect to this resource's probe and fall through to
4297 // re-driving the create.
4298 yield* seed({
4299 Half: { ...creatingWithUnresolvedProps("Half"), props: { string: undefined } as any },
4300 });
4301 const layer = Layer.succeed(TestResourceHooks, {
4302 read: () => Effect.die(new Error("SchemaError: Expected string, got undefined")),
4303 });
4304 const plan = yield* makePlan(
4305 Effect.gen(function* () {
4306 yield* TestResource("Half", { string: "resolved-now" });
4307 }),
4308 ).pipe(Effect.provide(layer));
4309 expect(plan.resources.Half!.action).toBe("create");
4310 }),
4311 );
4312
4313 test(
4314 "resolved persisted creating props still go through read recovery when re-declared (control)",
4315 Effect.gen(function* () {
4316 yield* seed({
4317 Half: { ...creatingWithUnresolvedProps("Half"), props: { string: "resolved" } },
4318 });
4319 const { reads, layer } = trackReads();
4320 const plan = yield* makePlan(
4321 Effect.gen(function* () {
4322 yield* TestResource("Half", { string: "resolved-now" });
4323 }),
4324 ).pipe(Effect.provide(layer));
4325 expect(reads).toContain("Half");
4326 expect(plan.resources.Half!.action).toBe("create");
4327 }),
4328 );
4329
4330 // `propsIncomplete`: Apply stripped unresolved props from this attr-less
4331 // checkpoint, so the remaining props can identify a different resource.
4332 const incomplete = (fqn: string, props: Record<string, unknown>): ResourceState => ({
4333 ...creatingWithUnresolvedProps(fqn),
4334 props,
4335 propsIncomplete: true,
4336 });
4337
4338 test(
4339 "an incomplete creating row skips the read probe and defers admission to apply",
4340 Effect.gen(function* () {
4341 yield* seed({ Half: incomplete("Half", { string: "resolved" }) });
4342 const { reads, layer } = trackReads();
4343 const plan = yield* makePlan(
4344 Effect.gen(function* () {
4345 yield* TestResource("Half", { string: "resolved" });
4346 }),
4347 ).pipe(Effect.provide(layer));
4348 expect(reads).toEqual([]);
4349 expect(plan.resources.Half).toMatchObject({
4350 action: "create",
4351 props: { string: "resolved" },
4352 deferredAdoption: { adopt: false },
4353 });
4354 }),
4355 );
4356
4357 test(
4358 "an incomplete creating row carries a scoped adopt(true) into deferred admission",
4359 Effect.gen(function* () {
4360 yield* seed({ Half: incomplete("Half", { string: "resolved" }) });
4361 const { reads, layer } = trackReads();
4362 const plan = yield* makePlan(
4363 Effect.gen(function* () {
4364 yield* TestResource("Half", { string: "resolved" }).pipe(adopt(true));
4365 }),
4366 ).pipe(Effect.provide(layer));
4367 expect(reads).toEqual([]);
4368 expect(plan.resources.Half).toMatchObject({
4369 action: "create",
4370 deferredAdoption: { adopt: true },
4371 });
4372 }),
4373 );
4374
4375 test(
4376 "an incomplete creating row still diffs: an immutable change plans a replacement",
4377 Effect.gen(function* () {
4378 yield* seed({ Half: incomplete("Half", { replaceString: "old" }) });
4379 const { reads, layer } = trackReads();
4380 const plan = yield* makePlan(
4381 Effect.gen(function* () {
4382 yield* TestResource("Half", { replaceString: "new" });
4383 }),
4384 ).pipe(Effect.provide(layer));
4385 expect(reads).toEqual([]);
4386 expect(plan.resources.Half).toMatchObject({
4387 action: "replace",
4388 props: { replaceString: "new" },
4389 state: { status: "creating", propsIncomplete: true },
4390 });
4391 }),
4392 );
4393
4394 test(
4395 "destroy of an incomplete creating row hands apply the marker without probing",
4396 Effect.gen(function* () {
4397 yield* seed({ Zombie: incomplete("Zombie", { string: "resolved" }) });
4398 const { reads, layer } = trackReads();
4399 const plan = yield* makePlan(Effect.void).pipe(Effect.provide(layer));
4400 expect(reads).toEqual([]);
4401 expect(plan.deletions.Zombie).toMatchObject({
4402 action: "delete",
4403 state: { status: "creating", attr: undefined, propsIncomplete: true },
4404 });
4405 }),
4406 );
4407 });
4408
4409 describe("provider modes (local ⇄ live)", { tags: ["unit", "local"] }, () => {
4410 // ModalResource registers via `ProviderLayer.dual` with distinct live and
4411 // local implementations. These tests cover the PLAN-level semantics:
4412 // - the resolved mode lands on the plan node (`node.mode`)
4413 // - a persisted mode different from the resolved mode forces a
4414 // REPLACEMENT, overriding whatever the provider diff would say
4415 // - legacy rows (no persisted mode) are assumed live, unless their
4416 // attrs carry the `dev:` identity marker (then local)
4417 // - deletions carry the persisted mode so orphans are torn down by the
4418 // provider that created them
4419 // - a mode-switching upstream invalidates its attrs for downstream diffs
4420
4421 const modalState = (fqn: string, overrides?: Partial<ResourceState>): ResourceState =>
4422 ({
4423 instanceId,
4424 providerVersion: 0,
4425 logicalId: fqn,
4426 fqn,
4427 namespace: undefined,
4428 resourceType: "Test.ModalResource",
4429 status: "created",
4430 props: { value: "v1" },
4431 attr: { value: "v1", runtime: "local" },
4432 downstream: [],
4433 bindings: [],
4434 providerMode: "local",
4435 ...overrides,
4436 }) as ResourceState;
4437
4438 test(
4439 "a fresh create resolves the run default (live) onto the node",
4440 Effect.gen(function* () {
4441 const plan = yield* makePlan(ModalResource("A", { value: "v1" }));
4442 expect(plan.resources.A).toMatchObject({ action: "create", mode: "live" });
4443 }),
4444 );
4445
4446 test(
4447 "a dev run resolves the local mode onto the node",
4448 Effect.gen(function* () {
4449 const plan = yield* inDev(makePlan(ModalResource("A", { value: "v1" })));
4450 expect(plan.resources.A).toMatchObject({ action: "create", mode: "local" });
4451 }),
4452 );
4453
4454 test(
4455 "remote() opts a resource out of local emulation during dev",
4456 Effect.gen(function* () {
4457 const plan = yield* inDev(makePlan(ModalResource("A", { value: "v1" }).pipe(remote())));
4458 expect(plan.resources.A).toMatchObject({ action: "create", mode: "live" });
4459 }),
4460 );
4461
4462 test(
4463 "mode-agnostic resources plan with mode undefined even in a dev run",
4464 Effect.gen(function* () {
4465 // A single-implementation provider (no dual registration) satisfies
4466 // any requested mode — constructs that mix emulatable and live-only
4467 // resources just work in dev.
4468 const plan = yield* inDev(
4469 makePlan(
4470 Effect.gen(function* () {
4471 yield* ModalResource("A", { value: "v1" });
4472 yield* TestResource("T", { string: "x" });
4473 }),
4474 ),
4475 );
4476 expect(plan.resources.A!.mode).toBe("local");
4477 expect(plan.resources.T!.mode).toBeUndefined();
4478 }),
4479 );
4480
4481 test(
4482 "a persisted mode different from the resolved mode forces a replacement",
4483 Effect.gen(function* () {
4484 yield* seed({ A: modalState("A") }); // providerMode: "local"
4485
4486 // Identical props — the provider diff would report `noop` — but the
4487 // row was reconciled by the LOCAL provider and this run resolves to
4488 // LIVE, so the plan must replace (create-first).
4489 const plan = yield* makePlan(ModalResource("A", { value: "v1" }));
4490 expect(plan.resources.A).toMatchObject({
4491 action: "replace",
4492 deleteFirst: false,
4493 mode: "live",
4494 });
4495 }),
4496 );
4497
4498 test(
4499 "the same mode plans normally (noop on identical props)",
4500 Effect.gen(function* () {
4501 yield* seed({ A: modalState("A") }); // providerMode: "local"
4502 const plan = yield* inDev(makePlan(ModalResource("A", { value: "v1" })));
4503 expect(plan.resources.A).toMatchObject({ action: "noop" });
4504 }),
4505 );
4506
4507 test(
4508 "switching live → local replaces too",
4509 Effect.gen(function* () {
4510 yield* seed({ A: modalState("A", { providerMode: "live" }) });
4511 const plan = yield* inDev(makePlan(ModalResource("A", { value: "v1" })));
4512 expect(plan.resources.A).toMatchObject({ action: "replace", mode: "local" });
4513 }),
4514 );
4515
4516 test(
4517 "a mode switch overrides the provider diff (update would have sufficed)",
4518 Effect.gen(function* () {
4519 yield* seed({ A: modalState("A") }); // providerMode: "local"
4520 // Changed value — same-mode planning would produce `update` — but the
4521 // mode switch escalates to `replace` without consulting the diff.
4522 const plan = yield* makePlan(ModalResource("A", { value: "v2" }));
4523 expect(plan.resources.A).toMatchObject({ action: "replace", mode: "live" });
4524 }),
4525 );
4526
4527 test(
4528 "legacy rows without a persisted mode are assumed live",
4529 Effect.gen(function* () {
4530 yield* seed({ A: modalState("A", { providerMode: undefined }) });
4531
4532 // An unstamped row was written by a pre-provider-mode engine (or by
4533 // a provider that only became dual later) — its physical resource is
4534 // LIVE. A deploy (live) run sees no churn; a dev run replaces it
4535 // exactly like a stamped live row. Assuming the run's mode instead
4536 // would silently adopt the deployed live resource as a local
4537 // instance and leak it untracked.
4538 const liveDefault = yield* makePlan(ModalResource("A", { value: "v1" }));
4539 expect(liveDefault.resources.A).toMatchObject({ action: "noop" });
4540
4541 const devRun = yield* inDev(makePlan(ModalResource("A", { value: "v1" })));
4542 expect(devRun.resources.A).toMatchObject({ action: "replace", mode: "local" });
4543 }),
4544 );
4545
4546 test(
4547 "a mode-agnostic resource never replaces across dev/deploy runs",
4548 Effect.gen(function* () {
4549 yield* seed({
4550 T: {
4551 instanceId,
4552 providerVersion: 0,
4553 logicalId: "T",
4554 fqn: "T",
4555 namespace: undefined,
4556 resourceType: "Test.TestResource",
4557 status: "created",
4558 props: { string: "x" },
4559 attr: { string: "x", stringArray: [], stableString: "T", stableArray: ["T"] },
4560 downstream: [],
4561 bindings: [],
4562 // Mode-agnostic providers never stamp a mode.
4563 providerMode: undefined,
4564 },
4565 });
4566 const plan = yield* inDev(makePlan(TestResource("T", { string: "x" })));
4567 expect(plan.resources.T).toMatchObject({ action: "noop" });
4568 }),
4569 );
4570
4571 test(
4572 "an interrupted create still replaces on a mode switch",
4573 Effect.gen(function* () {
4574 // A `creating` row (attr-less, interrupted) normally re-drives its
4575 // create via the read-recovery branch. When the mode switched, that
4576 // branch is skipped — the other runtime's half-created instance must
4577 // be replaced, not resumed.
4578 yield* seed({
4579 A: modalState("A", { status: "creating", attr: undefined } as Partial<ResourceState>),
4580 });
4581 const plan = yield* makePlan(ModalResource("A", { value: "v1" }));
4582 expect(plan.resources.A).toMatchObject({ action: "replace", mode: "live" });
4583 }),
4584 );
4585
4586 test(
4587 "an interrupted update still replaces on a mode switch",
4588 Effect.gen(function* () {
4589 yield* seed({
4590 A: modalState("A", {
4591 status: "updating",
4592 props: { value: "v2" },
4593 old: { props: { value: "v1" }, bindings: [], attr: { value: "v1", runtime: "local" } },
4594 } as Partial<ResourceState>),
4595 });
4596 // Same-mode planning would resume the interrupted update; a mode
4597 // switch must escalate to a replacement of the other runtime's
4598 // instance instead.
4599 const plan = yield* makePlan(ModalResource("A", { value: "v2" }));
4600 expect(plan.resources.A).toMatchObject({ action: "replace", mode: "live" });
4601 }),
4602 );
4603
4604 test(
4605 "an in-flight replacement generation hit by a mode switch restarts a new generation",
4606 Effect.gen(function* () {
4607 // `replacing`: the (local) replacement candidate is still being
4608 // created. A mode switch makes that candidate itself obsolete — the
4609 // plan must mint a NEW outer generation (`restart: true`) rather than
4610 // resuming the local candidate under the live provider.
4611 yield* seed({
4612 A: modalState("A", {
4613 status: "replacing",
4614 attr: undefined,
4615 deleteFirst: false,
4616 old: modalState("A", { instanceId: "00000000000000000000000000000000" }),
4617 } as Partial<ResourceState>),
4618 });
4619 const plan = yield* makePlan(ModalResource("A", { value: "v1" }));
4620 expect(plan.resources.A).toMatchObject({ action: "replace", restart: true, mode: "live" });
4621 }),
4622 );
4623
4624 test(
4625 "a completed-but-undrained replacement hit by a mode switch restarts; same mode just drains",
4626 Effect.gen(function* () {
4627 const replaced = (providerMode: "local" | "live") =>
4628 modalState("A", {
4629 status: "replaced",
4630 deleteFirst: false,
4631 providerMode,
4632 old: modalState("A", { instanceId: "00000000000000000000000000000000" }),
4633 } as Partial<ResourceState>);
4634
4635 // The live replacement of a LOCAL row completed but its old chain
4636 // hasn't drained. Re-planning in the same (live) mode continues the
4637 // existing generation (no restart — GC just finishes).
4638 yield* seed({ A: replaced("live") });
4639 const sameMode = yield* makePlan(ModalResource("A", { value: "v1" }));
4640 expect(sameMode.resources.A).toMatchObject({ action: "replace" });
4641 expect((sameMode.resources.A as any).restart).toBeUndefined();
4642
4643 // But if the completed replacement was LOCAL and this run resolves
4644 // live, the current "new" generation is itself obsolete — restart.
4645 yield* seed({ A: replaced("local") });
4646 const switched = yield* makePlan(ModalResource("A", { value: "v1" }));
4647 expect(switched.resources.A).toMatchObject({
4648 action: "replace",
4649 restart: true,
4650 mode: "live",
4651 });
4652 }),
4653 );
4654
4655 test(
4656 "orphan deletions carry the persisted mode",
4657 Effect.gen(function* () {
4658 yield* seed({
4659 LocalOrphan: modalState("LocalOrphan"), // providerMode: "local"
4660 LegacyOrphan: modalState("LegacyOrphan", { providerMode: undefined }),
4661 });
4662 const plan = yield* makePlan(Effect.void);
4663 // The Delete node records the mode its provider was resolved for —
4664 // Apply deletes the local orphan with the LOCAL provider even though
4665 // this is a live-default run.
4666 expect(plan.deletions.LocalOrphan).toMatchObject({ action: "delete", mode: "local" });
4667 expect(plan.deletions.LegacyOrphan).toMatchObject({ action: "delete" });
4668 expect(plan.deletions.LegacyOrphan!.mode).toBeUndefined();
4669 }),
4670 );
4671
4672 test(
4673 "a mode-switching upstream invalidates its attrs for downstream diffs",
4674 Effect.gen(function* () {
4675 yield* seed({
4676 A: modalState("A", { downstream: ["B"] }), // providerMode: "local"
4677 B: {
4678 instanceId,
4679 providerVersion: 0,
4680 logicalId: "B",
4681 fqn: "B",
4682 namespace: undefined,
4683 resourceType: "Test.TestResource",
4684 status: "created",
4685 props: { string: "v1" },
4686 attr: { string: "v1", stringArray: [], stableString: "B", stableArray: ["B"] },
4687 downstream: [],
4688 bindings: [],
4689 },
4690 });
4691
4692 const program = Effect.gen(function* () {
4693 const a = yield* ModalResource("A", { value: "v1" });
4694 yield* TestResource("B", { string: a.value });
4695 });
4696
4697 // Mode switch (local row, deploy plan): A is being replaced, so its
4698 // attrs are NOT stable — B must observe an unresolved upstream and
4699 // plan an update rather than nooping against stale values.
4700 const switched = yield* makePlan(program);
4701 expect(switched.resources.A).toMatchObject({ action: "replace" });
4702 expect(switched.resources.B).toMatchObject({ action: "update" });
4703
4704 // Control — same mode (dev run): A noops, its persisted attrs
4705 // resolve, B noops.
4706 const same = yield* inDev(makePlan(program));
4707 expect(same.resources.A).toMatchObject({ action: "noop" });
4708 expect(same.resources.B).toMatchObject({ action: "noop" });
4709 }),
4710 );
4711 });
4712
4713 describe("binding client data-plane routing (plan)", { tags: ["unit", "local"] }, () => {
4714 // Binding.Service wraps deploy-time clients so they hit the plane the
4715 // bound resource actually lives on. In a `dev` run ambient is the
4716 // emulator; `Alchemy.remote()` must still wrap with the live layer (the
4717 // inverse of the local wrap). Plan-time `yield* client()` is the same
4718 // routing `Service.execute` uses.
4719
4720 test(
4721 "in a dev run, a local resource's binding client hits the emulator plane",
4722 Effect.gen(function* () {
4723 const plan = yield* inDev(
4724 makePlan(
4725 Effect.gen(function* () {
4726 const a = yield* ModalResource("A", { value: "v1" });
4727 const read = yield* ProbeBinding(a);
4728 return yield* read();
4729 }),
4730 ),
4731 );
4732 expect(plan.output).toBe("local");
4733 }),
4734 );
4735
4736 test(
4737 "in a dev run, a remote() resource's binding client hits the live plane",
4738 Effect.gen(function* () {
4739 const plan = yield* inDev(
4740 makePlan(
4741 Effect.gen(function* () {
4742 const a = yield* ModalResource("A", { value: "v1" }).pipe(remote());
4743 const read = yield* ProbeBinding(a);
4744 return yield* read();
4745 }),
4746 ),
4747 );
4748 expect(plan.output).toBe("live");
4749 }),
4750 );
4751
4752 test(
4753 "a live-mode run wraps remote/live clients with the live plane (not ambient)",
4754 Effect.gen(function* () {
4755 const plan = yield* makePlan(
4756 Effect.gen(function* () {
4757 const a = yield* ModalResource("A", { value: "v1" });
4758 const read = yield* ProbeBinding(a);
4759 return yield* read();
4760 }),
4761 );
4762 expect(plan.output).toBe("live");
4763 }),
4764 );
4765
4766 test(
4767 "a binding spanning local and remote() resources dies",
4768 Effect.gen(function* () {
4769 const exit = yield* inDev(
4770 makePlan(
4771 Effect.gen(function* () {
4772 const local = yield* ModalResource("A", { value: "v1" });
4773 const live = yield* ModalResource("B", { value: "v1" }).pipe(remote());
4774 const read = yield* ProbeBinding([local, live]);
4775 return yield* read();
4776 }),
4777 ),
4778 ).pipe(Effect.exit);
4779 expect(Exit.isFailure(exit)).toBe(true);
4780 if (Exit.isFailure(exit)) {
4781 expect(String(Cause.squash(exit.cause))).toContain("mixed data planes");
4782 }
4783 }),
4784 );
4785 });
4786
4787 // Upstream dependency detection must find a Resource/Output reference at ANY
4788 // nesting depth of plain data — objects in arrays, arrays in objects, and
4789 // arbitrary mixes (#1082 hardened the walkers with a plain-data gate + cycle
4790 // guards; these pin that no nesting shape lost its dependency edge). Each
4791 // case plans `A` (upstream) and `B` whose props embed a reference to `A` in a
4792 // different shape, then asserts the A→B edge exists in the plan DAG.
4793 describe("upstream detection across nesting shapes", { tags: ["unit", "local"] }, () => {
4794 // Each shape gets the raw resource and an attr Output to embed.
4795 const shapes: [name: string, props: (a: any) => Record<string, any>][] = [
4796 ["raw resource at top level", (a) => ({ ref: a })],
4797 ["attr output at top level", (a) => ({ name: a.name })],
4798 ["raw resource in object", (a) => ({ obj: { ref: a } })],
4799 ["attr output in object", (a) => ({ obj: { name: a.name } })],
4800 ["deeply nested object (4 levels)", (a) => ({ l1: { l2: { l3: { l4: { name: a.name } } } } })],
4801 ["raw resource in array", (a) => ({ arr: [a] })],
4802 ["attr output in array", (a) => ({ arr: [a.name] })],
4803 ["output among primitives in array", (a) => ({ arr: [1, "x", a.name, null, true] })],
4804 ["array in object in array", (a) => ({ arr: [{ inner: [a.name] }] })],
4805 ["object in array in object", (a) => ({ obj: { list: [{ ref: a }] } })],
4806 [
4807 "arrays in objects in arrays in objects",
4808 (a) => ({
4809 layers: [
4810 { config: { hosts: [{ url: a.name }, { url: "static" }] } },
4811 { config: { hosts: [] } },
4812 ],
4813 }),
4814 ],
4815 [
4816 "mixed: raw resource and output at different depths",
4817 (a) => ({ top: a, nested: { deep: [{ deeper: { name: a.name } }] } }),
4818 ],
4819 [
4820 "nested empty containers alongside the ref",
4821 (a) => ({ empties: [{}, [], { x: [] }], ref: { arr: [[a.name]] } }),
4822 ],
4823 ["array of arrays", (a) => ({ matrix: [[a.name]] })],
4824 ];
4825
4826 for (const [name, props] of shapes) {
4827 test(
4828 `finds the dependency: ${name}`,
4829 Effect.gen(function* () {
4830 const plan = yield* Effect.gen(function* () {
4831 const a = yield* Bucket("A", { name: "nest-a" });
4832 yield* TestResource("B", props(a) as any);
4833 }).pipe(makePlan);
4834
4835 expect(plan.resources.A!.action).toBe("create");
4836 expect(plan.resources.B!.action).toBe("create");
4837 // The dependency edge A -> B must exist regardless of nesting shape.
4838 expect(plan.resources.A!.downstream).toContain("B");
4839 expect(plan.resources.B!.downstream).not.toContain("A");
4840 }),
4841 );
4842 }
4843
4844 test(
4845 "a reference inside a foreign class instance is NOT a dependency",
4846 Effect.gen(function* () {
4847 class SdkConfig {
4848 constructor(readonly ref: any) {}
4849 }
4850 const plan = yield* Effect.gen(function* () {
4851 const a = yield* Bucket("A", { name: "nest-a" });
4852 yield* TestResource("B", { config: new SdkConfig(a.name) } as any);
4853 }).pipe(makePlan);
4854
4855 expect(plan.resources.A!.downstream).not.toContain("B");
4856 }),
4857 );
4858
4859 test(
4860 "cyclic plain objects in props do not hang planning",
4861 Effect.gen(function* () {
4862 const cyclic: any = { name: "cycle" };
4863 cyclic.self = cyclic;
4864 const plan = yield* Effect.gen(function* () {
4865 const a = yield* Bucket("A", { name: "nest-a" });
4866 yield* TestResource("B", { config: cyclic, ref: a.name } as any);
4867 }).pipe(makePlan);
4868
4869 // The cycle is tolerated AND the sibling dependency is still found.
4870 expect(plan.resources.A!.downstream).toContain("B");
4871 }),
4872 );
4873 });
4874
4875 describe("renamed resources (renamedFrom)", { tags: ["unit", "local"] }, () => {
4876 const bucketRow = (fqn: string, rowInstanceId: string = instanceId): ResourceState => ({
4877 instanceId: rowInstanceId,
4878 providerVersion: 0,
4879 logicalId: parseFqnLogicalId(fqn),
4880 fqn,
4881 namespace: undefined,
4882 resourceType: "Test.Bucket",
4883 status: "created",
4884 props: { name: "b" },
4885 attr: { name: "b", bucketArn: `arn:test:bucket:${fqn}` },
4886 bindings: [],
4887 downstream: [],
4888 });
4889 const parseFqnLogicalId = (fqn: string) => fqn.split("/").pop()!;
4890
4891 test(
4892 "a row at a former FQN plans as an update at the new FQN, never a create+delete",
4893 Effect.gen(function* () {
4894 yield* seed({ OldBucket: bucketRow("OldBucket") });
4895
4896 const plan = yield* Effect.gen(function* () {
4897 yield* Bucket("NewBucket", { name: "b" }).pipe(renamedFrom("OldBucket"));
4898 return {};
4899 }).pipe(makePlan);
4900
4901 const node = plan.resources.NewBucket!;
4902 // An update, not a noop: the physical resource's tags are still
4903 // branded with the OLD logical id, so a reconcile must run to
4904 // re-brand them under the new identity. Never a create.
4905 expect(node.action).toEqual("update");
4906 expect(node.renamedFrom).toEqual(["OldBucket"]);
4907 // The row rides on the node under its NEW identity (apply persists
4908 // the move before any lifecycle runs).
4909 expect(node.state?.fqn).toEqual("NewBucket");
4910 expect(node.state?.logicalId).toEqual("NewBucket");
4911 expect(node.state?.instanceId).toEqual(instanceId);
4912 // The former row is NOT an orphan.
4913 expect(Object.keys(plan.deletions)).toHaveLength(0);
4914 }),
4915 );
4916
4917 test(
4918 "the alias is ignored when the new FQN already has a row with a different instanceId",
4919 Effect.gen(function* () {
4920 yield* seed({
4921 OldBucket: bucketRow("OldBucket", "0ld00000000000000000000000000000"),
4922 NewBucket: bucketRow("NewBucket"),
4923 });
4924
4925 const plan = yield* Effect.gen(function* () {
4926 yield* Bucket("NewBucket", { name: "b" }).pipe(renamedFrom("OldBucket"));
4927 return {};
4928 }).pipe(makePlan);
4929
4930 // The declared resource plans from its OWN row...
4931 const node = plan.resources.NewBucket!;
4932 expect(node.action).toEqual("noop");
4933 expect(node.renamedFrom).toBeUndefined();
4934 expect(node.state?.instanceId).toEqual(instanceId);
4935 // ...and the former row is a distinct resource: a normal orphan.
4936 expect(plan.deletions.OldBucket?.action).toEqual("delete");
4937 }),
4938 );
4939
4940 test(
4941 "rows at both FQNs with the same instanceId are an in-flight migration, not an orphan",
4942 Effect.gen(function* () {
4943 // Simulates a crash between apply's `state.set` (new FQN) and
4944 // `state.delete` (former FQN).
4945 yield* seed({ OldBucket: bucketRow("OldBucket"), NewBucket: bucketRow("NewBucket") });
4946
4947 const plan = yield* Effect.gen(function* () {
4948 yield* Bucket("NewBucket", { name: "b" }).pipe(renamedFrom("OldBucket"));
4949 return {};
4950 }).pipe(makePlan);
4951
4952 // The node plans from the new row and marks the leftover for
4953 // state-only cleanup at apply; no delete of the physical resource.
4954 const node = plan.resources.NewBucket!;
4955 expect(node.action).toEqual("noop");
4956 expect(node.renamedFrom).toEqual(["OldBucket"]);
4957 expect(Object.keys(plan.deletions)).toHaveLength(0);
4958 }),
4959 );
4960
4961 test(
4962 "the old id can be reused by a new resource in the same deploy",
4963 Effect.gen(function* () {
4964 yield* seed({ OldBucket: bucketRow("OldBucket") });
4965
4966 const plan = yield* Effect.gen(function* () {
4967 // A brand-new resource reuses the old id...
4968 yield* Bucket("OldBucket", { name: "fresh" });
4969 // ...while the original resource (which owns the row) renames.
4970 yield* Bucket("NewBucket", { name: "b" }).pipe(renamedFrom("OldBucket"));
4971 return {};
4972 }).pipe(makePlan);
4973
4974 // The rename claim wins the row: `NewBucket` migrates it...
4975 const renamed = plan.resources.NewBucket!;
4976 expect(renamed.action).toEqual("update");
4977 expect(renamed.renamedFrom).toEqual(["OldBucket"]);
4978 expect(renamed.state?.instanceId).toEqual(instanceId);
4979 // ...and the reusing resource starts from scratch — it must NOT
4980 // inherit the migrated resource's row (or physical resource).
4981 const reuser = plan.resources.OldBucket!;
4982 expect(reuser.action).toEqual("create");
4983 expect(reuser.state).toBeUndefined();
4984 expect(Object.keys(plan.deletions)).toHaveLength(0);
4985 }),
4986 );
4987
4988 test(
4989 "former ids resolve against the ambient namespace (StaticSite's <id>/Worker → <id>)",
4990 Effect.gen(function* () {
4991 // The pre-rename shape: a `Worker` resource declared under the
4992 // `App/Site` namespace chain.
4993 yield* seed({
4994 "App/Site/Worker": {
4995 ...bucketRow("App/Site/Worker"),
4996 namespace: { Id: "Site", Parent: { Id: "App" } },
4997 },
4998 });
4999
5000 const plan = yield* Effect.gen(function* () {
Showing first 5,000 of 6,040 lines. View raw