09
Datos y sistemas distribuidos

Los datos como decisión de arquitectura

Datos y sistemas distribuidos

Semana 9 — Los datos como decisión de arquitectura

Objetivos

  • Explicar por qué los datos son la parte de una arquitectura que más cuesta cambiar, y plantear las decisiones sobre datos como trade-offs: transaccional o analítico, un nodo o muchos, servicio administrado o propio.
  • Elegir un modelo de datos (relacional, de documentos, de grafos, clave-valor) según los patrones de acceso de un sistema, y decir qué se paga por usar más de uno.
  • Distinguir compatibilidad hacia atrás y hacia adelante en un formato o en un contrato, y decidir si un cambio es compatible.
  • Cambiar un esquema o un contrato que otros usan sin romperlos, con la secuencia expandir, migrar y contraer.

Sesión A — Trade-offs en los sistemas de datos: transaccional y analítico, un nodo y muchos

Lecturas:

  • Kleppmann y Riccomini, Designing Data-Intensive Applications (2.ª ed.), cap. 1 Trade-Offs in Data Systems Architecture y cap. 2 Defining Nonfunctional Requirements (el caso de las líneas de tiempo de una red social y la sección Scalability).
  • Lectura libre: Martin Kleppmann, apuntes del curso Concurrent and Distributed Systems de Cambridge, sección 1, Introduction.

Lecturas complementarias:

  • Martin Fowler, PolyglotPersistence.
  • Software Architecture in Practice, cap. 17 The Cloud and Distributed Computing.

Temas:

  • Por qué la segunda mitad del curso es sobre datos: el código sin estado se reemplaza, se copia y se escala con facilidad; los datos no. Las decisiones sobre dónde viven, cuántas copias hay y quién puede escribirlos son las que más cuesta deshacer.
  • Sistema intensivo en datos: su dificultad está en la cantidad, la complejidad o la velocidad de cambio de los datos, no en el cómputo. Se arma con piezas estándar (bases de datos, caches, índices de búsqueda, colas, procesos por lotes); la arquitectura es cómo se combinan y qué garantías sobreviven a la combinación.
  • Transaccional (OLTP) y analítico (OLAP). Transaccional: muchas operaciones pequeñas, por clave, de usuarios que esperan; importa la latencia y la exactitud. Analítico: pocas consultas grandes que recorren millones de filas; importa el throughput. Usar la misma base de datos para los dos hace que el reporte del mes compita con la venta. Las respuestas, de menos a más costo: una réplica para lecturas pesadas, un data warehouse cargado por lotes o por streams.
  • Sistema de registro y datos derivados: una sola fuente de verdad para cada dato; lo demás (caches, índices, vistas materializadas, reportes) se puede reconstruir a partir de ella. Saber cuál es cuál decide qué se puede perder.
  • Un nodo o muchos. Razones para distribuir: tolerar la falla de una máquina, escalar más allá de una, acercar los datos a los usuarios. Lo que cuesta: fallas parciales, retraso de replicación, relojes que no coinciden, y que lo que era una transacción pase a ser un protocolo. Una sola máquina aguanta hoy mucho más de lo que se suele suponer, y es más simple de razonar.
  • Servicio administrado o propio: se paga para no operar, y se pierde control y portabilidad. Es una decisión de arquitectura porque fija qué garantías se pueden pedir y cuánto cuesta salir.
  • Escalabilidad no es una propiedad, es una pregunta: si la carga crece de esta manera, ¿qué opciones hay? Primero describir la carga con sus parámetros (lecturas y escrituras por segundo, proporción entre ellas, tamaño de los datos, el caso extremo). En Tinkuy: miles de lecturas del catálogo por cada compra, y un pico de escrituras el minuto en que se abre una venta.
  • El caso del capítulo 2: las líneas de tiempo de una red social. Calcular al leer o al escribir; cómo un usuario con millones de seguidores rompe la opción que servía para los demás. La misma decisión, en pequeño, aparece en Tinkuy con la disponibilidad de un evento: contarla en cada lectura o mantenerla al vender.
  • Error común: diseñar para una escala que no existe. Cada componente distribuido que se agrega “por si crece” es operación y modos de falla desde hoy.

Sesión B — Modelos de datos, formatos y evolución de esquemas y contratos

Lecturas:

  • Designing Data-Intensive Applications (2.ª ed.), cap. 3 Data Models and Query Languages (las secciones sobre el modelo relacional y el de documentos) y cap. 5 Encoding and Evolution.
  • Lectura libre: Danilo Sato, ParallelChange (expandir y contraer), y Martin Fowler, TolerantReader.

Lecturas complementarias:

  • Designing Data-Intensive Applications (2.ª ed.), cap. 4 Storage and Retrieval: cómo guarda y busca una base de datos, y por qué las transaccionales y las analíticas lo hacen distinto.
  • Hyrum’s Law.
  • Protocol Buffers, Language Guide, la sección sobre cómo actualizar un tipo de mensaje.

Temas:

  • El modelo de datos decide qué preguntas son fáciles. Relacional: relaciones de muchos a muchos, JOIN, restricciones y transacciones. De documentos: un agregado que se lee y se escribe entero, esquema flexible, mala para relaciones entre documentos. De grafos: cuando las relaciones son los datos. Clave-valor: acceso por clave y nada más, a cambio de escala y velocidad. No se elige por moda: se elige por los patrones de acceso.
  • Esquema al escribir y esquema al leer: “sin esquema” significa que el esquema está en el código que lee, sin nadie que lo haga cumplir.
  • Persistencia políglota: una base de datos por necesidad (PostgreSQL para las órdenes, Redis para la cache, un índice de búsqueda para el catálogo). Lo que se gana en ajuste se paga en operación y en mantener las copias de acuerdo, porque ya no hay una transacción que las cubra.
  • El modelo de datos como interfaz: si otro módulo o servicio lee las tablas, el esquema es un contrato público. De ahí la regla del modular monolith (semana 4) y de los microservicios (semana 5): cada uno es owner de sus datos.
  • Por qué la evolución es un problema de arquitectura: en un sistema que no se detiene, la versión vieja y la nueva del código conviven (un despliegue gradual, un cliente móvil que no se actualiza, un mensaje que quedó en una cola). Los datos viven más que el código que los escribió.
  • Compatibilidad hacia atrás: el código nuevo lee datos escritos por el viejo. Hacia adelante: el código viejo lee datos escritos por el nuevo; es la difícil, porque exige que el código viejo ignore lo que no conoce sin destruirlo.
  • Formatos: JSON (legible, sin esquema obligatorio, ambiguo con los números), y los binarios con esquema (Protocol Buffers, Avro), donde los campos se identifican con etiquetas o por resolución de esquemas, y las reglas de evolución son explícitas: agregar un campo opcional es compatible; quitar uno obligatorio, renombrarlo o cambiarle el tipo no lo es.
  • Evolución de una API: cambios compatibles (agregar un campo opcional a la respuesta, un endpoint nuevo) e incompatibles (quitar o renombrar un campo, cambiar un tipo o un significado, volver obligatorio lo opcional). Lector tolerante: quien consume ignora lo que no conoce. Ley de Hyrum: con suficientes usuarios, alguien depende de cada comportamiento observable, esté o no en el contrato.
  • Expandir, migrar y contraer: para cambiar un esquema o un contrato sin detener nada. Expandir: agregar lo nuevo junto a lo viejo (la columna nueva, el campo nuevo) y escribir en ambos. Migrar: copiar los datos y mover a quienes leen, uno por uno. Contraer: cuando nadie usa lo viejo, quitarlo. Expandir y migrar son despliegues que se pueden revertir; contraer no, y por eso va al final y sin apuro.
  • En Tinkuy: buyer_name pasa a ser nombre y apellido; total_cents pasa a llevar moneda (un cambio que cabe en el formato y aun así cambia el significado del número para quien no lee el campo nuevo). Con el reporte y un cliente antiguo leyendo, ninguno de los dos cambios se puede hacer en un paso.
  • Error común: renombrar una columna o un campo en un solo despliegue. Durante los minutos que dura, la mitad del sistema lee un nombre que ya no existe.
  • Error común: versionar la API (/v2) para cada cambio. La mayoría de los cambios se pueden hacer compatibles, y cada versión viva es código que hay que mantener.

Laboratorio — Cambiar un contrato sin romper a quien lo usa

Referencias: Sato, ParallelChange; Designing Data-Intensive Applications, cap. 5. Material: code/week-09/. En parejas.

  1. El caso de code/week-09/: un servicio de órdenes (orders-v1), su base de datos, y dos consumidores que no controlan: un cliente móvil antiguo y un proceso de reportes que lee la tabla directamente. Correr make y make test: todo pasa.
  2. El cambio pedido: separar buyer_name en given_name y family_name, y agregar currency a los montos. Clasificar cada parte del cambio como compatible hacia atrás, hacia adelante, ambas o ninguna, para la API y para la tabla.
  3. Hacerlo mal a propósito: aplicar errors/rename-in-one-step.sql y correr las pruebas de los consumidores. Anotar qué se rompe y con qué mensaje. Deshacer.
  4. Expandir: agregar las columnas y los campos nuevos sin quitar los viejos; el servicio escribe en ambos. Correr las pruebas de los dos consumidores: deben pasar sin haberlos tocado.
  5. Migrar: llenar las columnas nuevas de las filas antiguas con el script por lotes de la carpeta (no con un UPDATE de toda la tabla; medir con el script de la carpeta cuánto esperan las lecturas y las escrituras de los demás con cada forma). Mover el proceso de reportes a los campos nuevos.
  6. El cliente móvil antiguo no se puede actualizar. Decidir cuánto tiempo se mantiene el campo viejo y cómo se sabría que ya nadie lo usa. El servicio no puede ver qué campos de la respuesta lee un cliente, así que hace falta un indicio: agregar un contador de las peticiones que no declaran usar el contrato nuevo (con una cabecera, por ejemplo).
  7. Contraer: la tabla y la API son dos contratos distintos. La columna vieja se puede quitar cuando ya nadie la lee con SQL (el reporte ya se movió); el campo viejo de la API, cuando el contador llegue a cero (en el laboratorio, apagando el cliente antiguo). Correr todo. ¿Cuál de los pasos anteriores se podía deshacer y cuál no?
  8. Compatibilidad hacia adelante: enviarle al servicio viejo (orders-v1, sin modificar) una orden escrita por el nuevo. ¿La acepta? ¿Qué pasa con los campos que no conoce, como currency, al guardarla y al devolverla? Explicar por qué importa durante un despliegue gradual.

Entregas

Sin entregas esta semana. P3 se entrega en la semana 11.

Preguntas de repaso

  1. Den dos razones por las que una consulta analítica no debería correr en la base de datos transaccional, y dos formas de separarlas con su costo.
  2. Clasifiquen como sistema de registro o dato derivado: la tabla de órdenes, la cache del catálogo, el índice de búsqueda, el reporte de ventas. ¿Qué pasa si se pierde cada uno?
  3. Un cambio agrega un campo obligatorio a la petición de una API. ¿Es compatible hacia atrás? ¿Y si el campo se agrega a la respuesta?
  4. ¿Por qué la compatibilidad hacia adelante importa durante un despliegue gradual, aunque todos los clientes sean del mismo equipo?
  5. Escriban los pasos para cambiar el tipo de una columna de integer a bigint en una tabla que recibe escrituras todo el día.
  6. Enuncien la ley de Hyrum y den un ejemplo con el orden de los elementos de una respuesta JSON.

Código de la semana

Compilar y probar dentro del contenedor del curso con make y make test.

Ejemplos (29)Errores (4)Pruebas (9)Laboratorio (8)Compilación (3)

Ejemplos

Los programas que usan los apuntes y la clase.

consumers/mobile-client.tsDescargar consumers/mobile-client.ts
// El cliente móvil antiguo, versión 1.4. Está instalado en los celulares de
// quienes no actualizan la aplicación: nadie del equipo puede cambiarlo.
// Aquí es un script, pero hace lo mismo que la aplicación: crea una orden y
// arma la pantalla "Mi compra" a partir de lo que responde el servicio.
//
// NO SE MODIFICA en el laboratorio: representa código que ya no controlamos.
//
//   node consumers/mobile-client.ts show 1
//   node consumers/mobile-client.ts buy rosa.quispe@correo.pe "Rosa Quispe" 32000

const USER_AGENT = 'mobile-app/1.4';

export type Purchase = { buyerEmail: string; buyerName: string; totalCents: number };

async function call(baseUrl: string, method: string, path: string, body?: unknown): Promise<Record<string, unknown>> {
  const response = await fetch(`${baseUrl}${path}`, {
    method,
    headers: { 'content-type': 'application/json', 'user-agent': USER_AGENT },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  if (!response.ok) {
    throw new Error(`mobile-app: el servicio respondió ${response.status} a ${method} ${path}: ${await response.text()}`);
  }
  const payload = (await response.json()) as { order?: Record<string, unknown> };
  if (typeof payload.order !== 'object' || payload.order === null) {
    throw new Error('mobile-app: la respuesta no trae "order"');
  }
  return payload.order;
}

// Lee solo los campos que necesita y no mira los demás. Pero los que necesita
// tienen que estar, con el tipo que tenían cuando se escribió la aplicación.
function field<T extends 'string' | 'number'>(
  order: Record<string, unknown>,
  name: string,
  type: T,
): T extends 'string' ? string : number {
  const value = order[name];
  if (typeof value !== type) {
    throw new Error(`mobile-app: la orden no trae el campo "${name}" (${type}); llegó ${JSON.stringify(value)}`);
  }
  return value as T extends 'string' ? string : number;
}

/** Las líneas de la pantalla "Mi compra". La aplicación solo conoce soles. */
export function purchaseScreen(order: Record<string, unknown>): string[] {
  const soles = (field(order, 'totalCents', 'number') / 100).toFixed(2);
  return [
    `Orden #${field(order, 'id', 'number')}`,
    `A nombre de: ${field(order, 'buyerName', 'string')}`,
    `Total: S/ ${soles}`,
    `Estado: ${field(order, 'status', 'string') === 'paid' ? 'pagada' : 'anulada'}`,
  ];
}

export async function buy(baseUrl: string, purchase: Purchase): Promise<number> {
  const order = await call(baseUrl, 'POST', '/orders', purchase);
  return field(order, 'id', 'number');
}

export async function showPurchase(baseUrl: string, orderId: number): Promise<string[]> {
  return purchaseScreen(await call(baseUrl, 'GET', `/orders/${orderId}`));
}

if (import.meta.main) {
  const baseUrl = process.env.ORDERS_URL ?? 'http://localhost:3000';
  const [command, ...args] = process.argv.slice(2);
  if (command === 'show' && args.length === 1) {
    console.log((await showPurchase(baseUrl, Number(args[0]))).join('\n'));
  } else if (command === 'buy' && args.length === 3) {
    const id = await buy(baseUrl, { buyerEmail: args[0]!, buyerName: args[1]!, totalCents: Number(args[2]) });
    console.log((await showPurchase(baseUrl, id)).join('\n'));
  } else {
    console.error('Uso: mobile-client.ts show <id> | buy <correo> "<nombre>" <céntimos>');
    process.exitCode = 1;
  }
}
consumers/sales-report.tsDescargar consumers/sales-report.ts
import type pg from 'pg';
import { closeDb, db } from '../shared/db.ts';

// El proceso de reportes. Lo escribió otro equipo y no pasa por la API: se
// conecta a la base de datos del servicio y lee la tabla orders directamente.
// Para ese equipo, las columnas de la tabla son el contrato.
//
//   node consumers/sales-report.ts 2026-03

export type BuyerLine = { buyerName: string; orders: number; totalCents: number };
export type SalesReport = { month: string; orders: number; totalCents: number; topBuyers: BuyerLine[] };

/** Ventas pagadas de un mes (`2026-03`), en hora de Lima, y sus cinco mayores compradores. */
export async function salesReport(pool: pg.Pool, month: string): Promise<SalesReport> {
  const range = `created_at >= ($1 || '-01 00:00:00-05')::timestamptz
             AND created_at <  ($1 || '-01 00:00:00-05')::timestamptz + interval '1 month'`;
  const totals = await pool.query<{ orders: string; total_cents: string }>(
    `SELECT count(*) AS orders, coalesce(sum(total_cents), 0) AS total_cents
       FROM orders WHERE status = 'paid' AND ${range}`,
    [month],
  );
  const buyers = await pool.query<{ buyer_name: string; orders: string; total_cents: string }>(
    `SELECT buyer_name, count(*) AS orders, sum(total_cents) AS total_cents
       FROM orders WHERE status = 'paid' AND ${range}
      GROUP BY buyer_email, buyer_name
      ORDER BY sum(total_cents) DESC, buyer_email
      LIMIT 5`,
    [month],
  );
  return {
    month,
    orders: Number(totals.rows[0]!.orders),
    totalCents: Number(totals.rows[0]!.total_cents),
    topBuyers: buyers.rows.map((row) => ({
      buyerName: row.buyer_name,
      orders: Number(row.orders),
      totalCents: Number(row.total_cents),
    })),
  };
}

export function formatReport(report: SalesReport): string {
  const soles = (cents: number): string => `S/ ${(cents / 100).toFixed(2)}`;
  return [
    `Ventas de ${report.month}: ${report.orders} órdenes pagadas, ${soles(report.totalCents)}`,
    'Mayores compradores:',
    ...report.topBuyers.map((b) => `  ${b.buyerName.padEnd(24)} ${String(b.orders).padStart(4)} órdenes  ${soles(b.totalCents)}`),
  ].join('\n');
}

if (import.meta.main) {
  try {
    console.log(formatReport(await salesReport(db(), process.argv[2] ?? '2026-03')));
  } finally {
    await closeDb();
  }
}
consumers/stage.tsDescargar consumers/stage.ts
import type { Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import type pg from 'pg';
import type { SalesReport } from './sales-report.ts';

// Las pruebas de los consumidores no cambian durante el laboratorio; lo que
// cambia es contra qué versión del servicio y del reporte corren:
//
//   ORDERS_DIR   carpeta del servicio (por omisión, orders-v1)
//   REPORT       archivo del proceso de reportes (por omisión, consumers/sales-report.ts)
//
// make consumers S=lab las pone en lab/orders y lab/sales-report.ts.

const root = new URL('../', import.meta.url);

export const ordersDir = process.env.ORDERS_DIR ?? 'orders-v1';
export const reportFile = process.env.REPORT ?? 'consumers/sales-report.ts';

export type RunningService = { url: string; close(): Promise<void> };

export async function startOrders(dir: string = ordersDir): Promise<RunningService> {
  const module = (await import(new URL(`${dir}/server.ts`, root).href)) as { createOrdersServer(): Server };
  const server = module.createOrdersServer();
  await new Promise<void>((resolve) => server.listen(0, resolve));
  const { port } = server.address() as AddressInfo;
  return {
    url: `http://localhost:${port}`,
    close: () =>
      new Promise<void>((resolve) => {
        server.close(() => resolve());
        server.closeAllConnections();
      }),
  };
}

export async function loadReport(file: string = reportFile): Promise<(pool: pg.Pool, month: string) => Promise<SalesReport>> {
  const module = (await import(new URL(file, root).href)) as {
    salesReport(pool: pg.Pool, month: string): Promise<SalesReport>;
  };
  return module.salesReport;
}
db/schema.sqlDescargar db/schema.sql
-- El esquema del servicio de órdenes, versión 1. Los montos van en céntimos,
-- como enteros, y todos son en soles: la tabla no dice la moneda.

CREATE TABLE orders (
    id          integer     PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    buyer_email text        NOT NULL,
    buyer_name  text        NOT NULL,
    total_cents integer     NOT NULL CHECK (total_cents >= 0),
    status      text        NOT NULL DEFAULT 'paid' CHECK (status IN ('paid', 'cancelled')),
    created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX orders_created_at_idx ON orders (created_at);
db/seed.sqlDescargar db/seed.sql
-- Datos de ejemplo: :rows órdenes entre enero y junio de 2026, de 5 000
-- compradores. No hay nada al azar: con el mismo :rows salen siempre las
-- mismas filas, y por eso las pruebas pueden esperar valores exactos.
--
-- Los nombres se guardan como los escribió cada comprador: algunos tienen dos
-- nombres (Luz Marina) y otros dos apellidos (Quispe Mamani).

WITH names AS (
    SELECT ARRAY['Rosa', 'Juan', 'María', 'Carlos', 'Luz Marina', 'Pedro', 'Ana', 'José Luis',
                 'Carmen', 'Miguel', 'Julia', 'Víctor', 'Elena', 'Raúl', 'Flor', 'Óscar',
                 'Milagros', 'Jorge', 'Yolanda', 'César'] AS given,
           ARRAY['Quispe', 'Mamani', 'Flores', 'Huamán', 'Quispe Mamani', 'Rojas', 'García',
                 'Condori', 'Sánchez', 'Vargas', 'Torres Huamán', 'Ccori', 'Ramos', 'Mendoza',
                 'Castillo', 'Chávez', 'Apaza', 'Gutiérrez', 'Díaz', 'Salazar', 'Paredes',
                 'Cruz', 'Poma', 'Espinoza', 'Layme'] AS family
), numbered AS (
    -- Unos pocos compradores concentran muchas órdenes: el cuadrado empuja los
    -- índices hacia cero.
    SELECT i, floor(5000 * power(((i::bigint * 7919) % 10007) / 10007.0, 2))::int AS buyer
    FROM generate_series(1, :rows) AS i
)
INSERT INTO orders (buyer_email, buyer_name, total_cents, status, created_at)
SELECT 'comprador' || lpad(buyer::text, 4, '0') || '@correo.pe',
       given[buyer % 20 + 1] || ' ' || family[(buyer / 20) % 25 + 1],
       2000 + ((i * 37) % 60) * 500,
       CASE WHEN i % 23 = 0 THEN 'cancelled' ELSE 'paid' END,
       timestamptz '2026-01-01 00:00:00-05' + (i - 1) * (interval '181 days' / :rows)
FROM numbered, names
ORDER BY i;

ANALYZE orders;
expand-contract/versions.tsDescargar expand-contract/versions.ts
import type pg from 'pg';

// Las tres versiones del código que usa la tabla coupons durante el cambio de
// nombre de discount a percent_off. Cada una es lo que haría un despliegue.

export type CouponCode = {
  name: 'antigua' | 'puente' | 'nueva';
  write(client: pg.Client, code: string, percent: number): Promise<void>;
  /** El porcentaje del cupón, o null si esta versión no lo encuentra donde lo busca. */
  read(client: pg.Client, code: string): Promise<number | null>;
};

async function one(client: pg.Client, sql: string, code: string): Promise<number | null> {
  const result = await client.query<{ percent: number | null }>(sql, [code]);
  return result.rows[0]?.percent ?? null;
}

/** La que está en producción antes de empezar: solo conoce discount. */
export const oldCode: CouponCode = {
  name: 'antigua',
  write: async (client, code, percent) =>
    void (await client.query('INSERT INTO coupons (code, discount) VALUES ($1, $2)', [code, percent])),
  read: (client, code) => one(client, 'SELECT discount AS percent FROM coupons WHERE code = $1', code),
};

/** La de la transición: escribe en las dos columnas y lee la nueva, o la vieja si la nueva está vacía. */
export const bridgeCode: CouponCode = {
  name: 'puente',
  write: async (client, code, percent) =>
    void (await client.query('INSERT INTO coupons (code, discount, percent_off) VALUES ($1, $2, $2)', [code, percent])),
  read: (client, code) =>
    one(client, 'SELECT coalesce(percent_off, discount) AS percent FROM coupons WHERE code = $1', code),
};

/** La del final: solo conoce percent_off. */
export const newCode: CouponCode = {
  name: 'nueva',
  write: async (client, code, percent) =>
    void (await client.query('INSERT INTO coupons (code, percent_off) VALUES ($1, $2)', [code, percent])),
  read: (client, code) => one(client, 'SELECT percent_off AS percent FROM coupons WHERE code = $1', code),
};

export const versions = [oldCode, bridgeCode, newCode];
expand-contract/walkthrough.tsDescargar expand-contract/walkthrough.ts
import { readFile } from 'node:fs/promises';
import type pg from 'pg';
import { connect } from '../shared/db.ts';
import { versions, type CouponCode } from './versions.ts';

// Recorre los cuatro estados del esquema de coupons y, en cada uno, prueba
// todas las parejas de versiones del código: una escribe un cupón y otra lo
// lee. Dos versiones pueden convivir en un estado si las cuatro combinaciones
// entre ellas dan "bien".
//
//   make expand-contract

export const steps = ['0-initial', '1-expand', '2-migrate', '3-contract'] as const;
export type Step = (typeof steps)[number];
export type Cell = 'bien' | 'lee NULL' | 'no escribe' | 'no lee';
export type Matrix = Record<string, Record<string, Cell>>;

export async function applyStep(client: pg.Client, step: Step): Promise<void> {
  await client.query(await readFile(new URL(`steps/${step}.sql`, import.meta.url), 'utf8'));
}

/** `writer` guarda un cupón de 25 % y `reader` lo busca. Nada queda en la tabla. */
async function tryPair(client: pg.Client, writer: CouponCode, reader: CouponCode): Promise<{ cell: Cell; error?: string }> {
  await client.query('BEGIN');
  try {
    try {
      await writer.write(client, 'PRUEBA', 25);
    } catch (error) {
      return { cell: 'no escribe', error: (error as Error).message };
    }
    try {
      return { cell: (await reader.read(client, 'PRUEBA')) === 25 ? 'bien' : 'lee NULL' };
    } catch (error) {
      return { cell: 'no lee', error: (error as Error).message };
    }
  } finally {
    await client.query('ROLLBACK');
  }
}

export async function matrixOf(client: pg.Client, onError?: (who: string, message: string) => void): Promise<Matrix> {
  const matrix: Matrix = {};
  for (const writer of versions) {
    matrix[writer.name] = {};
    for (const reader of versions) {
      const { cell, error } = await tryPair(client, writer, reader);
      matrix[writer.name]![reader.name] = cell;
      if (error) onError?.(cell === 'no escribe' ? writer.name : reader.name, error);
    }
  }
  return matrix;
}

/** Las versiones que pueden correr a la vez en este estado: todas sus parejas dan "bien". */
export function canCoexist(matrix: Matrix): string[] {
  const alone = versions.map((v) => v.name).filter((name) => matrix[name]![name] === 'bien');
  return alone.filter((a) => alone.every((b) => matrix[a]![b] === 'bien' && matrix[b]![a] === 'bien'));
}

if (import.meta.main) {
  const client = await connect();
  try {
    for (const step of steps) {
      await applyStep(client, step);
      const errors = new Map<string, string>();
      const matrix = await matrixOf(client, (who, message) => errors.set(who, message));
      console.log(`\n== ${step}.sql`);
      console.log(`${'escribe \\ lee'.padEnd(14)}${versions.map((v) => v.name.padEnd(12)).join('')}`);
      for (const writer of versions) {
        console.log(`${writer.name.padEnd(14)}${versions.map((r) => matrix[writer.name]![r.name]!.padEnd(12)).join('')}`);
      }
      for (const [who, message] of errors) console.log(`  ${who}: ${message}`);
      console.log(`  pueden convivir: ${canCoexist(matrix).join(' y ') || 'ninguna'}`);
    }
    await client.query('DROP TABLE coupons');
  } finally {
    await client.end();
  }
}
formats/document-roundtrip.tsDescargar formats/document-roundtrip.ts
// El caso que hace difícil la compatibilidad hacia adelante: código viejo que
// lee un documento escrito por código nuevo, lo modifica y lo vuelve a guardar.
// Las dos funciones anulan una orden; solo una conserva lo que no conoce.
//
//   node formats/document-roundtrip.ts

type OrderV1 = { id: number; buyerName: string; totalCents: number; status: string };

/** Como se escribe sin pensarlo: se copia el documento a un objeto con los campos conocidos. */
export function cancelDroppingUnknown(document: string): string {
  const raw = JSON.parse(document) as OrderV1;
  const order: OrderV1 = { id: raw.id, buyerName: raw.buyerName, totalCents: raw.totalCents, status: 'cancelled' };
  return JSON.stringify(order);
}

/** Lo mismo, llevando consigo todo lo que llegó: solo se toca el campo que cambia. */
export function cancelKeepingUnknown(document: string): string {
  const raw = JSON.parse(document) as Record<string, unknown>;
  return JSON.stringify({ ...raw, status: 'cancelled' });
}

if (import.meta.main) {
  const writtenByNewCode = JSON.stringify({
    id: 7,
    buyerName: 'Ana Ccori',
    givenName: 'Ana',
    familyName: 'Ccori',
    totalCents: 10000,
    currency: 'USD',
    status: 'paid',
  });
  console.log(`escrito por el código nuevo:  ${writtenByNewCode}`);
  console.log(`anulado por el código viejo:  ${cancelDroppingUnknown(writtenByNewCode)}`);
  console.log(`anulado conservando el resto: ${cancelKeepingUnknown(writtenByNewCode)}`);
}
formats/json-numbers.tsDescargar formats/json-numbers.ts
// JSON no dice de qué tamaño es un número: cada lenguaje decide. JavaScript
// los lee todos como números de punto flotante de 64 bits, que solo
// representan enteros exactos hasta 2^53 - 1.
//
//   node formats/json-numbers.ts

const text = '{"orderId": 9007199254740993, "totalCents": 1999, "price": 0.1}';
const parsed = JSON.parse(text) as { orderId: number; totalCents: number; price: number };

console.log(`texto recibido:   ${text}`);
console.log(`orderId leído:    ${parsed.orderId}`);
console.log(`vuelto a escribir: ${JSON.stringify(parsed)}`);
console.log(`Number.MAX_SAFE_INTEGER = ${Number.MAX_SAFE_INTEGER}`);
console.log(`0.1 + 0.2 = ${0.1 + 0.2}   (por eso los montos van en céntimos, como enteros)`);
// Quien necesita enteros grandes en JSON los manda como texto.
console.log(`como texto:       ${BigInt('9007199254740993')}`);
formats/tagged.tsDescargar formats/tagged.ts
// Un formato binario mínimo, con la misma idea que Protocol Buffers: en los
// bytes no viaja el nombre de cada campo sino un número (su etiqueta), y el
// esquema dice qué nombre y qué tipo le corresponde a cada etiqueta.
//
// Cada campo se escribe como: clave (etiqueta * 8 + tipo), y luego el valor.
//   tipo 0: un entero sin signo en varint (7 bits por byte, el bit alto dice "sigue")
//   tipo 2: un texto: su longitud en varint y luego sus bytes en UTF-8
//
//   node formats/tagged.ts

export type FieldType = 'int' | 'string';
export type Schema = Record<number, { name: string; type: FieldType }>;
export type Unknown = { tag: number; wireType: 0 | 2; value: number | Uint8Array };
export type Decoded = { known: Record<string, number | string>; unknown: Unknown[] };

function writeVarint(out: number[], value: number): void {
  let rest = value;
  while (rest >= 0x80) {
    out.push((rest % 0x80) + 0x80);
    rest = Math.floor(rest / 0x80);
  }
  out.push(rest);
}

function readVarint(bytes: Uint8Array, at: number): { value: number; next: number } {
  let value = 0;
  let scale = 1;
  let position = at;
  for (;;) {
    const byte = bytes[position];
    if (byte === undefined) throw new Error('El mensaje termina a la mitad de un número');
    position += 1;
    value += (byte & 0x7f) * scale;
    if (byte < 0x80) return { value, next: position };
    scale *= 0x80;
  }
}

function writeField(out: number[], tag: number, value: number | string | Uint8Array): void {
  if (typeof value === 'number') {
    writeVarint(out, tag * 8);
    writeVarint(out, value);
  } else {
    const content = typeof value === 'string' ? new TextEncoder().encode(value) : value;
    writeVarint(out, tag * 8 + 2);
    writeVarint(out, content.length);
    out.push(...content);
  }
}

/** Escribe los campos de `message` que el esquema conoce y, detrás, los `unknown` tal como llegaron. */
export function encode(schema: Schema, message: Record<string, number | string>, unknown: Unknown[] = []): Uint8Array {
  const out: number[] = [];
  for (const [tag, field] of Object.entries(schema)) {
    const value = message[field.name];
    if (value !== undefined) writeField(out, Number(tag), value);
  }
  for (const field of unknown) writeField(out, field.tag, field.value);
  return Uint8Array.from(out);
}

/**
 * Lee un mensaje con el esquema de quien lee. Un campo cuya etiqueta no está
 * en el esquema no es un error: el tipo dice cuántos bytes ocupa, así que se
 * puede saltar, y se guarda aparte para poder devolverlo.
 */
export function decode(schema: Schema, bytes: Uint8Array): Decoded {
  const decoded: Decoded = { known: {}, unknown: [] };
  let position = 0;
  while (position < bytes.length) {
    const key = readVarint(bytes, position);
    const tag = Math.floor(key.value / 8);
    const wireType = key.value % 8;
    let value: number | Uint8Array;
    if (wireType === 0) {
      const number = readVarint(bytes, key.next);
      value = number.value;
      position = number.next;
    } else if (wireType === 2) {
      const length = readVarint(bytes, key.next);
      value = bytes.slice(length.next, length.next + length.value);
      position = length.next + length.value;
    } else {
      throw new Error(`Tipo de campo desconocido: ${wireType}`);
    }
    const field = schema[tag];
    if (!field) {
      decoded.unknown.push({ tag, wireType, value });
    } else if (field.type === 'int' && typeof value === 'number') {
      decoded.known[field.name] = value;
    } else if (field.type === 'string' && typeof value !== 'number') {
      decoded.known[field.name] = new TextDecoder().decode(value);
    } else {
      throw new Error(`El campo ${tag} (${field.name}) llegó con otro tipo`);
    }
  }
  return decoded;
}

// El esquema de la orden, antes y después del cambio. La etiqueta 2 se llamaba
// buyerName; al dejar de usarse no se reutiliza: queda reservada para siempre.
export const orderV1: Schema = {
  1: { name: 'id', type: 'int' },
  2: { name: 'buyerName', type: 'string' },
  3: { name: 'totalCents', type: 'int' },
};

export const orderV2: Schema = {
  1: { name: 'id', type: 'int' },
  2: { name: 'buyerName', type: 'string' },
  3: { name: 'totalCents', type: 'int' },
  4: { name: 'givenName', type: 'string' },
  5: { name: 'familyName', type: 'string' },
  6: { name: 'currency', type: 'string' },
};

const hex = (bytes: Uint8Array): string => [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(' ');

if (import.meta.main) {
  const order = { id: 150, buyerName: 'Ana Ccori', totalCents: 32000, givenName: 'Ana', familyName: 'Ccori', currency: 'USD' };
  const json = JSON.stringify(order);
  const binary = encode(orderV2, order);
  console.log(`JSON (${Buffer.byteLength(json)} bytes): ${json}`);
  console.log(`binario (${binary.length} bytes): ${hex(binary)}`);

  console.log('\nUn lector con el esquema v1 lee el mensaje escrito con el v2:');
  const seenByOld = decode(orderV1, binary);
  console.log(`  conoce:    ${JSON.stringify(seenByOld.known)}`);
  console.log(`  no conoce: etiquetas ${seenByOld.unknown.map((u) => u.tag).join(', ')}`);

  const rewritten = encode(orderV1, { ...seenByOld.known, totalCents: 30000 }, seenByOld.unknown);
  console.log('\nEl lector v1 cambia totalCents y vuelve a escribir, conservando lo que no conoce:');
  console.log(`  un lector v2 lee: ${JSON.stringify(decode(orderV2, rewritten).known)}`);

  const dropped = encode(orderV1, { ...seenByOld.known, totalCents: 30000 });
  console.log('Si no lo conserva:');
  console.log(`  un lector v2 lee: ${JSON.stringify(decode(orderV2, dropped).known)}`);
}
models/models.sqlDescargar models/models.sql
-- El mismo pedido de una librería guardado de dos maneras en PostgreSQL:
-- en tablas (modelo relacional) y como un documento JSON (modelo de documentos).
--
--   make models

\set QUIET on
\pset footer off
SET client_min_messages = warning;
DROP TABLE IF EXISTS m_items, m_orders, m_books, m_order_docs;

-- Relacional: cada dato está en un solo lugar y las tablas se relacionan por clave.
CREATE TABLE m_books  (id integer PRIMARY KEY, title text NOT NULL, price_cents integer NOT NULL CHECK (price_cents > 0));
CREATE TABLE m_orders (id integer PRIMARY KEY, buyer text NOT NULL);
CREATE TABLE m_items  (order_id integer NOT NULL REFERENCES m_orders (id),
                       book_id  integer NOT NULL REFERENCES m_books (id),
                       quantity integer NOT NULL CHECK (quantity > 0),
                       PRIMARY KEY (order_id, book_id));

INSERT INTO m_books VALUES (1, 'Los ríos profundos', 4500), (2, 'La ciudad y los perros', 5200), (3, 'Trilce', 3000);
INSERT INTO m_orders SELECT i, 'comprador ' || i FROM generate_series(1, 1000) AS i;
INSERT INTO m_items SELECT i, 1 + i % 3, 1 + i % 2 FROM generate_series(1, 1000) AS i;
INSERT INTO m_items SELECT i, 1 + (i + 1) % 3, 1 FROM generate_series(1, 1000) AS i WHERE i % 4 = 0;

-- Documentos: el pedido entero, con sus libros adentro, en una sola fila.
CREATE TABLE m_order_docs (id integer PRIMARY KEY, doc jsonb NOT NULL);
INSERT INTO m_order_docs
SELECT o.id, jsonb_build_object('buyer', o.buyer, 'items',
         jsonb_agg(jsonb_build_object('title', b.title, 'priceCents', b.price_cents, 'quantity', i.quantity) ORDER BY b.id))
FROM m_orders o JOIN m_items i ON i.order_id = o.id JOIN m_books b ON b.id = i.book_id
GROUP BY o.id;

\echo '== 1. Leer un pedido entero'
\echo 'Documento: una fila, sin JOIN.'
SELECT jsonb_pretty(doc) AS pedido_4 FROM m_order_docs WHERE id = 4;
\echo 'Relacional: tres tablas.'
SELECT o.buyer, b.title, b.price_cents, i.quantity
FROM m_orders o JOIN m_items i ON i.order_id = o.id JOIN m_books b ON b.id = i.book_id
WHERE o.id = 4 ORDER BY b.id;

\echo '== 2. Una pregunta que cruza pedidos: cuántos ejemplares se vendieron de cada libro'
\echo 'Relacional:'
SELECT b.title, sum(i.quantity) AS ejemplares FROM m_items i JOIN m_books b ON b.id = i.book_id GROUP BY b.title ORDER BY b.title;
\echo 'Documento: hay que abrir todos los documentos y desarmar sus listas.'
SELECT item->>'title' AS title, sum((item->>'quantity')::int) AS ejemplares
FROM m_order_docs, jsonb_array_elements(doc->'items') AS item GROUP BY 1 ORDER BY 1;

\echo '== 3. Corregir el título de un libro'
\set QUIET off
\echo 'Relacional:'
UPDATE m_books SET title = 'Los ríos profundos (ed. 2026)' WHERE id = 1;
\echo 'Documento: el título está copiado en cada pedido que lo incluye.'
UPDATE m_order_docs SET doc = jsonb_set(doc, '{items}',
         (SELECT jsonb_agg(CASE WHEN item->>'title' = 'Los ríos profundos'
                                THEN jsonb_set(item, '{title}', '"Los ríos profundos (ed. 2026)"') ELSE item END)
            FROM jsonb_array_elements(doc->'items') AS item))
WHERE doc->'items' @> '[{"title": "Los ríos profundos"}]';
\set QUIET on

\echo '== 4. Un dato mal formado'
\echo 'Relacional (esquema al escribir): la base de datos lo rechaza.'
INSERT INTO m_items VALUES (1, 3, 0);
\echo 'Documento (esquema al leer): entra, y falla después, en quien lo lea.'
INSERT INTO m_order_docs VALUES (1001, '{"buyer": "comprador 1001", "items": [{"title": "Trilce", "quantity": "dos"}]}');
SELECT sum((item->>'quantity')::int) AS ejemplares FROM m_order_docs, jsonb_array_elements(doc->'items') AS item;

DROP TABLE m_items, m_orders, m_books, m_order_docs;
orders-v1/main.tsDescargar orders-v1/main.ts
import { closeDb } from '../shared/db.ts';
import { log, settings } from '../shared/settings.ts';
import { createOrdersServer } from './server.ts';

const server = createOrdersServer();
server.listen(settings.port, () => {
  log('orders-v1', `escuchando en http://localhost:${settings.port} (base de datos ${settings.database})`);
});

// Con Ctrl+C se deja de aceptar pedidos y se cierra el pool; si no, el proceso no termina.
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
  process.on(signal, () => {
    server.close(() => void closeDb());
    server.closeAllConnections();
  });
}
orders-v1/server.tsDescargar orders-v1/server.ts
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { AppError, orderIdFrom, readJson, sendError, sendJson } from '../shared/http.ts';
import { log } from '../shared/settings.ts';
import { cancelOrder, findOrder, insertOrder, type NewOrder } from './store.ts';

// orders-v1: el contrato que usan hoy el cliente móvil y cualquier otro cliente.
//
//   POST /orders             { buyerEmail, buyerName, totalCents }  -> 201 { order }
//   GET  /orders/:id                                                -> 200 { order }
//   POST /orders/:id/cancel                                         -> 200 { order }
//
// order = { id, buyerEmail, buyerName, totalCents, status, createdAt }

function parseNewOrder(body: unknown): NewOrder {
  // Solo se miran los campos que el servicio conoce; cualquier otro se ignora.
  const input = (typeof body === 'object' && body !== null ? body : {}) as Record<string, unknown>;
  const { buyerEmail, buyerName, totalCents } = input;
  const valid =
    typeof buyerEmail === 'string' &&
    buyerEmail.includes('@') &&
    typeof buyerName === 'string' &&
    buyerName.trim().length > 0 &&
    Number.isInteger(totalCents) &&
    (totalCents as number) >= 0;
  if (!valid) {
    throw new AppError(422, 'INVALID_INPUT', 'Se espera { buyerEmail, buyerName, totalCents }');
  }
  return { buyerEmail: buyerEmail as string, buyerName: (buyerName as string).trim(), totalCents: totalCents as number };
}

async function route(request: IncomingMessage, response: ServerResponse): Promise<number> {
  const { pathname } = new URL(request.url ?? '/', 'http://localhost');
  const method = request.method ?? 'GET';

  if (method === 'GET' && pathname === '/health') {
    sendJson(response, 200, { status: 'ok', version: 'orders-v1' });
    return 200;
  }
  if (method === 'POST' && pathname === '/orders') {
    const order = await insertOrder(parseNewOrder(await readJson(request)));
    sendJson(response, 201, { order });
    return 201;
  }
  const id = orderIdFrom(pathname);
  if (method === 'GET' && id !== undefined) {
    const order = await findOrder(id);
    if (!order) throw new AppError(404, 'ORDER_NOT_FOUND', `No existe la orden ${id}`);
    sendJson(response, 200, { order });
    return 200;
  }
  const cancelId = orderIdFrom(pathname, '/cancel');
  if (method === 'POST' && cancelId !== undefined) {
    const order = await cancelOrder(cancelId);
    if (!order) throw new AppError(404, 'ORDER_NOT_FOUND', `No existe la orden ${cancelId}`);
    sendJson(response, 200, { order });
    return 200;
  }
  throw new AppError(404, 'NOT_FOUND', `No existe ${method} ${pathname}`);
}

/** El servidor de órdenes, todavía sin escuchar en ningún puerto. */
export function createOrdersServer(): Server {
  return createServer((request, response) => {
    route(request, response)
      .catch((error: unknown) => {
        const status = sendError(response, error);
        if (status === 500) log('orders-v1', `error: ${String(error)}`);
        return status;
      })
      .then((status) => log('orders-v1', `${request.method} ${request.url} ${status}`));
  });
}
orders-v1/store.tsDescargar orders-v1/store.ts
import { db } from '../shared/db.ts';

// Lo único que sabe de la tabla orders dentro del servicio. Cada consulta
// nombra sus columnas: un SELECT * cambiaría de forma el día en que alguien
// agregue una columna.

export type Order = {
  id: number;
  buyerEmail: string;
  buyerName: string;
  totalCents: number;
  status: 'paid' | 'cancelled';
  createdAt: string;
};

export type NewOrder = { buyerEmail: string; buyerName: string; totalCents: number };

type OrderRow = {
  id: number;
  buyer_email: string;
  buyer_name: string;
  total_cents: number;
  status: 'paid' | 'cancelled';
  created_at: Date;
};

const COLUMNS = 'id, buyer_email, buyer_name, total_cents, status, created_at';

function toOrder(row: OrderRow): Order {
  return {
    id: row.id,
    buyerEmail: row.buyer_email,
    buyerName: row.buyer_name,
    totalCents: row.total_cents,
    status: row.status,
    createdAt: row.created_at.toISOString(),
  };
}

export async function insertOrder(input: NewOrder): Promise<Order> {
  const result = await db().query<OrderRow>(
    `INSERT INTO orders (buyer_email, buyer_name, total_cents) VALUES ($1, $2, $3) RETURNING ${COLUMNS}`,
    [input.buyerEmail, input.buyerName, input.totalCents],
  );
  return toOrder(result.rows[0]!);
}

export async function findOrder(id: number): Promise<Order | undefined> {
  const result = await db().query<OrderRow>(`SELECT ${COLUMNS} FROM orders WHERE id = $1`, [id]);
  const row = result.rows[0];
  return row ? toOrder(row) : undefined;
}

export async function cancelOrder(id: number): Promise<Order | undefined> {
  const result = await db().query<OrderRow>(
    `UPDATE orders SET status = 'cancelled' WHERE id = $1 RETURNING ${COLUMNS}`,
    [id],
  );
  const row = result.rows[0];
  return row ? toOrder(row) : undefined;
}
shared/db.tsDescargar shared/db.ts
import pg from 'pg';
import { settings } from './settings.ts';

// Un pool por proceso. El host y el usuario salen de PGHOST y PGUSER, que el
// contenedor ya define.
let pool: pg.Pool | undefined;

export function db(): pg.Pool {
  pool ??= new pg.Pool({ database: settings.database, max: 5 });
  return pool;
}

/** Cierra el pool. Sin esto, el programa no termina. */
export async function closeDb(): Promise<void> {
  const open = pool;
  pool = undefined;
  await open?.end();
}

/** Una conexión aparte, para los programas que necesitan varias sesiones a la vez. */
export async function connect(database: string = settings.database): Promise<pg.Client> {
  const client = new pg.Client({ database });
  await client.connect();
  return client;
}
shared/http.tsDescargar shared/http.ts
import type { IncomingMessage, ServerResponse } from 'node:http';

// Lo que comparten todas las versiones del servicio: leer y escribir JSON, y
// los errores que se convierten en una respuesta HTTP.

export class AppError extends Error {
  readonly status: number;
  readonly code: string;

  constructor(status: number, code: string, message: string) {
    super(message);
    this.status = status;
    this.code = code;
  }
}

export function sendJson(response: ServerResponse, status: number, body: unknown): void {
  const text = JSON.stringify(body);
  response.writeHead(status, {
    'content-type': 'application/json; charset=utf-8',
    'content-length': Buffer.byteLength(text),
  });
  response.end(text);
}

export async function readJson(request: IncomingMessage): Promise<unknown> {
  const chunks: Buffer[] = [];
  for await (const chunk of request) chunks.push(chunk as Buffer);
  try {
    return JSON.parse(Buffer.concat(chunks).toString('utf8'));
  } catch {
    throw new AppError(400, 'INVALID_JSON', 'El cuerpo del pedido no es JSON válido');
  }
}

/** Convierte cualquier error en la respuesta que le toca. */
export function sendError(response: ServerResponse, error: unknown): number {
  if (error instanceof AppError) {
    sendJson(response, error.status, { error: { code: error.code, message: error.message } });
    return error.status;
  }
  // Un error que nadie previó: se responde 500 sin contar detalles internos.
  sendJson(response, 500, { error: { code: 'INTERNAL_ERROR', message: 'Ocurrió un error inesperado' } });
  return 500;
}

/** El id de `/orders/:id` o de `/orders/:id/cancel`; undefined si la ruta no tiene esa forma. */
export function orderIdFrom(pathname: string, suffix = ''): number | undefined {
  const match = new RegExp(`^/orders/(\\d+)${suffix}$`).exec(pathname);
  return match ? Number(match[1]) : undefined;
}
shared/settings.tsDescargar shared/settings.ts
// Configuración de la semana: todo sale de variables de entorno.

function numberFromEnv(name: string, fallback: number): number {
  const raw = process.env[name];
  if (raw === undefined || raw === '') return fallback;
  const value = Number(raw);
  if (!Number.isFinite(value) || value < 0) {
    throw new Error(`La variable ${name} debe ser un número, y es "${raw}"`);
  }
  return value;
}

export const settings = {
  port: numberFromEnv('PORT', 3000),
  // La base de datos del servicio de órdenes. Las pruebas y las mediciones usan otras.
  database: process.env.W09_DB ?? 'arq_w09',
  logEnabled: process.env.W09_LOG !== 'off',
};

export { numberFromEnv };

export function log(who: string, message: string): void {
  if (settings.logEnabled) console.log(`[${who}] ${message}`);
}
shared/split-name.tsDescargar shared/split-name.ts
// Cómo se parte un nombre completo cuando solo se tiene el texto que escribió
// el comprador: la primera palabra es el nombre y el resto, el apellido.
// Es una regla, no un dato: acierta con "Rosa Quispe Mamani" y se equivoca
// con "Luz Marina Flores". La misma regla está aquí dos veces, en TypeScript
// y en SQL, y test/split-name.test.ts comprueba que dicen lo mismo.

export type SplitName = { givenName: string; familyName: string };

export function splitName(fullName: string): SplitName {
  const space = fullName.indexOf(' ');
  if (space === -1) return { givenName: fullName, familyName: '' };
  return { givenName: fullName.slice(0, space), familyName: fullName.slice(space + 1) };
}

/** Lo contrario: el nombre completo como lo espera quien todavía lee el campo viejo. */
export function joinName(givenName: string, familyName: string): string {
  return familyName === '' ? givenName : `${givenName} ${familyName}`;
}

// Las mismas dos mitades, como expresiones SQL sobre la columna buyer_name.
export const GIVEN_NAME_SQL = `split_part(buyer_name, ' ', 1)`;
export const FAMILY_NAME_SQL = `substr(buyer_name, length(split_part(buyer_name, ' ', 1)) + 2)`;
timeline/measure.tsDescargar timeline/measure.ts
import { connect } from '../shared/db.ts';
import { postSimple, postWithFanOut, readByQuery, readPrecomputed } from './timeline.ts';

// Mide las dos formas de armar una línea de tiempo: cuánto cuesta leerla y
// cuánto cuesta publicar, para una cuenta común y para la cuenta famosa.
//
//   make timeline            (USERS=10000 por omisión)

const database = process.env.W09_TIMELINE_DB ?? 'arq_w09_timeline';
const client = await connect(database);

const median = (values: number[]): number => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!;

async function timed(run: () => Promise<unknown>): Promise<number> {
  const start = performance.now();
  await run();
  return performance.now() - start;
}

try {
  const users = Number((await client.query<{ n: string }>('SELECT max(follower_id) AS n FROM tl_follows')).rows[0]!.n);
  const followers = async (id: number): Promise<number> =>
    Number((await client.query<{ n: string }>('SELECT count(*) AS n FROM tl_follows WHERE followee_id = $1', [id])).rows[0]!.n);
  const sizes = await client.query<{ posts: string; home: string }>(
    'SELECT (SELECT count(*) FROM tl_posts) AS posts, (SELECT count(*) FROM tl_home) AS home',
  );
  const normal = 4242 % users || 2;
  console.log(
    `${users} usuarios, ${sizes.rows[0]!.posts} publicaciones, ${sizes.rows[0]!.home} filas en las líneas de tiempo ya calculadas.`,
  );
  console.log(`La cuenta ${normal} tiene ${await followers(normal)} seguidores; la cuenta 1, ${await followers(1)}.\n`);

  // Leer: 500 lectores distintos con cada diseño.
  const readers = Array.from({ length: 500 }, (_, i) => 2 + ((i * 7919) % (users - 1)));
  const byQuery: number[] = [];
  const precomputed: number[] = [];
  for (const reader of readers) byQuery.push(await timed(() => readByQuery(client, reader)));
  for (const reader of readers) precomputed.push(await timed(() => readPrecomputed(client, reader)));
  console.log('Leer una línea de tiempo (mediana de 500 lectores):');
  console.log(`  calculada al leer       ${median(byQuery).toFixed(2)} ms`);
  console.log(`  calculada al escribir   ${median(precomputed).toFixed(2)} ms\n`);

  // Publicar: 20 veces con cada diseño y cada cuenta. Todo se deshace al final.
  await client.query('CREATE TEMP TABLE keep AS SELECT max(id) AS id FROM tl_posts');
  const now = new Date('2026-11-01T12:00:00Z');
  let rowsNormal = 0;
  let rowsFamous = 0;
  const publish = async (author: number, fanOut: boolean): Promise<number> => {
    const times: number[] = [];
    for (let i = 0; i < 20; i += 1) {
      const at = new Date(now.getTime() + author * 1000 + i + (fanOut ? 500 : 0));
      times.push(
        await timed(async () => {
          if (!fanOut) return postSimple(client, author, 'medición', at);
          const rows = await postWithFanOut(client, author, 'medición', at);
          if (author === 1) rowsFamous = rows;
          else rowsNormal = rows;
        }),
      );
    }
    return median(times);
  };
  const simpleNormal = await publish(normal, false);
  const simpleFamous = await publish(1, false);
  const fanNormal = await publish(normal, true);
  const fanFamous = await publish(1, true);
  console.log('Publicar (mediana de 20 publicaciones):');
  console.log(`  calculada al leer,     cuenta común    ${simpleNormal.toFixed(2)} ms   (1 fila)`);
  console.log(`  calculada al leer,     cuenta famosa   ${simpleFamous.toFixed(2)} ms   (1 fila)`);
  console.log(`  calculada al escribir, cuenta común    ${fanNormal.toFixed(2)} ms   (${rowsNormal} filas)`);
  console.log(`  calculada al escribir, cuenta famosa   ${fanFamous.toFixed(2)} ms   (${rowsFamous} filas)`);

  await client.query('DELETE FROM tl_home WHERE post_id > (SELECT id FROM keep)');
  await client.query('DELETE FROM tl_posts WHERE id > (SELECT id FROM keep)');
} finally {
  await client.end();
}
timeline/schema.sqlDescargar timeline/schema.sql
-- Una red social mínima: quién sigue a quién, y qué publicó cada uno.
-- :users usuarios; el usuario 1 es la cuenta famosa, a la que siguen todos.

DROP TABLE IF EXISTS tl_home, tl_posts, tl_follows;

CREATE TABLE tl_follows (
    follower_id integer NOT NULL,
    followee_id integer NOT NULL,
    PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX tl_follows_followee_idx ON tl_follows (followee_id);

CREATE TABLE tl_posts (
    id         integer     PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    author_id  integer     NOT NULL,
    body       text        NOT NULL,
    created_at timestamptz NOT NULL
);
CREATE INDEX tl_posts_author_idx ON tl_posts (author_id, created_at DESC);

-- La línea de tiempo ya calculada: una fila por cada (lector, publicación).
-- Es un dato derivado: se puede borrar y volver a armar con las otras dos tablas.
CREATE TABLE tl_home (
    user_id    integer     NOT NULL,
    created_at timestamptz NOT NULL,
    post_id    integer     NOT NULL,
    PRIMARY KEY (user_id, created_at, post_id)
);

-- Cada usuario sigue a la cuenta famosa y a otros 30, siempre los mismos.
INSERT INTO tl_follows (follower_id, followee_id)
SELECT u, 1 FROM generate_series(2, :users) AS u;

INSERT INTO tl_follows (follower_id, followee_id)
SELECT u, 2 + ((u::bigint * 31 + k * 7919) % (:users - 1))::int
FROM generate_series(1, :users) AS u, generate_series(1, 30) AS k
WHERE u <> 2 + ((u::bigint * 31 + k * 7919) % (:users - 1))::int
ON CONFLICT DO NOTHING;

-- Cinco publicaciones por usuario, repartidas en el tiempo.
INSERT INTO tl_posts (author_id, body, created_at)
SELECT u, 'publicación ' || n || ' de ' || u,
       timestamptz '2026-09-01 00:00:00-05' + ((n * :users + u) * interval '1 second')
FROM generate_series(1, 5) AS n, generate_series(1, :users) AS u
ORDER BY n, u;

-- La línea de tiempo de cada uno, con lo publicado hasta ahora.
INSERT INTO tl_home (user_id, created_at, post_id)
SELECT f.follower_id, p.created_at, p.id
FROM tl_posts p JOIN tl_follows f ON f.followee_id = p.author_id;

ANALYZE tl_follows, tl_posts, tl_home;
timeline/timeline.tsDescargar timeline/timeline.ts
import type pg from 'pg';

// La misma pregunta, "las 20 publicaciones más recientes de las cuentas que
// sigo", resuelta de dos maneras.

export type TimelineEntry = { postId: number; createdAt: string };

type Row = { post_id: number; created_at: Date };
const toEntries = (rows: Row[]): TimelineEntry[] =>
  rows.map((row) => ({ postId: row.post_id, createdAt: row.created_at.toISOString() }));

/** Calcular al leer: se buscan las publicaciones de todos los seguidos y se ordenan. */
export async function readByQuery(client: pg.Client, userId: number): Promise<TimelineEntry[]> {
  const result = await client.query<Row>(
    `SELECT p.id AS post_id, p.created_at
       FROM tl_follows f JOIN tl_posts p ON p.author_id = f.followee_id
      WHERE f.follower_id = $1
      ORDER BY p.created_at DESC, p.id DESC
      LIMIT 20`,
    [userId],
  );
  return toEntries(result.rows);
}

/** Calcular al escribir: la línea de tiempo ya está armada; leerla es un recorrido corto de un índice. */
export async function readPrecomputed(client: pg.Client, userId: number): Promise<TimelineEntry[]> {
  const result = await client.query<Row>(
    `SELECT post_id, created_at FROM tl_home
      WHERE user_id = $1
      ORDER BY created_at DESC, post_id DESC
      LIMIT 20`,
    [userId],
  );
  return toEntries(result.rows);
}

/** Publicar cuando se calcula al leer: una fila. */
export async function postSimple(client: pg.Client, authorId: number, body: string, createdAt: Date): Promise<number> {
  const result = await client.query<{ id: number }>(
    'INSERT INTO tl_posts (author_id, body, created_at) VALUES ($1, $2, $3) RETURNING id',
    [authorId, body, createdAt],
  );
  return result.rows[0]!.id;
}

/**
 * Publicar cuando se calcula al escribir: la publicación y una fila por cada
 * seguidor, en la misma transacción. Devuelve cuántas filas escribió.
 */
export async function postWithFanOut(client: pg.Client, authorId: number, body: string, createdAt: Date): Promise<number> {
  await client.query('BEGIN');
  try {
    const postId = await postSimple(client, authorId, body, createdAt);
    const fanOut = await client.query(
      `INSERT INTO tl_home (user_id, created_at, post_id)
       SELECT follower_id, $2, $3 FROM tl_follows WHERE followee_id = $1`,
      [authorId, createdAt, postId],
    );
    await client.query('COMMIT');
    return 1 + (fanOut.rowCount ?? 0);
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  }
}
tools/backfill-batches.tsDescargar tools/backfill-batches.ts
import type pg from 'pg';
import { closeDb, db } from '../shared/db.ts';
import { FAMILY_NAME_SQL, GIVEN_NAME_SQL } from '../shared/split-name.ts';
import { numberFromEnv, settings } from '../shared/settings.ts';

// Llena given_name y family_name en las filas que todavía no los tienen, por
// lotes: cada lote es un UPDATE de pocas filas en su propia transacción, así
// que ningún lock dura más que un lote. Se puede interrumpir y volver a
// correr: solo toca las filas con given_name IS NULL.
//
//   node tools/backfill-batches.ts            (make backfill)
//   BATCH=1000 PAUSE_MS=50 node tools/backfill-batches.ts
//
// Las columnas nuevas tienen que existir: este script migra, no expande.

export type BackfillOptions = { batchSize: number; pauseMs: number; onBatch?: (done: number, total: number) => void };
export type BackfillResult = { rows: number; batches: number; totalMs: number; longestBatchMs: number };

type Queryable = pg.Pool | pg.Client;

export async function backfill(conn: Queryable, options: BackfillOptions): Promise<BackfillResult> {
  const limits = await conn.query<{ first: number | null; last: number | null }>(
    'SELECT min(id) AS first, max(id) AS last FROM orders WHERE given_name IS NULL',
  );
  const { first, last } = limits.rows[0]!;
  const result: BackfillResult = { rows: 0, batches: 0, totalMs: 0, longestBatchMs: 0 };
  if (first === null || last === null) return result;

  const start = performance.now();
  // Se avanza por rangos de id, no con OFFSET: cada lote encuentra sus filas
  // por la clave primaria, sin recorrer las que ya pasaron.
  for (let from = first; from <= last; from += options.batchSize) {
    const batchStart = performance.now();
    const updated = await conn.query(
      `UPDATE orders
          SET given_name = ${GIVEN_NAME_SQL}, family_name = ${FAMILY_NAME_SQL}
        WHERE id >= $1 AND id < $2 AND given_name IS NULL`,
      [from, from + options.batchSize],
    );
    result.longestBatchMs = Math.max(result.longestBatchMs, performance.now() - batchStart);
    result.rows += updated.rowCount ?? 0;
    result.batches += 1;
    options.onBatch?.(Math.min(from + options.batchSize - first, last - first + 1), last - first + 1);
    // La pausa deja pasar a las demás escrituras y le da tiempo a quien viene
    // detrás (una réplica, el autovacuum).
    if (options.pauseMs > 0) await new Promise((resolve) => setTimeout(resolve, options.pauseMs));
  }
  result.totalMs = performance.now() - start;
  return result;
}

if (import.meta.main) {
  const batchSize = numberFromEnv('BATCH', 5000);
  const pauseMs = numberFromEnv('PAUSE_MS', 0);
  try {
    const result = await backfill(db(), { batchSize, pauseMs });
    console.log(
      `${settings.database}: ${result.rows} filas en ${result.batches} lotes de hasta ${batchSize}, ` +
        `${result.totalMs.toFixed(0)} ms en total; el lote más largo tardó ${result.longestBatchMs.toFixed(0)} ms`,
    );
    const doubtful = await db().query<{ n: string }>(
      `SELECT count(*) AS n FROM orders WHERE buyer_name LIKE '% % %'`,
    );
    console.log(`Nombres de tres o más palabras, donde la regla pudo partir mal: ${doubtful.rows[0]!.n}`);
  } catch (error) {
    if ((error as { code?: string }).code === '42703') {
      console.error('La tabla orders todavía no tiene given_name y family_name: primero hay que expandir.');
      process.exitCode = 1;
    } else {
      throw error;
    }
  } finally {
    await closeDb();
  }
}
tools/forward-compat.tsDescargar tools/forward-compat.ts
import { startOrders } from '../consumers/stage.ts';
import { closeDb, db } from '../shared/db.ts';

// Compatibilidad hacia adelante: el servicio viejo (orders-v1, sin tocar)
// recibe órdenes con la forma que escribe el servicio nuevo.
//
//   make forward        usa su propia base de datos, arq_w09_fwd

async function post(url: string, body: unknown): Promise<{ status: number; body: unknown }> {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { status: response.status, body: await response.json() };
}

const service = await startOrders('orders-v1');
try {
  // 1. Durante la transición, el servicio nuevo manda los campos viejos y los nuevos.
  const both = { buyerEmail: 'ana.ccori@correo.pe', buyerName: 'Ana Ccori', givenName: 'Ana', familyName: 'Ccori', totalCents: 10000, currency: 'USD' };
  console.log('1. Una orden con los campos viejos y los nuevos');
  console.log(`   se envía:  ${JSON.stringify(both)}`);
  const accepted = await post(`${service.url}/orders`, both);
  console.log(`   responde:  ${accepted.status} ${JSON.stringify(accepted.body)}`);
  const returned = (accepted.body as { order: Record<string, unknown> }).order;
  const lost = Object.keys(both).filter((key) => !(key in returned));
  console.log(`   campos que orders-v1 no devolvió: ${lost.join(', ')}`);

  // 2. Después de contraer, el servicio nuevo ya no manda buyerName.
  const onlyNew = { buyerEmail: 'ana.ccori@correo.pe', givenName: 'Ana', familyName: 'Ccori', totalCents: 10000, currency: 'USD' };
  console.log('\n2. Una orden solo con los campos nuevos');
  console.log(`   se envía:  ${JSON.stringify(onlyNew)}`);
  const rejected = await post(`${service.url}/orders`, onlyNew);
  console.log(`   responde:  ${rejected.status} ${JSON.stringify(rejected.body)}`);

  // 3. En la tabla: una fila que ya tiene columnas nuevas, modificada por orders-v1.
  await db().query(`ALTER TABLE orders ADD COLUMN given_name text, ADD COLUMN family_name text, ADD COLUMN currency text NOT NULL DEFAULT 'PEN'`);
  const id = returned.id as number;
  await db().query(`UPDATE orders SET given_name = 'Ana', family_name = 'Ccori', currency = 'USD' WHERE id = $1`, [id]);
  console.log('\n3. La tabla ya tiene las columnas nuevas, y orders-v1 anula esa orden');
  const cancelled = await post(`${service.url}/orders/${id}/cancel`, {});
  console.log(`   responde:  ${cancelled.status} ${JSON.stringify(cancelled.body)}`);
  const row = await db().query('SELECT buyer_name, given_name, family_name, currency, status FROM orders WHERE id = $1', [id]);
  console.log(`   la fila:   ${JSON.stringify(row.rows[0])}`);

  // 4. Y una orden que orders-v1 crea mientras la tabla ya está expandida.
  const fromOld = await post(`${service.url}/orders`, { buyerEmail: 'raul.poma@correo.pe', buyerName: 'Raúl Poma', totalCents: 4500 });
  const oldRow = await db().query('SELECT buyer_name, given_name, family_name, currency FROM orders WHERE id = $1', [
    (fromOld.body as { order: { id: number } }).order.id,
  ]);
  console.log('\n4. orders-v1 crea una orden con la tabla ya expandida');
  console.log(`   la fila:   ${JSON.stringify(oldRow.rows[0])}`);
} finally {
  await service.close();
  await closeDb();
}
tools/lock-time.tsDescargar tools/lock-time.ts
import { readFile } from 'node:fs/promises';
import type pg from 'pg';
import { connect } from '../shared/db.ts';
import { FAMILY_NAME_SQL, GIVEN_NAME_SQL } from '../shared/split-name.ts';
import { numberFromEnv } from '../shared/settings.ts';
import { backfill } from './backfill-batches.ts';

// Cuánto tiempo deja esperando a los demás cada forma de migrar los datos.
// Mientras corre la migración, una sesión lee órdenes al azar y otra las
// modifica (como haría el servicio), y se anota la espera más larga de cada una.
//
//   make lock-time            usa su propia base de datos, arq_w09_lock
//   ROWS=1000000 BATCH=2000 make lock-time

const DATABASE = process.env.W09_LOCK_DB ?? 'arq_w09_lock';
const ROWS = numberFromEnv('ROWS', 300_000);
const BATCH = numberFromEnv('BATCH', 5000);

const file = (path: string): Promise<string> => readFile(new URL(`../${path}`, import.meta.url), 'utf8');

/** Deja la tabla orders como recién creada, en la versión 1 del esquema. */
async function resetOrders(admin: pg.Client): Promise<void> {
  await admin.query('DROP TABLE IF EXISTS orders');
  await admin.query(await file('db/schema.sql'));
  await admin.query((await file('db/seed.sql')).replaceAll(':rows', String(ROWS)));
}

type Probe = { stop(): Promise<number[]> };

/** Una sesión que repite una consulta sobre una orden al azar y mide cada vez. */
async function startProbe(sql: string): Promise<Probe> {
  const client = await connect(DATABASE);
  const waits: number[] = [];
  let running = true;
  const loop = (async () => {
    while (running) {
      const id = 1 + Math.floor(Math.random() * ROWS);
      const start = performance.now();
      await client.query(sql, [id]);
      waits.push(performance.now() - start);
    }
  })();
  return {
    stop: async () => {
      running = false;
      await loop;
      await client.end();
      return waits;
    },
  };
}

type Migration = { name: string; prepare?: (admin: pg.Client) => Promise<void>; run: (admin: pg.Client) => Promise<void> };

const addColumns = (admin: pg.Client): Promise<unknown> =>
  admin.query('ALTER TABLE orders ADD COLUMN given_name text, ADD COLUMN family_name text');

const migrations: Migration[] = [
  {
    name: 'todo en una transacción (errors/rename-in-one-step.sql)',
    run: async (admin) => void (await admin.query(await file('errors/rename-in-one-step.sql'))),
  },
  {
    name: 'un UPDATE de toda la tabla',
    prepare: async (admin) => void (await addColumns(admin)),
    run: async (admin) =>
      void (await admin.query(`UPDATE orders SET given_name = ${GIVEN_NAME_SQL}, family_name = ${FAMILY_NAME_SQL}`)),
  },
  {
    name: `lotes de ${BATCH} filas (tools/backfill-batches.ts)`,
    prepare: async (admin) => void (await addColumns(admin)),
    run: async (admin) => void (await backfill(admin, { batchSize: BATCH, pauseMs: 0 })),
  },
];

const ms = (value: number): string => `${value.toFixed(0)} ms`.padStart(9);

const admin = await connect(DATABASE);
try {
  console.log(`${ROWS} órdenes. Durante cada migración, una sesión lee y otra modifica órdenes al azar.\n`);
  console.log(`${'migración'.padEnd(58)}${'duró'.padStart(9)}  ${'lectura más lenta'.padStart(18)}  ${'escritura más lenta'.padStart(20)}`);
  for (const migration of migrations) {
    await resetOrders(admin);
    await migration.prepare?.(admin);
    const reader = await startProbe('SELECT status FROM orders WHERE id = $1');
    const writer = await startProbe('UPDATE orders SET status = status WHERE id = $1');
    const start = performance.now();
    await migration.run(admin);
    const elapsed = performance.now() - start;
    const reads = await reader.stop();
    const writes = await writer.stop();
    console.log(
      `${migration.name.padEnd(58)}${ms(elapsed)}  ${ms(Math.max(...reads)).padStart(18)}  ${ms(Math.max(...writes)).padStart(20)}`,
    );
  }
} finally {
  await admin.end();
}
tools/oltp-vs-olap.tsDescargar tools/oltp-vs-olap.ts
import { connect } from '../shared/db.ts';
import { numberFromEnv, settings } from '../shared/settings.ts';

// La misma base de datos atendiendo dos cargas. Primero solo la transaccional:
// varias sesiones leen una orden por su id, una tras otra. Después lo mismo,
// con sesiones analíticas que repiten un reporte que recorre toda la tabla.
//
//   make oltp-olap
//   ANALYTIC=14 SECONDS=10 make oltp-olap

const POINT_SESSIONS = numberFromEnv('POINT', 8);
const ANALYTIC_SESSIONS = numberFromEnv('ANALYTIC', 40);
const SECONDS = numberFromEnv('SECONDS', 5);

const POINT_SQL = 'SELECT id, buyer_email, total_cents, status FROM orders WHERE id = $1';
const REPORT_SQL = `SELECT buyer_email, count(*) AS orders, sum(total_cents) AS total_cents
                      FROM orders WHERE status = 'paid'
                     GROUP BY buyer_email ORDER BY sum(total_cents) DESC LIMIT 5`;

function percentile(sorted: number[], p: number): number {
  // Rango más cercano: el menor valor que deja debajo al menos p % de la muestra.
  return sorted[Math.max(0, Math.ceil((p / 100) * sorted.length) - 1)]!;
}

async function session(sql: string, params: () => unknown[], until: () => boolean): Promise<number[]> {
  const client = await connect();
  const times: number[] = [];
  try {
    while (!until()) {
      const start = performance.now();
      await client.query(sql, params());
      times.push(performance.now() - start);
    }
  } finally {
    await client.end();
  }
  return times;
}

async function phase(name: string, rows: number, analyticSessions: number): Promise<void> {
  const deadline = performance.now() + SECONDS * 1000;
  const done = (): boolean => performance.now() >= deadline;
  const analytic = Array.from({ length: analyticSessions }, () => session(REPORT_SQL, () => [], done));
  const point = Array.from({ length: POINT_SESSIONS }, () =>
    session(POINT_SQL, () => [1 + Math.floor(Math.random() * rows)], done),
  );
  const pointTimes = (await Promise.all(point)).flat().sort((a, b) => a - b);
  const reportTimes = (await Promise.all(analytic)).flat().sort((a, b) => a - b);
  const f = (value: number): string => value.toFixed(2).padStart(7);
  console.log(
    `${name.padEnd(34)} ${String(Math.round(pointTimes.length / SECONDS)).padStart(7)} lecturas/s   ` +
      `p50 ${f(percentile(pointTimes, 50))} ms   p95 ${f(percentile(pointTimes, 95))} ms   p99 ${f(percentile(pointTimes, 99))} ms` +
      (reportTimes.length > 0
        ? `   (${reportTimes.length} reportes, mediana ${percentile(reportTimes, 50).toFixed(0)} ms)`
        : ''),
  );
}

const probe = await connect();
const rows = Number((await probe.query<{ n: string }>('SELECT max(id) AS n FROM orders')).rows[0]!.n);
await probe.end();

console.log(`${settings.database}: ${rows} órdenes; ${POINT_SESSIONS} sesiones leen una orden por id durante ${SECONDS} s.\n`);
await phase('solo lecturas por id', rows, 0);
await phase(`con ${ANALYTIC_SESSIONS} ${ANALYTIC_SESSIONS === 1 ? 'sesión' : 'sesiones'} de reportes`, rows, ANALYTIC_SESSIONS);
await phase('solo lecturas por id, otra vez', rows, 0);
expand-contract/steps/0-initial.sqlDescargar expand-contract/steps/0-initial.sql
-- El ejemplo resuelto del apunte: una tabla de cupones cuya columna discount
-- (un porcentaje) va a pasar a llamarse percent_off.
DROP TABLE IF EXISTS coupons;
CREATE TABLE coupons (
    code     text    PRIMARY KEY,
    discount integer NOT NULL CHECK (discount BETWEEN 1 AND 100)
);
INSERT INTO coupons (code, discount) VALUES ('VERANO', 15), ('FIESTAS', 30);
expand-contract/steps/1-expand.sqlDescargar expand-contract/steps/1-expand.sql
-- Expandir: la columna nueva aparece junto a la vieja. Admite NULL, porque el
-- código antiguo, que sigue corriendo, no sabe que existe y no la va a llenar.
ALTER TABLE coupons
    ADD COLUMN percent_off integer CHECK (percent_off BETWEEN 1 AND 100);
expand-contract/steps/2-migrate.sqlDescargar expand-contract/steps/2-migrate.sql
-- Migrar: cuando ya no queda ninguna instancia del código antiguo, se copian
-- los datos que faltan y se intercambian las obligaciones: la columna nueva
-- pasa a ser obligatoria y la vieja deja de serlo, para que el código nuevo
-- pueda insertar sin ella.
UPDATE coupons SET percent_off = discount WHERE percent_off IS NULL;
ALTER TABLE coupons
    ALTER COLUMN percent_off SET NOT NULL,
    ALTER COLUMN discount DROP NOT NULL;
expand-contract/steps/3-contract.sqlDescargar expand-contract/steps/3-contract.sql
-- Contraer: cuando ya nadie lee ni escribe la columna vieja, se borra. Es el
-- único paso que destruye algo.
ALTER TABLE coupons DROP COLUMN discount;

Errores

Ejemplos con errores a propósito: no compilan, fallan o dan un resultado incorrecto. Los apuntes explican cada uno.

errors/currency-meaning.tsDescargar errors/currency-meaning.ts
import { purchaseScreen } from '../consumers/mobile-client.ts';

// Agregar currency es compatible en la forma: el cliente antiguo ignora el
// campo y sigue funcionando. Pero el significado de totalCents cambió, de
// "céntimos de sol" a "céntimos de la moneda que diga currency", y el cliente
// antiguo no se entera.
//
//   node errors/currency-meaning.ts

const order = {
  id: 300010,
  buyerEmail: 'ana.ccori@correo.pe',
  buyerName: 'Ana Ccori',
  givenName: 'Ana',
  familyName: 'Ccori',
  totalCents: 10000,
  currency: 'USD',
  status: 'paid',
  createdAt: '2026-11-16T15:00:00.000Z',
};

console.log(`El servicio responde: ${JSON.stringify(order)}`);
console.log('El cliente móvil antiguo muestra:');
for (const line of purchaseScreen(order)) console.log(`  ${line}`);
errors/rename-in-one-step.sqlDescargar errors/rename-in-one-step.sql
-- El cambio completo en un solo paso: columnas nuevas, datos copiados y
-- columna vieja borrada, todo en una transacción. Así se haría si el servicio
-- fuera el único que usa la tabla y se pudiera detener mientras tanto.
-- Ninguna de las dos cosas es cierta.
--
--   psql -d arq_w09 -f errors/rename-in-one-step.sql
--
-- Para deshacerlo: errors/undo-rename-in-one-step.sql, o make db (que borra
-- la base de datos y la crea de nuevo).

BEGIN;

ALTER TABLE orders
    ADD COLUMN given_name  text,
    ADD COLUMN family_name text,
    ADD COLUMN currency    text NOT NULL DEFAULT 'PEN';

-- El nombre es la primera palabra; el apellido, el resto.
UPDATE orders
   SET given_name  = split_part(buyer_name, ' ', 1),
       family_name = substr(buyer_name, length(split_part(buyer_name, ' ', 1)) + 2);

ALTER TABLE orders
    ALTER COLUMN given_name  SET NOT NULL,
    ALTER COLUMN family_name SET NOT NULL,
    DROP COLUMN buyer_name;

COMMIT;
errors/strict-reader.tsDescargar errors/strict-reader.ts
// Un cliente que valida la respuesta contra la lista exacta de campos que
// conocía cuando se escribió. Parece prudente y hace que agregar un campo, el
// cambio más inocente que existe, lo rompa.
//
//   node errors/strict-reader.ts

const KNOWN_FIELDS = ['id', 'buyerEmail', 'buyerName', 'totalCents', 'status', 'createdAt'];

export function strictRead(order: Record<string, unknown>): string {
  const extra = Object.keys(order).filter((key) => !KNOWN_FIELDS.includes(key));
  if (extra.length > 0) throw new Error(`Respuesta inesperada: campos desconocidos ${extra.join(', ')}`);
  return `Orden #${String(order.id)} de ${String(order.buyerName)}`;
}

export function tolerantRead(order: Record<string, unknown>): string {
  // Toma lo que necesita y no opina sobre lo demás.
  return `Orden #${String(order.id)} de ${String(order.buyerName)}`;
}

if (import.meta.main) {
  const before = { id: 7, buyerEmail: 'ana@correo.pe', buyerName: 'Ana Ccori', totalCents: 10000, status: 'paid', createdAt: '2026-03-01T15:00:00.000Z' };
  const after = { ...before, givenName: 'Ana', familyName: 'Ccori', currency: 'PEN' };
  console.log(`lector tolerante, respuesta de antes:   ${tolerantRead(before)}`);
  console.log(`lector tolerante, respuesta con campos nuevos: ${tolerantRead(after)}`);
  console.log(`lector estricto, respuesta de antes:    ${strictRead(before)}`);
  console.log(`lector estricto, respuesta con campos nuevos:`);
  strictRead(after);
}
errors/undo-rename-in-one-step.sqlDescargar errors/undo-rename-in-one-step.sql
-- Deshace errors/rename-in-one-step.sql. Se puede porque buyer_name se
-- reconstruye uniendo las dos partes; un cambio que destruye información no
-- tiene un archivo como este.
--
--   psql -d arq_w09 -f errors/undo-rename-in-one-step.sql

BEGIN;

ALTER TABLE orders ADD COLUMN buyer_name text;

UPDATE orders SET buyer_name = rtrim(given_name || ' ' || family_name);

ALTER TABLE orders
    ALTER COLUMN buyer_name SET NOT NULL,
    DROP COLUMN given_name,
    DROP COLUMN family_name,
    DROP COLUMN currency;

COMMIT;

Pruebas

Comprueban lo que afirman los apuntes; se ejecutan con make test.

consumers/mobile-client.test.tsDescargar consumers/mobile-client.test.ts
import assert from 'node:assert/strict';
import { after, before, test } from 'node:test';
import { closeDb } from '../shared/db.ts';
import { buy, showPurchase } from './mobile-client.ts';
import { ordersDir, startOrders, type RunningService } from './stage.ts';

// Lo que el cliente móvil antiguo necesita del servicio. NO SE MODIFICA en el
// laboratorio: si esta prueba deja de pasar, se rompió la aplicación de
// alguien que no puede actualizarla.

let service: RunningService;

before(async () => {
  service = await startOrders();
});

after(async () => {
  await service.close();
  await closeDb();
});

test(`[${ordersDir}] el cliente móvil antiguo muestra una orden que ya existía`, async () => {
  assert.deepEqual(await showPurchase(service.url, 1), [
    'Orden #1',
    'A nombre de: Víctor García',
    'Total: S/ 205.00',
    'Estado: pagada',
  ]);
});

test(`[${ordersDir}] el cliente móvil antiguo compra y ve su compra`, async () => {
  const id = await buy(service.url, { buyerEmail: 'luz.flores@correo.pe', buyerName: 'Luz Marina Flores', totalCents: 32000 });
  assert.deepEqual(await showPurchase(service.url, id), [
    `Orden #${id}`,
    'A nombre de: Luz Marina Flores',
    'Total: S/ 320.00',
    'Estado: pagada',
  ]);
});
consumers/sales-report.test.tsDescargar consumers/sales-report.test.ts
import assert from 'node:assert/strict';
import { after, test } from 'node:test';
import { closeDb, db } from '../shared/db.ts';
import { loadReport, reportFile } from './stage.ts';

// Lo que el equipo de reportes espera ver. NO SE MODIFICA en el laboratorio:
// el reporte puede cambiar por dentro, pero tiene que seguir diciendo lo mismo.
// Marzo de 2026 ya pasó, así que las órdenes nuevas no lo cambian.

after(closeDb);

test(`[${reportFile}] el reporte de marzo de 2026 dice lo mismo de siempre`, async () => {
  const salesReport = await loadReport();
  const report = await salesReport(db(), '2026-03');

  assert.equal(report.orders, 49147);
  assert.equal(report.totalCents, 823191500);
  assert.deepEqual(
    report.topBuyers.map((b) => ({ buyerName: b.buyerName, orders: b.orders, totalCents: b.totalCents })),
    [
      { buyerName: 'Rosa Quispe', orders: 697, totalCents: 11570500 },
      { buyerName: 'Juan Quispe', orders: 290, totalCents: 4937500 },
      { buyerName: 'Luz Marina Quispe', orders: 162, totalCents: 3217500 },
      { buyerName: 'María Quispe', orders: 222, totalCents: 3159500 },
      { buyerName: 'Carlos Quispe', orders: 187, totalCents: 2946000 },
    ],
  );
});
test/backfill.test.tsDescargar test/backfill.test.ts
import assert from 'node:assert/strict';
import { after, before, test } from 'node:test';
import { closeDb, db } from '../shared/db.ts';
import { backfill } from '../tools/backfill-batches.ts';

// El script por lotes, sobre la tabla de pruebas con las columnas nuevas
// agregadas solo mientras dura este archivo.

const pending = async (): Promise<number> =>
  Number((await db().query<{ n: string }>('SELECT count(*) AS n FROM orders WHERE given_name IS NULL')).rows[0]!.n);

before(async () => {
  await db().query('ALTER TABLE orders ADD COLUMN given_name text, ADD COLUMN family_name text');
});

after(async () => {
  await db().query('ALTER TABLE orders DROP COLUMN given_name, DROP COLUMN family_name');
  await closeDb();
});

test('si se interrumpe a la mitad, lo hecho queda hecho', async () => {
  const total = await pending();
  let batches = 0;
  await assert.rejects(
    backfill(db(), {
      batchSize: 20_000,
      pauseMs: 0,
      onBatch: () => {
        batches += 1;
        if (batches === 3) throw new Error('interrumpido');
      },
    }),
    /interrumpido/,
  );
  assert.equal(await pending(), total - 60_000);
});

test('al volver a correr termina lo que faltaba y no repite lo demás', async () => {
  const before = await pending();
  const result = await backfill(db(), { batchSize: 20_000, pauseMs: 0 });
  assert.equal(result.rows, before);
  assert.equal(await pending(), 0);

  const again = await backfill(db(), { batchSize: 20_000, pauseMs: 0 });
  assert.deepEqual({ rows: again.rows, batches: again.batches }, { rows: 0, batches: 0 });
});

test('las dos mitades, unidas, son el nombre original en todas las filas', async () => {
  const different = await db().query(
    `SELECT 1 FROM orders WHERE rtrim(given_name || ' ' || family_name) <> buyer_name LIMIT 1`,
  );
  assert.equal(different.rowCount, 0);
});
test/expand-contract.test.tsDescargar test/expand-contract.test.ts
import assert from 'node:assert/strict';
import { after, before, test } from 'node:test';
import type pg from 'pg';
import { applyStep, canCoexist, matrixOf, steps } from '../expand-contract/walkthrough.ts';
import { connect } from '../shared/db.ts';

let client: pg.Client;

before(async () => {
  client = await connect();
});

after(async () => {
  await client.query('DROP TABLE IF EXISTS coupons');
  await client.end();
});

test('en cada estado del esquema conviven dos versiones consecutivas del código, nunca la primera con la última', async () => {
  const coexisting: string[][] = [];
  for (const step of steps) {
    await applyStep(client, step);
    coexisting.push(canCoexist(await matrixOf(client)));
  }
  assert.deepEqual(coexisting, [['antigua'], ['antigua', 'puente'], ['puente', 'nueva'], ['nueva']]);
});

test('con la tabla solo expandida, la versión nueva no ve lo que escribe la antigua', async () => {
  await applyStep(client, '0-initial');
  await applyStep(client, '1-expand');
  const matrix = await matrixOf(client);
  assert.equal(matrix.antigua!.nueva, 'lee NULL');
  assert.equal(matrix.antigua!.puente, 'bien');
  assert.equal(matrix.nueva!.nueva, 'no escribe');
});

test('migrar no pierde ningún cupón', async () => {
  await applyStep(client, '0-initial');
  await applyStep(client, '1-expand');
  await applyStep(client, '2-migrate');
  await applyStep(client, '3-contract');
  const result = await client.query('SELECT code, percent_off FROM coupons ORDER BY code');
  assert.deepEqual(result.rows, [
    { code: 'FIESTAS', percent_off: 30 },
    { code: 'VERANO', percent_off: 15 },
  ]);
});
test/formats.test.tsDescargar test/formats.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { purchaseScreen } from '../consumers/mobile-client.ts';
import { strictRead, tolerantRead } from '../errors/strict-reader.ts';
import { cancelDroppingUnknown, cancelKeepingUnknown } from '../formats/document-roundtrip.ts';
import { decode, encode, orderV1, orderV2 } from '../formats/tagged.ts';

const newOrder = { id: 150, buyerName: 'Ana Ccori', totalCents: 32000, givenName: 'Ana', familyName: 'Ccori', currency: 'USD' };

test('JSON: un entero mayor que 2^53 no sobrevive a JSON.parse', () => {
  assert.equal(JSON.stringify(JSON.parse('{"id": 9007199254740993}')), '{"id":9007199254740992}');
});

test('formato con etiquetas: el campo 1 con valor 150 son los bytes 08 96 01', () => {
  assert.deepEqual([...encode({ 1: { name: 'id', type: 'int' } }, { id: 150 })], [0x08, 0x96, 0x01]);
});

test('hacia atrás: el lector nuevo lee un mensaje viejo; los campos nuevos simplemente no están', () => {
  const old = encode(orderV1, { id: 1, buyerName: 'Rosa Quispe', totalCents: 500 });
  assert.deepEqual(decode(orderV2, old), { known: { id: 1, buyerName: 'Rosa Quispe', totalCents: 500 }, unknown: [] });
});

test('hacia adelante: el lector viejo lee un mensaje nuevo saltando las etiquetas que no conoce', () => {
  const seen = decode(orderV1, encode(orderV2, newOrder));
  assert.deepEqual(seen.known, { id: 150, buyerName: 'Ana Ccori', totalCents: 32000 });
  assert.deepEqual(seen.unknown.map((field) => field.tag), [4, 5, 6]);
});

test('hacia adelante: si el lector viejo reescribe el mensaje, los campos nuevos sobreviven solo si los conserva', () => {
  const seen = decode(orderV1, encode(orderV2, newOrder));
  const kept = encode(orderV1, { ...seen.known, totalCents: 30000 }, seen.unknown);
  assert.deepEqual(decode(orderV2, kept).known, { ...newOrder, totalCents: 30000 });
  const dropped = encode(orderV1, { ...seen.known, totalCents: 30000 });
  assert.deepEqual(decode(orderV2, dropped).known, { id: 150, buyerName: 'Ana Ccori', totalCents: 30000 });
});

test('cambiar el nombre de un campo no cambia los bytes; reutilizar su etiqueta para otra cosa, sí rompe', () => {
  const renamed = { ...orderV1, 2: { name: 'fullName', type: 'string' as const } };
  assert.deepEqual(encode(renamed, { id: 1, fullName: 'Rosa Quispe', totalCents: 500 }), encode(orderV1, { id: 1, buyerName: 'Rosa Quispe', totalCents: 500 }));
  // Alguien reutiliza la etiqueta 2 para un número: el lector viejo ya no puede leer.
  const reused = { 1: orderV1[1]!, 2: { name: 'discountCents', type: 'int' as const }, 3: orderV1[3]! };
  assert.throws(() => decode(orderV1, encode(reused, { id: 1, discountCents: 100, totalCents: 500 })), /llegó con otro tipo/);
});

test('documento JSON: leer, modificar y guardar pierde lo desconocido, salvo que se lleve consigo', () => {
  const document = JSON.stringify({ id: 7, buyerName: 'Ana Ccori', totalCents: 10000, currency: 'USD', status: 'paid' });
  assert.equal('currency' in JSON.parse(cancelDroppingUnknown(document)), false);
  assert.deepEqual(JSON.parse(cancelKeepingUnknown(document)), { id: 7, buyerName: 'Ana Ccori', totalCents: 10000, currency: 'USD', status: 'cancelled' });
});

test('agregar un campo no rompe al lector tolerante y sí al que valida la lista exacta de campos', () => {
  const before = { id: 7, buyerEmail: 'ana@correo.pe', buyerName: 'Ana Ccori', totalCents: 10000, status: 'paid', createdAt: '2026-03-01T15:00:00.000Z' };
  const after = { ...before, currency: 'PEN' };
  assert.equal(tolerantRead(after), tolerantRead(before));
  assert.equal(strictRead(before), 'Orden #7 de Ana Ccori');
  assert.throws(() => strictRead(after), /campos desconocidos currency/);
});

test('currency es compatible en la forma y no en el significado: el cliente antiguo muestra dólares como soles', () => {
  const screen = purchaseScreen({ id: 9, buyerName: 'Ana Ccori', totalCents: 10000, currency: 'USD', status: 'paid' });
  assert.equal(screen[2], 'Total: S/ 100.00');
});
test/forward-compat.test.tsDescargar test/forward-compat.test.ts
import assert from 'node:assert/strict';
import { after, before, test } from 'node:test';
import { startOrders, type RunningService } from '../consumers/stage.ts';
import { closeDb } from '../shared/db.ts';

// Lo que orders-v1 hace con una orden que tiene la forma del contrato nuevo.

let service: RunningService;

async function post(body: unknown): Promise<{ status: number; order?: Record<string, unknown> }> {
  const response = await fetch(`${service.url}/orders`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { status: response.status, order: ((await response.json()) as { order?: Record<string, unknown> }).order };
}

before(async () => {
  service = await startOrders('orders-v1');
});

after(async () => {
  await service.close();
  await closeDb();
});

test('orders-v1 acepta una orden con campos que no conoce, y los pierde', async () => {
  const { status, order } = await post({ buyerEmail: 'ana.ccori@correo.pe', buyerName: 'Ana Ccori', givenName: 'Ana', familyName: 'Ccori', totalCents: 10000, currency: 'USD' });
  assert.equal(status, 201);
  assert.equal(order!.buyerName, 'Ana Ccori');
  for (const field of ['givenName', 'familyName', 'currency']) assert.equal(field in order!, false);
});

test('orders-v1 rechaza una orden que ya no trae buyerName', async () => {
  const { status } = await post({ buyerEmail: 'ana.ccori@correo.pe', givenName: 'Ana', familyName: 'Ccori', totalCents: 10000 });
  assert.equal(status, 422);
});
test/locks.test.tsDescargar test/locks.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import type pg from 'pg';
import { connect } from '../shared/db.ts';

// Qué bloquea a quién durante una migración. No se miden tiempos: una sesión
// deja una transacción abierta y la otra intenta su operación con
// lock_timeout, así que el resultado es siempre el mismo.

const LOCK_NOT_AVAILABLE = '55P03';

async function twoSessions(run: (migration: pg.Client, service: pg.Client) => Promise<void>): Promise<void> {
  const migration = await connect();
  const service = await connect();
  try {
    await service.query(`SET lock_timeout = '300ms'`);
    await migration.query('BEGIN');
    await run(migration, service);
  } finally {
    await migration.query('ROLLBACK');
    await migration.end();
    await service.end();
  }
}

test('un UPDATE sin confirmar deja leer la fila, pero no modificarla', async () => {
  await twoSessions(async (migration, service) => {
    await migration.query(`UPDATE orders SET buyer_name = buyer_name WHERE id <= 1000`);

    const read = await service.query('SELECT status FROM orders WHERE id = 500');
    assert.equal(read.rowCount, 1);

    await assert.rejects(service.query(`UPDATE orders SET status = 'cancelled' WHERE id = 500`), { code: LOCK_NOT_AVAILABLE });

    // Las filas que la migración no tocó siguen libres: por eso sirven los lotes.
    const other = await service.query(`UPDATE orders SET status = status WHERE id = 2000`);
    assert.equal(other.rowCount, 1);
  });
});

test('un ALTER TABLE sin confirmar no deja ni leer', async () => {
  await twoSessions(async (migration, service) => {
    await migration.query('ALTER TABLE orders ADD COLUMN probe text');

    await assert.rejects(service.query('SELECT status FROM orders WHERE id = 500'), { code: LOCK_NOT_AVAILABLE });
  });
});

test('un ALTER TABLE que espera detrás de una lectura larga hace esperar a todas las lecturas siguientes', async () => {
  const report = await connect();
  const migration = await connect();
  const service = await connect();
  try {
    // El reporte tiene una transacción abierta que ya leyó la tabla.
    await report.query('BEGIN');
    await report.query('SELECT count(*) FROM orders WHERE id <= 10');

    // La migración pide su lock y se queda en la cola.
    const pid = (await migration.query<{ pid: number }>('SELECT pg_backend_pid() AS pid')).rows[0]!.pid;
    const alter = migration.query('ALTER TABLE orders ADD COLUMN probe text').catch((error: unknown) => error);
    for (;;) {
      const waiting = await report.query('SELECT 1 FROM pg_locks WHERE pid = $1 AND NOT granted', [pid]);
      if (waiting.rowCount === 1) break;
      await new Promise((resolve) => setTimeout(resolve, 10));
    }

    // Una lectura cualquiera, que con el reporte solo habría pasado, ahora espera detrás del ALTER.
    await service.query(`SET lock_timeout = '300ms'`);
    await assert.rejects(service.query('SELECT status FROM orders WHERE id = 500'), { code: LOCK_NOT_AVAILABLE });

    // Se cancela la migración (es lo que haría su propio lock_timeout) y la cola se deshace.
    await report.query('SELECT pg_cancel_backend($1)', [pid]);
    assert.equal(((await alter) as { code?: string }).code, '57014');
    await report.query('ROLLBACK');
    assert.equal((await service.query('SELECT status FROM orders WHERE id = 500')).rowCount, 1);
  } finally {
    await report.end();
    await migration.end();
    await service.end();
  }
});
test/split-name.test.tsDescargar test/split-name.test.ts
import assert from 'node:assert/strict';
import { after, test } from 'node:test';
import { closeDb, db } from '../shared/db.ts';
import { FAMILY_NAME_SQL, GIVEN_NAME_SQL, joinName, splitName } from '../shared/split-name.ts';

after(closeDb);

test('la regla parte en la primera palabra', () => {
  assert.deepEqual(splitName('Rosa Quispe'), { givenName: 'Rosa', familyName: 'Quispe' });
  assert.deepEqual(splitName('Rosa Quispe Mamani'), { givenName: 'Rosa', familyName: 'Quispe Mamani' });
  assert.deepEqual(splitName('Madonna'), { givenName: 'Madonna', familyName: '' });
});

test('la regla se equivoca con los nombres compuestos, y no tiene cómo saberlo', () => {
  assert.deepEqual(splitName('Luz Marina Flores'), { givenName: 'Luz', familyName: 'Marina Flores' });
});

test('partir y volver a unir devuelve el nombre original, aunque se haya partido mal', () => {
  for (const name of ['Rosa Quispe', 'Luz Marina Flores', 'Madonna', 'José Luis Torres Huamán']) {
    const { givenName, familyName } = splitName(name);
    assert.equal(joinName(givenName, familyName), name);
  }
});

test('la regla en SQL y en TypeScript dicen lo mismo para todos los nombres de la tabla', async () => {
  const result = await db().query<{ buyer_name: string; given: string; family: string }>(
    `SELECT DISTINCT buyer_name, ${GIVEN_NAME_SQL} AS given, ${FAMILY_NAME_SQL} AS family FROM orders`,
  );
  assert.ok(result.rows.length >= 400);
  for (const row of result.rows) {
    assert.deepEqual(splitName(row.buyer_name), { givenName: row.given, familyName: row.family });
  }
});
test/timeline.test.tsDescargar test/timeline.test.ts
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { after, before, test } from 'node:test';
import type pg from 'pg';
import { connect } from '../shared/db.ts';
import { postSimple, postWithFanOut, readByQuery, readPrecomputed } from '../timeline/timeline.ts';

// Una red pequeña (300 usuarios) para comprobar que los dos diseños responden
// lo mismo y cuánto escribe cada uno.

const USERS = 300;
let client: pg.Client;

before(async () => {
  client = await connect();
  await client.query(`SET client_min_messages = warning`);
  const schema = await readFile(new URL('../timeline/schema.sql', import.meta.url), 'utf8');
  await client.query(schema.replaceAll(':users', String(USERS)));
});

after(async () => {
  await client.query('DROP TABLE IF EXISTS tl_home, tl_posts, tl_follows');
  await client.end();
});

test('calcular al leer y calcular al escribir muestran la misma línea de tiempo', async () => {
  for (const user of [2, 17, 150, 300]) {
    const computed = await readByQuery(client, user);
    assert.equal(computed.length, 20);
    assert.deepEqual(await readPrecomputed(client, user), computed);
  }
});

test('publicar con fan-out escribe la publicación y una fila por seguidor; para la cuenta famosa, una por usuario', async () => {
  const followers = async (id: number): Promise<number> =>
    Number((await client.query<{ n: string }>('SELECT count(*) AS n FROM tl_follows WHERE followee_id = $1', [id])).rows[0]!.n);
  const at = new Date('2026-11-01T12:00:00Z');
  assert.equal(await postWithFanOut(client, 17, 'hola', at), 1 + (await followers(17)));
  assert.equal(await followers(1), USERS - 1);
  assert.equal(await postWithFanOut(client, 1, 'hola a todos', new Date(at.getTime() + 1000)), USERS);
});

test('después de publicar, los dos diseños siguen de acuerdo', async () => {
  for (const user of [2, 17, 150]) {
    assert.deepEqual(await readPrecomputed(client, user), await readByQuery(client, user));
  }
});

test('si se publica sin fan-out, la línea de tiempo ya calculada queda atrasada: es un dato derivado', async () => {
  const postId = await postSimple(client, 1, 'sin repartir', new Date('2026-11-02T12:00:00Z'));
  assert.equal((await readByQuery(client, 150))[0]!.postId, postId);
  assert.notEqual((await readPrecomputed(client, 150))[0]!.postId, postId);
  // Y se puede reconstruir entera a partir de las tablas de origen.
  await client.query('TRUNCATE tl_home');
  await client.query(
    `INSERT INTO tl_home SELECT f.follower_id, p.created_at, p.id FROM tl_posts p JOIN tl_follows f ON f.followee_id = p.author_id`,
  );
  assert.deepEqual(await readPrecomputed(client, 150), await readByQuery(client, 150));
});

Laboratorio

Archivos de partida del laboratorio de la semana.

lab/compatibility-table.mdDescargar lab/compatibility-table.md
# Paso 2: ¿qué parte del cambio es compatible?

Para cada fila, marquen si el cambio es compatible **hacia atrás** (lo nuevo
entiende lo que produce lo viejo), **hacia adelante** (lo viejo entiende lo que
produce lo nuevo), ambas o ninguna, y con qué consumidor lo comprobarían.

## La API

| Cambio | Hacia atrás | Hacia adelante | Quién lo notaría |
|---|---|---|---|
| La respuesta agrega `givenName` y `familyName` | | | |
| La respuesta agrega `currency` | | | |
| La respuesta deja de traer `buyerName` | | | |
| La petición acepta `givenName` y `familyName` en vez de `buyerName` | | | |
| La petición exige `givenName` y `familyName` | | | |
| La petición acepta `currency`, opcional, con `PEN` por omisión | | | |
| `totalCents` pasa a estar en la moneda que diga `currency` | | | |

## La tabla

| Cambio | Hacia atrás | Hacia adelante | Quién lo notaría |
|---|---|---|---|
| Agregar `given_name` y `family_name`, que admiten `NULL` | | | |
| Agregar `currency` con `DEFAULT 'PEN'` | | | |
| Volver obligatorias `given_name` y `family_name` | | | |
| Borrar `buyer_name` | | | |

## Decisiones del paso 6

- ¿Cuánto tiempo se mantiene `buyerName` en la API? ¿De qué depende?
- ¿Qué cuenta el contador, exactamente? ¿Qué uso del campo viejo no vería?
- ¿Qué valor del contador, durante cuánto tiempo, autoriza a contraer?
lab/sales-report.tsDescargar lab/sales-report.ts
import type pg from 'pg';
import { closeDb, db } from '../shared/db.ts';

// Copia de trabajo del laboratorio: el reporte que se mueve a los campos nuevos
// en el paso 5 (consumers/sales-report.ts queda como estaba).
//
// El proceso de reportes. Lo escribió otro equipo y no pasa por la API: se
// conecta a la base de datos del servicio y lee la tabla orders directamente.
// Para ese equipo, las columnas de la tabla son el contrato.
//
//   node lab/sales-report.ts 2026-03

export type BuyerLine = { buyerName: string; orders: number; totalCents: number };
export type SalesReport = { month: string; orders: number; totalCents: number; topBuyers: BuyerLine[] };

/** Ventas pagadas de un mes (`2026-03`), en hora de Lima, y sus cinco mayores compradores. */
export async function salesReport(pool: pg.Pool, month: string): Promise<SalesReport> {
  const range = `created_at >= ($1 || '-01 00:00:00-05')::timestamptz
             AND created_at <  ($1 || '-01 00:00:00-05')::timestamptz + interval '1 month'`;
  const totals = await pool.query<{ orders: string; total_cents: string }>(
    `SELECT count(*) AS orders, coalesce(sum(total_cents), 0) AS total_cents
       FROM orders WHERE status = 'paid' AND ${range}`,
    [month],
  );
  const buyers = await pool.query<{ buyer_name: string; orders: string; total_cents: string }>(
    `SELECT buyer_name, count(*) AS orders, sum(total_cents) AS total_cents
       FROM orders WHERE status = 'paid' AND ${range}
      GROUP BY buyer_email, buyer_name
      ORDER BY sum(total_cents) DESC, buyer_email
      LIMIT 5`,
    [month],
  );
  return {
    month,
    orders: Number(totals.rows[0]!.orders),
    totalCents: Number(totals.rows[0]!.total_cents),
    topBuyers: buyers.rows.map((row) => ({
      buyerName: row.buyer_name,
      orders: Number(row.orders),
      totalCents: Number(row.total_cents),
    })),
  };
}

export function formatReport(report: SalesReport): string {
  const soles = (cents: number): string => `S/ ${(cents / 100).toFixed(2)}`;
  return [
    `Ventas de ${report.month}: ${report.orders} órdenes pagadas, ${soles(report.totalCents)}`,
    'Mayores compradores:',
    ...report.topBuyers.map((b) => `  ${b.buyerName.padEnd(24)} ${String(b.orders).padStart(4)} órdenes  ${soles(b.totalCents)}`),
  ].join('\n');
}

if (import.meta.main) {
  try {
    console.log(formatReport(await salesReport(db(), process.argv[2] ?? '2026-03')));
  } finally {
    await closeDb();
  }
}
lab/migrations/01-expand.sqlDescargar lab/migrations/01-expand.sql
-- Paso 4 del laboratorio: expandir.
--
-- Agreguen aquí las columnas nuevas (given_name, family_name, currency) sin
-- quitar ni cambiar nada de lo que existe. Después de aplicar este archivo,
-- orders-v1 y los dos consumidores tienen que seguir funcionando sin tocarlos:
--
--   psql -d arq_w09 -v ON_ERROR_STOP=1 -f lab/migrations/01-expand.sql
--   make consumers            (todavía contra orders-v1)
--
-- Piensen qué pasa con cada columna nueva cuando orders-v1, que no la conoce,
-- inserta una fila.
lab/migrations/02-migrate.sqlDescargar lab/migrations/02-migrate.sql
-- Paso 5 del laboratorio: migrar.
--
-- Los datos de las filas antiguas se llenan con make backfill (el script por
-- lotes), no aquí. En este archivo va lo que cambia en el esquema cuando los
-- datos ya están completos y ya no corre ninguna instancia de orders-v1: qué
-- columnas pasan a ser obligatorias y cuáles dejan de serlo.
--
--   psql -d arq_w09 -v ON_ERROR_STOP=1 -f lab/migrations/02-migrate.sql
lab/migrations/03-contract.sqlDescargar lab/migrations/03-contract.sql
-- Paso 7 del laboratorio: contraer.
--
-- Solo cuando el contador del servicio dice que nadie usa el campo viejo y
-- el reporte ya lee las columnas nuevas.
--
--   psql -d arq_w09 -v ON_ERROR_STOP=1 -f lab/migrations/03-contract.sql
lab/orders/main.tsDescargar lab/orders/main.ts
import { closeDb } from '../../shared/db.ts';
import { log, settings } from '../../shared/settings.ts';
import { createOrdersServer } from './server.ts';

const server = createOrdersServer();
server.listen(settings.port, () => {
  log('orders-lab', `escuchando en http://localhost:${settings.port} (base de datos ${settings.database})`);
});

// Con Ctrl+C se deja de aceptar pedidos y se cierra el pool; si no, el proceso no termina.
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
  process.on(signal, () => {
    server.close(() => void closeDb());
    server.closeAllConnections();
  });
}
lab/orders/server.tsDescargar lab/orders/server.ts
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { AppError, orderIdFrom, readJson, sendError, sendJson } from '../../shared/http.ts';
import { log } from '../../shared/settings.ts';
import { cancelOrder, findOrder, insertOrder, type NewOrder } from './store.ts';

// Copia de trabajo del laboratorio: empieza idéntica a orders-v1 y es la que
// se modifica. orders-v1 y los consumidores no se tocan.
//
// El contrato que usan hoy el cliente móvil y cualquier otro cliente:
//
//   POST /orders             { buyerEmail, buyerName, totalCents }  -> 201 { order }
//   GET  /orders/:id                                                -> 200 { order }
//   POST /orders/:id/cancel                                         -> 200 { order }
//
// order = { id, buyerEmail, buyerName, totalCents, status, createdAt }

function parseNewOrder(body: unknown): NewOrder {
  // Solo se miran los campos que el servicio conoce; cualquier otro se ignora.
  const input = (typeof body === 'object' && body !== null ? body : {}) as Record<string, unknown>;
  const { buyerEmail, buyerName, totalCents } = input;
  const valid =
    typeof buyerEmail === 'string' &&
    buyerEmail.includes('@') &&
    typeof buyerName === 'string' &&
    buyerName.trim().length > 0 &&
    Number.isInteger(totalCents) &&
    (totalCents as number) >= 0;
  if (!valid) {
    throw new AppError(422, 'INVALID_INPUT', 'Se espera { buyerEmail, buyerName, totalCents }');
  }
  return { buyerEmail: buyerEmail as string, buyerName: (buyerName as string).trim(), totalCents: totalCents as number };
}

async function route(request: IncomingMessage, response: ServerResponse): Promise<number> {
  const { pathname } = new URL(request.url ?? '/', 'http://localhost');
  const method = request.method ?? 'GET';

  if (method === 'GET' && pathname === '/health') {
    sendJson(response, 200, { status: 'ok', version: 'orders-lab' });
    return 200;
  }
  if (method === 'POST' && pathname === '/orders') {
    const order = await insertOrder(parseNewOrder(await readJson(request)));
    sendJson(response, 201, { order });
    return 201;
  }
  const id = orderIdFrom(pathname);
  if (method === 'GET' && id !== undefined) {
    const order = await findOrder(id);
    if (!order) throw new AppError(404, 'ORDER_NOT_FOUND', `No existe la orden ${id}`);
    sendJson(response, 200, { order });
    return 200;
  }
  const cancelId = orderIdFrom(pathname, '/cancel');
  if (method === 'POST' && cancelId !== undefined) {
    const order = await cancelOrder(cancelId);
    if (!order) throw new AppError(404, 'ORDER_NOT_FOUND', `No existe la orden ${cancelId}`);
    sendJson(response, 200, { order });
    return 200;
  }
  throw new AppError(404, 'NOT_FOUND', `No existe ${method} ${pathname}`);
}

/** El servidor de órdenes, todavía sin escuchar en ningún puerto. */
export function createOrdersServer(): Server {
  return createServer((request, response) => {
    route(request, response)
      .catch((error: unknown) => {
        const status = sendError(response, error);
        if (status === 500) log('orders-lab', `error: ${String(error)}`);
        return status;
      })
      .then((status) => log('orders-lab', `${request.method} ${request.url} ${status}`));
  });
}
lab/orders/store.tsDescargar lab/orders/store.ts
import { db } from '../../shared/db.ts';

// Lo único que sabe de la tabla orders dentro del servicio. Cada consulta
// nombra sus columnas: un SELECT * cambiaría de forma el día en que alguien
// agregue una columna.

export type Order = {
  id: number;
  buyerEmail: string;
  buyerName: string;
  totalCents: number;
  status: 'paid' | 'cancelled';
  createdAt: string;
};

export type NewOrder = { buyerEmail: string; buyerName: string; totalCents: number };

type OrderRow = {
  id: number;
  buyer_email: string;
  buyer_name: string;
  total_cents: number;
  status: 'paid' | 'cancelled';
  created_at: Date;
};

const COLUMNS = 'id, buyer_email, buyer_name, total_cents, status, created_at';

function toOrder(row: OrderRow): Order {
  return {
    id: row.id,
    buyerEmail: row.buyer_email,
    buyerName: row.buyer_name,
    totalCents: row.total_cents,
    status: row.status,
    createdAt: row.created_at.toISOString(),
  };
}

export async function insertOrder(input: NewOrder): Promise<Order> {
  const result = await db().query<OrderRow>(
    `INSERT INTO orders (buyer_email, buyer_name, total_cents) VALUES ($1, $2, $3) RETURNING ${COLUMNS}`,
    [input.buyerEmail, input.buyerName, input.totalCents],
  );
  return toOrder(result.rows[0]!);
}

export async function findOrder(id: number): Promise<Order | undefined> {
  const result = await db().query<OrderRow>(`SELECT ${COLUMNS} FROM orders WHERE id = $1`, [id]);
  const row = result.rows[0];
  return row ? toOrder(row) : undefined;
}

export async function cancelOrder(id: number): Promise<Order | undefined> {
  const result = await db().query<OrderRow>(
    `UPDATE orders SET status = 'cancelled' WHERE id = $1 RETURNING ${COLUMNS}`,
    [id],
  );
  const row = result.rows[0];
  return row ? toOrder(row) : undefined;
}

Compilación

Cómo se compilan y ejecutan los ejemplos.

MakefileDescargar Makefile
# Semana 9: los datos como decisión de arquitectura. Un servicio de órdenes
# (orders-v1) con dos consumidores que no controlamos, y un cambio de contrato
# que hay que hacer sin romperlos. Se usa dentro del contenedor del curso.
#
#   make                 crea la base de datos arq_w09 (versión 1, 300 000 órdenes)
#   make start           levanta orders-v1 en http://localhost:3000
#   make start S=lab     levanta la copia de trabajo del laboratorio (lab/orders)
#   make consumers       las pruebas de los dos consumidores contra orders-v1 y arq_w09
#   make consumers S=lab las mismas pruebas contra lab/orders y lab/sales-report.ts
#   make report          el reporte de ventas de marzo (S=lab: el del laboratorio)
#   make backfill        llena given_name y family_name por lotes (BATCH=5000 PAUSE_MS=0)
#   make lock-time       cuánto hace esperar cada forma de migrar (usa arq_w09_lock)
#   make forward         orders-v1 recibe órdenes escritas por el servicio nuevo (usa arq_w09_fwd)
#   make expand-contract el ejemplo resuelto del apunte: cambiar el nombre de una columna
#   make oltp-olap       lecturas por id con y sin reportes pesados en la misma base de datos
#   make timeline        calcular al leer o al escribir, medido (usa arq_w09_timeline)
#   make models          el mismo pedido en tablas y como documento
#   make formats         JSON y un formato binario con etiquetas
#   make test            revisa los tipos (tsc) y corre las pruebas (usa arq_w09_test)
#   make clean           borra las bases de datos de la semana
#
# S elige contra qué se corre: v1 (por omisión) o lab. También se pueden dar
# las rutas a mano: make consumers ORDERS_DIR=lab/orders REPORT=consumers/sales-report.ts
#
# Los archivos de consumers/ y orders-v1/ no se modifican en el laboratorio.

ROWS ?= 300000
USERS ?= 10000
S ?= v1
ifeq ($(S),lab)
ORDERS_DIR ?= lab/orders
REPORT ?= lab/sales-report.ts
else
ORDERS_DIR ?= orders-v1
REPORT ?= consumers/sales-report.ts
endif
# psql no avisa cuando la base de datos que se va a borrar todavía no existe.
PGOPTIONS = --client-min-messages=warning
export PGOPTIONS ORDERS_DIR REPORT ROWS

DATABASES = arq_w09 arq_w09_test arq_w09_sol arq_w09_lock arq_w09_fwd arq_w09_timeline

# $(call create_db,nombre,filas): la base de datos recién creada, en la versión 1.
define create_db
	@psql -q -d postgres -c "DROP DATABASE IF EXISTS $(1) WITH (FORCE)" -c "CREATE DATABASE $(1)"
	@psql -q -d $(1) -v ON_ERROR_STOP=1 -f db/schema.sql
	@psql -q -d $(1) -v ON_ERROR_STOP=1 -v rows=$(2) -f db/seed.sql
endef

.PHONY: all db start consumers report backfill lock-time forward expand-contract oltp-olap timeline models formats test clean

all: db

db:
	$(call create_db,arq_w09,$(ROWS))
	@echo "Base de datos arq_w09 recién creada: $(ROWS) órdenes, esquema de la versión 1."

start:
	node $(ORDERS_DIR)/main.ts

consumers:
	W09_LOG=off node --test --test-concurrency=1 "consumers/*.test.ts"

report:
	@node $(REPORT) 2026-03

backfill:
	@node tools/backfill-batches.ts

lock-time:
	@psql -q -d postgres -c "DROP DATABASE IF EXISTS arq_w09_lock WITH (FORCE)" -c "CREATE DATABASE arq_w09_lock"
	@node tools/lock-time.ts

forward:
	$(call create_db,arq_w09_fwd,1000)
	@W09_DB=arq_w09_fwd W09_LOG=off node tools/forward-compat.ts

expand-contract:
	@node expand-contract/walkthrough.ts

oltp-olap:
	@node tools/oltp-vs-olap.ts

timeline:
	@psql -q -d postgres -c "DROP DATABASE IF EXISTS arq_w09_timeline WITH (FORCE)" -c "CREATE DATABASE arq_w09_timeline"
	@psql -q -d arq_w09_timeline -v ON_ERROR_STOP=1 -v users=$(USERS) -f timeline/schema.sql
	@node timeline/measure.ts

models:
	@psql -d arq_w09 -f models/models.sql

formats:
	@node formats/json-numbers.ts
	@echo
	@node formats/tagged.ts
	@echo
	@node formats/document-roundtrip.ts

# Las pruebas usan sus propias bases de datos: no tocan arq_w09, así que se
# pueden correr en cualquier momento del laboratorio. La solución del
# laboratorio, cuando está publicada, se prueba aparte.
test:
	tsc -p .
	$(call create_db,arq_w09_test,300000)
	W09_DB=arq_w09_test W09_LOG=off ORDERS_DIR=orders-v1 REPORT=consumers/sales-report.ts \
	  node --test --test-concurrency=1 "consumers/*.test.ts" "test/*.test.ts"
	@if [ -d solution ]; then \
	  psql -q -d postgres -c "DROP DATABASE IF EXISTS arq_w09_sol WITH (FORCE)" -c "CREATE DATABASE arq_w09_sol" && \
	  psql -q -d arq_w09_sol -v ON_ERROR_STOP=1 -f db/schema.sql && \
	  psql -q -d arq_w09_sol -v ON_ERROR_STOP=1 -v rows=300000 -f db/seed.sql && \
	  W09_DB=arq_w09_sol W09_LOG=off node --test --test-concurrency=1 "solution/*.test.ts"; \
	fi

clean:
	@for database in $(DATABASES); do \
	  psql -q -d postgres -c "DROP DATABASE IF EXISTS $$database WITH (FORCE)"; \
	done
	@echo "Bases de datos de la semana 9 borradas."
package.jsonDescargar package.json
{
  "name": "week-09",
  "private": true,
  "type": "module"
}
tsconfig.jsonDescargar tsconfig.json
{
  "compilerOptions": {
    "target": "es2024",
    "lib": ["es2024"],
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "types": ["node"],
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true
  },
  "include": ["shared", "orders-v1", "consumers", "errors", "lab", "solution", "tools", "test", "expand-contract", "timeline", "formats"]
}