Lifecycle and rebuilds
Rebuild a circuit with generations, run old and new circuits side by side, roll back, forget or retire old generations, and cascade to downstream circuits.
Views builds its lifecycle directly on @streamsy/projection generations and retirement. Because every circuit output must use Projection.perGeneration, each generation owns its own operator-state namespace and its own output stream addresses.
Retain your input State stream history so circuits can rebuild from the start when plans change.
Plan identity and namespaces
The circuit id, generation, and encoded binding params identify the operator namespace. The first unit in a namespace stores the circuit's canonical plan hash. SQLite, Postgres, and MySQL store the hash in streamsy_view_circuits. A memory backend keeps it in the heap with the namespace's other state.
On every subsequent unit in that namespace, the circuit compares the declared plan hash with the stored hash:
- If they differ, the unit fails before committing with
PlanChanged(_tag: "ViewPlanChanged"). Operator state, output streams, and checkpoint offsets stay at their last committed values. - Attached runners treat
PlanChangedas non-retryable and stop only the affected binding. - Reordering view keys or object properties preserves the hash. Changing
maxAffectedKeysalso preserves the hash. - Collection codec changes are not reflected in the plan hash; raise
generationwhen a codec changes.
Scenario 1: edit in place with a raised generation
To replace a circuit plan in one deploy, edit the views and raise generation on the same declaration. Migrate a declaration that set version
export const smoke = Effect.gen(function* () {
// ...
// The new plan excludes orders below 25 and replays into a fresh stream.
const rebuilt = shopCircuit(2, 25);
yield* Projection.run(rebuilt.at(params));
// ...
}).pipe(Effect.provide(host));Because the output is wrapped with Projection.perGeneration, generation 2 writes to a new stream address (for example shop/main/views/g/2) while generation 1's stream (shop/main/views/g/1) stays untouched. Keys dropped by the new filter simply never appear in generation 2's stream.
On startup, Projection.attach and ProjectionWakeup.attach use the checkpoint inventory for the circuit id, when available. They queue bindings with a live checkpoint at another generation and no checkpoint at the attached generation. They also consider {} for a circuit with no params. Pass a bindings Effect to supply the inventory yourself. The runner replays queued bindings in the background. Choose the binding inventory
For startup replay, the runner creates fixed wrapped streams before it queues the binding. Routed streams open on demand in a unit. Readers can see StreamNotFound before streams are created and partial results until replay catches up. Keep readers and State tables pinned to generation 1 until generation 2 is ready. Check replay progress
Scenario 2: run old and new side by side
When readers must stay on a live, complete stream while the new plan rebuilds and is verified, run both generations side by side across three deploys.
Use two distinct circuit ids and two distinct generation numbers:
import { Layer, Schema } from "effect";
import { Projection } from "@streamsy/projection";
import { View } from "@streamsy/views";
import { Orders, ShopViews } from "./streams.ts";
const orders = View.from(Orders, "order");
const totalsFor = (source: typeof orders) =>
source
.groupBy((row) => ({ customerId: row.customerId }))
.aggregate((row) => ({ orders: View.count(), revenue: View.sum(row.total) }));
const topFor = (source: typeof orders) =>
source.top({
partitionBy: (row) => row.customerId,
by: (row) => [row.total.desc(), row.orderId.asc()],
limit: 1,
});
export const shopViewsV1 = View.circuit({
id: "views-shop",
generation: 1,
params: { shopId: Schema.String },
output: Projection.perGeneration(ShopViews, "generation"),
views: { customerTotals: totalsFor(orders), topOrder: topFor(orders) },
});
const filtered = orders.where((row) => row.total.gte(25));
export const shopViewsV2 = View.circuit({
id: "views-shop-2",
generation: 2,
params: { shopId: Schema.String },
output: Projection.perGeneration(ShopViews, "generation"),
views: { customerTotals: totalsFor(filtered), topOrder: topFor(filtered) },
});
// Deploy 1: attach both while readers stay on generation 1.
export const overlap = Layer.mergeAll(
Projection.attach(shopViewsV1, { durable: true }),
Projection.attach(shopViewsV2, { durable: true }),
);Why both the id and generation must differ:
- Distinct
id:Projection.Registryrejects two attachments with the same id, and pending marks and backoff are keyed by id and params. Separate ids prevent a bug or backoff in the new circuit from stalling the serving circuit. - Distinct
generation: the generation number selects theProjection.perGenerationoutput stream address. Two ids with the same generation target the same stream, and the second writer fails with non-retryableinvalid-output.
Run the cutover in three deploys:
- Deploy 1 (build side by side). Add
shopViewsV2besideshopViewsV1and attach both. Schedule or runshopViewsV2bindings so they catch up from input history. Keep readers pinned to generation 1. - Deploy 2 (switch readers). Point readers and any output
StateTablebindings to generation 2. Stop attachingshopViewsV1, but keep its declaration in code until retirement finishes. - Retire and Deploy 3 (clean up). After old runners have stopped and drained, retire each binding of
shopViewsV1withProjection.retire(and clear any oldStateTablecache). Then deploy the code change that removesshopViewsV1.
Remote and browser readers that stay open on generation 1 keep reading a consistent, stale stream until you retire it. Retiring with streams: "close" lets open readers reach the stream end and observe the close; retiring with streams: "remove" causes subsequent reads to fail with a missing stream.
Roll back before retirement
Keep the old generation’s checkpoint record, operator state, and output streams until you finish the cutover.
To roll back:
- Stop runners for the new generation.
- Resume runners for the older generation.
The older generation continues from its saved checkpoint and writes to its own stream address without touching the newer generation's stream.
Because old and new operator state and output streams coexist until retirement, storage roughly doubles while two generations remain active. Retire superseded generations once you no longer need rollback.
Forget versus retire
Stop and drain all runners for a binding before calling either Projection.forget or Projection.retire. A runner that was already running or pinned before retirement can still append to an open stream.
| Operation | Checkpoint | Operator state | Owned output streams | Route records | Later run of same generation |
|---|---|---|---|---|---|
Projection.forget(bound) | Deleted. A tombstone stays. | Cleared in the owner transaction | Kept | Marked forgotten. Tombstoned bindings keep their records as they are. | An exclusive output that fails the empty-and-open check gives invalid-output. |
Projection.retire(circuit, params, { generation }) | Fenced by a tombstone, even if the checkpoint cannot be decoded | Cleared in the owner transaction | Removed or closed | Cleared on removal and kept on close | Fails at load with retired-generation. |
Forget
Pass the bound declaration from circuit.at(params) so forget can mark its route records. Retirement can still find those streams. If cleanup fails, the owner transaction rolls back. Raise generation to replay into fresh streams. Forget
Retire
Projection.retire(declaration, params, { generation }) retires one binding of an older generation in a single transaction on the checkpoint owner.
export const smoke = Effect.gen(function* () {
// ...
// Each run above has finished, so generation 1 has no active runner.
const retirement = yield* Projection.retire(rebuilt, params, { generation: initial.generation });
const missing = yield* output
.head({ ...params, generation: initial.generation })
.pipe(Effect.flip);
const refused = yield* Projection.run(initial).pipe(Effect.flip);
// ...
}).pipe(Effect.provide(host));The transaction writes the checkpoint tombstone, clears the binding’s operator state, and removes every exclusively owned wrapped output stream. Pass streams: "close" to close the streams and keep their data. If the owner transaction aborts, the tombstone, operator cleanup, and output changes roll back together.
- A successful repeat of
Projection.retirereportsrecord: "already-retired". streamsreports{ output, id, result }for the wrapped streams, sorted by output name and then stream id in code-unit order.- In scenario 2, pass the old declaration (
shopViewsV1) so retirement targets the old circuit's id and route templates. - Retirement operates on one binding at a time, so callers supply the binding
params. - If a
StateTableindexed the retired stream, stop its runner and clear its cached rows separately withStateTable.clear(table). See Clear a retired stream's rows and Retire a generation.
Operator state cleanup by backend
Both operations clear the same state for the binding. The backend decides how to clear it.
| Backend | Cleanup |
|---|---|
| SQLite | Deletes the binding’s rows from the five Views tables by namespace. The tables stay in place. |
| Postgres and MySQL | Deletes the binding’s rows from the five state tables by namespace digest. The streamsy_view_layout table and its version row stay in place. |
| Memory | Removes the namespace and its state from the heap. A retirement tombstone also lives in memory and disappears when the host is discarded. |
Cascade to downstream circuits
When a downstream circuit reads an upstream circuit's generation-addressed output stream, pin the upstream generation in the input State route used by the downstream circuit.
Because a projection checkpoint records each input's stream id, repinning a downstream circuit to upstream generation 2 while keeping the downstream circuit at generation 1 fails at load with identity-mismatch. Raise the downstream circuit's generation at the same time so it replays from the start of the new upstream stream into its own new output stream:
import { Schema } from "effect";
import { Streamsy } from "@streamsy/core";
import { Projection } from "@streamsy/projection";
import { View } from "@streamsy/views";
import { Orders, ShopViews } from "./streams.ts";
const pinnedShopViews = (generation: number) =>
Streamsy.state<ShopViews>()("ViewsShop/Views", `shop/:shopId/views/g/${generation}`, {
params: Orders.paramCodecs,
collections: ShopViews.collections,
});
class HighValueTotals extends Streamsy.state<HighValueTotals>()(
"ViewsShop/HighValueTotals",
"shop/:shopId/high-value/g/:generation",
{
params: { shopId: Schema.String, generation: Schema.FiniteFromString },
collections: { customerTotals: ShopViews.collections.customerTotals },
},
) {}
export const downstreamCircuit = (upstreamGeneration: number, generation: number) =>
View.circuit({
id: "high-value-totals",
generation,
params: Orders.paramCodecs,
output: Projection.perGeneration(HighValueTotals, "generation"),
views: {
customerTotals: View.from(pinnedShopViews(upstreamGeneration), "customerTotals").where(
(row) => row.revenue.gte(100),
),
},
});When upstream moves from generation 1 to generation 2, move downstream from downstreamCircuit(1, 1) to downstreamCircuit(2, 2).