Repository navigation
fix(cli): materialize CSV redirects into the KV decofile snapshot - #548
Merged
Merged
Conversation
This was referenced Sep 14, 2026
`readDecofileFromDir` promises a decofile "byte-identical to the bundled
blocks.gen snapshot", but `generate-blocks` also injects synthetic
`__csv_redirects__*` blocks via `buildCsvRedirectBlocks` and the KV writers
did not. So `decofile:<sha>` never carried CSV-backed redirects.
Today that is masked: the bundled snapshot is still resident, so the
redirects resolve from memory. The moment the bundle stops being the
fallback — `decoVitePlugin({ fastDeploy })` stubs it to `{}` — every
CSV-backed redirect disappears and bulk-migration 301s turn into silent
404s. Sites with tens of thousands of rules are exactly the ones that opt
into fast-deploy for the memory win.
Fixed in `readDecofileFromDir` rather than in each caller, so both
`sync-blocks-to-kv` and `migrate-blocks-to-kv` are covered and the stated
byte-identical invariant actually holds. Same precedence as the generator:
a curated CMS redirect wins over a CSV row.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
JonasJesus42
force-pushed
the
fix/csv-redirects-kv-snapshot
branch
from
September 29, 2026 17:43
82e78d0 to
6894ca7
Compare
JonasJesus42
added a commit
that referenced
this pull request
Sep 29, 2026
Substitui a decisão que eu tinha tomado errado no #548 ("uma cópia só dentro do snapshot é o ganho inteiro"). Aquilo só valeria se a chave fosse *uma lista*. Com **uma chave por rota**, a lista nunca entra em memória — que é onde está o ganho de verdade num site cujo decofile é majoritariamente redirect. ## Problema Dezenas de milhares de regras dentro do decofile ficam residentes **duas vezes** em cada isolate: no grafo do snapshot parseado, e no `RedirectMap` construído a partir dele. Megabytes de um orçamento de 128 MB por isolate sem botão de GC, para uma tabela de lookup consultada no máximo uma vez por request e que quase sempre não casa com nada. ## Mudança Cada regra **exata** sai do decofile e vira uma chave `redirect:<deployment-id>:<path>`. O request consulta só o path pedido. **Glob fica no decofile.** `/old/*` precisa ser varrido em ordem contra o path — nunca vira lookup por chave. São dezenas, não milhares. Chaveado por deployment id como todo o resto do fast-deploy: rollback continua coerente (código velho lê o conteúdo dele), o isolamento entre deploys se mantém, e o GC já existente prunes junto. ## Três coisas load-bearing e não-óbvias 1. **A ordem é exato → KV → glob**, não "matchRedirect e depois KV". Senão um glob ganha de uma regra exata e a precedência inverte. Por isso `matchRedirect` virou `matchExactRedirect` + `matchPatternRedirect` (compostos, sem mudança de comportamento). 2. **`<path>` é `normalizePath(from)` nos dois lados.** `normalizePath` passou a ser exportado exatamente porque é o contrato da chave — uma segunda normalização em qualquer ponta grava a regra numa chave que ninguém pergunta. 3. **Edição de redirect propaga por TTL de 60s no isolate, não pelo poll de revisão.** As regras estão fora do decofile agora, então um sync só-de-redirect deixa o snapshot byte-idêntico e `index:revision:<id>` não mexe. Se esse atraso um dia precisar ser ~zero, o caminho é uma chave `index:redirects-revision:<id>` polada junto — **não** um TTL menor, que só multiplica leitura de KV. Está comentado no código e no doc. ## Add / update / remove Reconciliado contra um `LIST` por prefixo, não contra uma chave de manifesto: o KV não tem "substitua tudo sob este prefixo", e manifesto é mais uma coisa que pode divergir da realidade. Update não é detectado por valor — reescrever tudo é um bulk write, ler cada valor de volta pra comparar seria um GET por chave. Só o delete precisa do diff. GC apaga as chaves de redirect do deployment prunado, senão cada deploy vaza dezenas de milhares de órfãos. `putMany`/`deleteMany` no cliente REST (bulk, 10k por request) porque um request por chave não é forma que sobrevive a 18k regras. Todo modo de falha resolve pra "sem redirect", nunca throw: queda de KV não pode 5xxar uma página que renderizaria normal. ## Testes 21 casos novos. Cobrem o round-trip do split (nada matchável se perde), a precedência exato-em-KV sobre glob-em-memória, cache de HIT **e** de MISS (o miss é o caso comum de todo request), re-leitura após TTL, inércia com fast-deploy desligado, recusa a ler chave de outro deployment, e KV fora do ar / valor malformado. Depende de #548 (os redirects de CSV precisam estar no que o sync lê antes de serem extraídos). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Moves exact redirect rules out of the decofile into one KV key per rule (`redirect:<id>:<path>`), so a site with tens of thousands of redirects no longer holds the full list resident in every isolate. Only the requested path is looked up per request; glob rules stay in the decofile since they must be scanned in order. CSV-backed redirects are now materialized into the KV snapshot so they survive once the bundled fallback snapshot stops being resident. **Behavior** - Matching order is now exact (memory) → KV → glob; `matchRedirect` is split into `matchExactRedirect` and `matchPatternRedirect` so a glob never beats an exact rule. - `normalizePath` is now exported as the key contract; the writer and request-time reader must produce identical bytes. - Redirect edits propagate on a 60s TTL cache (hits and misses), not the revision poll, since redirect-only syncs leave the snapshot byte-identical. - Sync reconciles against a prefix `LIST` using new bulk put/delete on the KV REST client (10k per request); GC prunes a deployment's redirect keys alongside its snapshot. - Every KV failure resolves to "no redirect", never a throw. - `readDecofileFromDir` injects synthetic `__csv_redirects__*` blocks like `generate-blocks` does, so CSV redirects reach the KV snapshot; a curated CMS block still wins on key collision. **Migration** - `sync-blocks-to-kv` and `migrate-blocks-to-kv` both split exact rules before building the snapshot so a one-shot seed and CI sync stay consistent. <sup>Written for commit 3dcbe26. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/553?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --- **Stacked on #548** (merge #548 first): without it CSV rows never reach the KV snapshot, so they'd never be split. This branch contains #548's commit; the extra diff goes away once #548 lands. Review follow-ups folded in: KvRestClient mock gains `putMany`/`deleteMany` (TS2739), paths over 400 bytes stay in memory (KV keys cap at 512 bytes; an over-long `from` would otherwise fail the bulk PUT and block the deploy), and a test proving CSV-derived exact rules are split out of the snapshot. Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
JonasJesus42
added a commit
that referenced
this pull request
Sep 29, 2026
…#549) ## Contexto O stub de `blocks.gen` no bundle servidor é a correção para o decofile ficar **três vezes** residente por isolate: 1. o grafo `JSON.parse(...)` bundlado, mantido vivo pelo binding `import { blocks } from ".deco/blocks.gen"` pela vida inteira do isolate; 2. o grafo que `setBlocks()` aloca a partir do KV; 3. a string JSON escapada no bundle SSR. Medido em **+13.6 MB e +13.4 MB para um decofile de 9.2 MB**, contra um teto de 128 MB por isolate na Cloudflare — onde não existe `--max-old-space-size` nem nenhum outro botão: a única correção é parar de alocar. Ele shipou opt-in (#542) e **nada opta**: nem o scaffold de migração, nem o `deco-sites/storefront-tanstack`, nem site nenhum. `grep fastDeploy` acha a opção só no plugin e nos testes. ## Por que opt-in era a forma errada O stub só é perigoso quando a pipeline de deploy **não** semeia `decofile:<deployment-id>` antes de ativar a versão nova — aí não há conteúdo e `ensureBlocksHydrated` dá 5xx de propósito (melhor que servir site vazio com 200 e o edge cachear). Isso é propriedade **da pipeline**, não do site. Pedir para cada site declarar garante que algum declare errado, na direção que derruba. ## Mudança `fastDeploy` passa a default `"auto"`: stuba só quando a pipeline seta `DECO_SEEDED_DEPLOY`. O `cfworkers-builder` seta sob exatamente a condição que já guarda o `seedContentToKV`, então stub e seed não podem divergir (PR companion em `decocms/infra_applications`). - Cloudflare Workers Builds / `wrangler deploy` manual → nunca setam → snapshot bundlado, comportamento byte-idêntico ao de hoje. - Build pela infra própria → ganha a memória de volta no próximo deploy, **sem nenhum site mudar nada**. - `true`/`false` continuam forçando. ## Testes 6 casos novos: default sem a env não stuba (e `__DECO_BLOCKS_STUBBED__` fica `"false"`); com a env em `build` stuba; `vite dev` nunca stuba nem dentro de pipeline que semeia; `false` ganha de pipeline que semeia; `true` ganha de pipeline que não semeia. Os testes existentes ganharam um `stubEnv` explícito para não poderem ser satisfeitos por env ambiente. Depende de #548 (redirects de CSV no snapshot de KV) — sem ele, stubar o bundle apaga os redirects vindos de CSV. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Defaults the `blocks.gen` server stub to `"auto"` in the tanstack Vite plugin, so sites on our build pipeline drop two extra in-memory copies of the decofile without any site-side change. A stubbed bundle now also fails loudly when fast-deploy is off at runtime, instead of serving `{}` with a 200 the edge would cache. - The plugin stubs only when `DECO_SEEDED_DEPLOY` is set; Cloudflare Workers Builds and manual `wrangler deploy` keep the bundled snapshot, byte-identical to today. - Explicit `true`/`false` still force either way. - A stubbed bundle needs `DECO_FAST_DEPLOY=1` and a `DECO_KV` binding at runtime; without them every request fails rather than serving an empty site. - Depends on #548, otherwise stubbing the bundle drops CSV redirects from the KV snapshot. <sup>Written for commit 60d43ba. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/549?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --- **Merge after #548** — once stubbed, CSV redirects only exist if the KV snapshot carries them. The companion infra PR must set `DECO_SEEDED_DEPLOY` only where the runtime also has `DECO_FAST_DEPLOY=1` + `DECO_KV`; a stubbed bundle without them now 5xxs on purpose instead of serving an empty site. --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
JonasJesus42
added a commit
that referenced
this pull request
Sep 29, 2026
## Problema Um site migrado não conseguia usar fast-deploy sem edição manual: - `generateWranglerConfig` emitia um `wrangler.jsonc` **sem `vars`**, sem observabilidade, e com um único binding KV: `SITES_KV` com o id literal `"dev-sites-kv"` — que não resolve em ambiente nenhum. - O `setup.ts` scaffoldado nunca chamava `setupTanstackFastDeploy()`, então mesmo com o wrangler corrigido na mão o write-through do publish do Studio no-opava em silêncio (o `blocks-admin` não pode importar o `@decocms/tanstack` — direção errada no grafo de pacotes — então quem entrega o resolver de KV é o site). ## Mudanças - **`wrangler.jsonc`** declara `DECO_KV` e `DECO_FAST_DEPLOY: "1"` juntos, mais `version_metadata` e `tail_consumers: deco-otel-tail`. O tail consumer não é enfeite: a Cloudflare mata o isolate acima do teto de 128 MB **antes** de qualquer código in-worker conseguir reportar, então sem ele um `exceededMemory` é invisível (`docs/runbooks/tail-exception-spike.md`). Emitido como JSONC de verdade em vez de `JSON.stringify`, pra os porquês ficarem ao lado dos campos. - **Ids de namespace ficam vazios de propósito.** O control-plane provisiona os namespaces próprios do site (`ensureSiteKvNamespace`) e o builder re-força os ids a cada build via `CF_KV_NAMESPACE_ID`, então id errado no repo nunca chega em produção — e um id falso com cara de real é pior que um branco. - **`setup.ts`** chama `setupTanstackFastDeploy()`, espelhando `examples/tanstack-smoke`. - **Check novo no `phase-verify`**, severidade `error`, exigindo os três juntos. Dois de três é o pior estado possível: parece configurado, o publish reporta sucesso, e nada chega no KV. ## Testes `fast-deploy-scaffold.test.ts` — 8 casos. O wrangler gerado é **parseado**, não grepado (um vírgula solta desliga fast-deploy em todo lugar de uma vez: builder, control-plane e o próprio check lêem esse arquivo por um parser JSONC). O check de verify é exercitado nos quatro estados parciais. Parte da pilha: #548 → #549 → este. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Makes migrated sites fast-deploy-ready without hand edits. Previously the scaffolded `wrangler.jsonc` had no `vars`, no observability, and a `SITES_KV` binding with an unresolvable id, and `setup.ts` never called `setupTanstackFastDeploy()`, so Studio publishes silently no-opped. - The generated `wrangler.jsonc` now declares `DECO_KV` and `DECO_FAST_DEPLOY: "1"` together, plus `version_metadata` and a `deco-otel-tail` tail consumer; it's emitted as JSONC so the comments explaining each field survive. - Namespace ids stay empty on purpose: the control-plane provisions the site's own namespaces and re-forces the ids on every build, so a wrong id in the repo can never reach production. - `SITES_KV` is gone entirely — nothing provisions it, and `withABTesting` passes through when unbound. - `setup.ts` calls `setupTanstackFastDeploy()`, handing the KV resolver to `@decocms/blocks-admin`, which can't import `@decocms/tanstack` itself. - A `phase-verify` check (severity `error`) requires all three pieces together, since two of three looks configured but writes nothing to KV. - The scaffold tests parse the generated JSONC rather than grep it, covering the partial-config failure states. <sup>Written for commit 45de820. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/550?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --- Closes #486 (DECO_KV id filled by control-plane/D7; the unprovisioned `SITES_KV` binding is dropped). Refs #485 (separate fix: the setup template passes admin options to `createSiteSetup`). --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
JonasJesus42
added a commit
that referenced
this pull request
Sep 29, 2026
…D7) (#551) ## Problema Um site migrado saía **não-deployável**. A pipeline era wiring manual, um clique no dashboard da Cloudflare por worker (D6.3), e nada dava ao site o namespace de KV que o fast-deploy precisa. ## D7 — deploy passa para o control-plane Registro D7 (neste PR, em `MIGRATION_TOOLING_PLAN.md` + a regra always-loaded) — é o "follow-up D-record once shipped" que o D6.3 prometeu. O Cloudflare Workers Builds sai; entra `decocms/control-plane` (`SITE_CREATE` → repo, admin `sites`, org ownership, KV/R2/D1 próprios do site, env de produção, Deco CR) + operator + `cfworkers-builder`. Três coisas que o CF Builds estruturalmente não dava: 1. **Isolamento de KV por site.** `index:live` é uma chave por namespace — dois sites dividindo um se atropelam. `ensureSiteKvNamespace` cria `deco-kv-<site>` e o builder re-força o id do `DECO_KV` a partir de `CF_KV_NAMESPACE_ID` a cada build, então repo de tenant não consegue bindar KV de outro site. 2. **Seed antes de ativar.** O builder semeia `decofile:<sha>` antes do `wrangler deploy` e vira `index:live` depois — código novo nunca lê conteúdo velho. Essa ordem é exatamente o que torna seguro stubar o `blocks.gen` do bundle servidor (#549), o corte de memória. Site no CF Builds **nunca** consegue esse ganho. 3. Zero clique por worker, e o builder tira `routes`/`account_id` controlados pelo tenant. **Inalterado do D6.3:** storefront continua **sem** `deploy.yml`/`preview.yml`/`sync-secrets.yml` scaffoldados — a pipeline é do control-plane, não do repo do site. ## Mudanças - `provisionSite` no `migrate.ts`, logo após o bootstrap: `tools/call SITE_CREATE` no `/mcp`, grava o `kvNamespaceId` retornado no `wrangler.jsonc`. **Inerte sem `DECO_CONTROL_PLANE_TOKEN` + `DECO_ORG`** — imprime a chamada equivalente e segue, mesmo padrão do `provisionAnalytics`. Migração não pode falhar porque alguém rodou sem token, e o id nem é load-bearing (o builder re-força a cada build). - `setKvNamespaceIdInJsonc` em `lib/wrangler-config.ts`, ao lado do leitor. Edita como texto em vez de parse-and-restringify, porque o `wrangler.jsonc` scaffoldado carrega os comentários explicando por que cada binding existe. - **Bonus fix:** `provisionAnalytics` interpolava `package.json.name` direto numa string SQL enviada à Supabase Management API. Essa API não aceita bind parameters, então a correção honesta é recusar o que não for um slug de site. - `--help` documenta as env vars novas. ## Testes 5 casos para `setKvNamespaceIdInJsonc`: escreve o id preservando comentários, não encosta em outro binding, aceita `binding`/`id` em qualquer ordem e entrada sem `id`, e devolve a fonte intacta quando o binding não existe (não é erro — o builder re-força mesmo assim). Pilha: #548 → #549 (+ infra#333) → #550 → este. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Migrated sites previously required manual Cloudflare wiring and lacked the KV namespace needed for fast deploys. Migration now calls the control plane's `SITE_CREATE` tool to provision deployment resources and writes the site's KV namespace ID to `wrangler.jsonc`; storefront repos still receive no deploy workflow scaffolding. - The provisioning step is enabled by `DECO_CONTROL_PLANE_TOKEN` and `DECO_ORG`; without them, migration prints an equivalent `curl` command and continues. - The `SITE_CREATE` call times out after 30 seconds so a stalled control-plane can't block the migration. - The config update preserves JSONC comments and leaves unrelated KV bindings unchanged. - Analytics provisioning now rejects site names that are not valid slugs before interpolating them into SQL. - Adds coverage for KV config updates, including reversed fields, missing IDs, and absent bindings. <sup>Written for commit 9804336. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/551?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --- Refs #486. Supersedes #431: the builder strips tenant-supplied `account_id`/`routes`, so the scaffold shouldn't pin one. --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
JonasJesus42
added a commit
that referenced
this pull request
Sep 29, 2026
Quatro coisas em circulação estavam erradas ou desatualizadas. **1. As chaves de KV.** `CLAUDE.md` dizia `decofile:current` + `index:revision`. Nenhuma das duas existe. As chaves são **por deployment id**: `decofile:<id>`, `index:revision:<id>`, `index:live`, `index:deployments` (`packages/blocks/src/cms/blockSource.ts:113-145`). E isso não é cosmético — um ponteiro único mutável entregaria conteúdo novo para código velho ainda no ar durante um rolling deploy. **2. `wrangler.toml`.** O `docs/fast-deploy.md` documentava a config em toml. O tooling lê e escreve `wrangler.jsonc`; nada emite toml (o parser toml existe só para repos legados). **3. "O snapshot bundlado é o fallback de KV".** No modo bundle-stub não é — `ensureBlocksHydrated` falha alto em vez de servir um site vazio que o edge cacharia. Esse modo, os números de memória por trás dele (três cópias do decofile por isolate, ~27 MB para um decofile de 9.2 MB contra teto de 128 MB sem botão de GC) e o porquê de ser gated na pipeline declarar que semeia agora têm seção própria. **4. `loadRedirects` module-level.** Listado como limitação não-fast-deployável; o `workerEntry.ts:2082-2097` já rechaveia o mapa de redirects por revisão. Só vale para código de site que iça o próprio `loadRedirects(loadBlocks())`. De quebra: os pré-requisitos de site agora apontam para a automação que passou a cobri-los (`SITE_CREATE` + o scaffold de migração, D7), e o requisito de chamar `setupTanstackFastDeploy()` — que não estava documentado em lugar nenhum e é a diferença entre um publish funcionar e escrever nada em silêncio. Fecha a pilha: #548 → #549 (+ infra#333) → #550 → #551 → este. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Corrects the fast-deploy docs in `CLAUDE.md` and `docs/fast-deploy.md` to match the actual tooling contract. - KV keys are per deployment id (`decofile:<id>`, `index:revision:<id>`, `index:live`, `index:deployments`), never a single mutable pointer that would feed new content to old code mid-rollout. - The config is `wrangler.jsonc`; nothing emits toml, though it is still parsed for legacy repos. - Bundle-stub mode removes the bundled snapshot fallback — `ensureBlocksHydrated` fails loudly rather than serving an empty site, and the mode is gated on the pipeline declaring it seeds the KV key before activation. - The module-level `loadRedirects` limitation no longer applies to the framework's own redirects; it only affects site code that hoists its own `loadRedirects(loadBlocks())`. - Site prerequisites now point at the automation that provisions them, and the previously undocumented `setupTanstackFastDeploy()` call is recorded as required. Merge after #550 and #551 — the prerequisites section references D7, `SITE_CREATE`, and the scaffolded `setupTanstackFastDeploy()` call. <sup>Written for commit 7bfb8b1. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/552?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --- **Merge after #550 and #551** — the prerequisites section references D7, `SITE_CREATE` and the scaffolded `setupTanstackFastDeploy()` call, which only exist once those land. Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problema
readDecofileFromDirdiz produzir um decofile "byte-identical to the bundledblocks.gensnapshot". Não produz:generate-blocksinjeta blocos sintéticos__csv_redirects__*viabuildCsvRedirectBlocks(scripts/generate-blocks.ts:183,288) e os escritores de KV liam os.deco/blocks/*.jsoncrus. Logodecofile:<sha>nunca teve os redirects vindos de CSV.Hoje isso está mascarado — o
blocks.genbundlado continua residente e os redirects resolvem da memória. No momento em que o bundle deixa de ser o fallback (decoVitePlugin({ fastDeploy })stuba pra{}), todo redirect de CSV some e os 301 de migração viram 404 silencioso. Justamente os sites com dezenas de milhares de regras são os que optam por fast-deploy pelo ganho de memória.Correção
Uma chamada a
buildCsvRedirectBlocksdentro dereadDecofileFromDir, não em cada caller — assimsync-blocks-to-kvemigrate-blocks-to-kvficam cobertos de uma vez e a invariante declarada passa a valer de fato. Mesma precedência do gerador ({ ...csv, ...blocks }): redirect curado no CMS ganha de linha de CSV.Testes
3 casos novos em
fast-deploy-kv.test.ts: loader de CSV aninhado emsite.routes[](a forma que quebrou em produção — invisível paraloadRedirects, que só varre o topo), colisão de chave com bloco real, e no-op quando não há CSV. O primeiro falha sem a correção.Primeiro de uma pilha; pré-requisito para ligar o stub do
blocks.gen.🤖 Generated with Claude Code
Summary by cubic
Fixes
readDecofileFromDirso the KV decofile snapshot includes CSV-backed__csv_redirects__*blocks, matching the bundledblocks.gensnapshot. Previously those redirects were missing, so fast-deploy sites lost them once the bundled snapshot stopped being the fallback, turning migration 301s into silent 404s.Notes
sync-blocks-to-kvandmigrate-blocks-to-kvare covered.Written for commit 6894ca7. Summary will update on new commits.