gioser

hifas · los hilos con que crece un hongo · sheafsync · cuaderno de laboratorio

hifas · the threads a fungus grows with · sheafsync · lab notebook

hifas

Decide, con demostración y no a ojo, cuándo un conjunto de copias puede trabajar sin coordinarse — y cuando la respuesta es que sí dentro de ciertos límites, entrega el mecanismo que los sostiene, con el precio exacto de cada límite escrito.

Decides, with a proof rather than by eye, when a set of replicas can work without coordinating — and when the answer is yes within limits, it hands over the mechanism that holds them, with the exact price of each limit written down.

resumen

abstract

hifas empezó como una conjetura: que la cohomología de un haz celular sobre el grafo de réplicas coincide con lo que el teorema CALM predice sobre la coordinación. La conjetura se sometió a prueba con un oráculo independiente, fase por fase, y no sobrevivió en su forma fuerte: el motor lineal medía la topología del grafo y no la semántica del dato; la versión sobre retículos acertaba porque leía la respuesta; y la «separación respecto de CALM» que se llegó a anunciar era detección tardía con un punto ciego. Lo que quedó en pie es más modesto y más útil: evitación de coordinación por escrow, con un certificado que aguanta concurrencia, particiones y caídas, ruteada por el grafo de comunicación real, y un enunciado de seguridad que nombra el único supuesto físico del que depende.

hifas began as a conjecture: that the cohomology of a cellular sheaf over the replica graph coincides with what the CALM theorem predicts about coordination. The conjecture was tested against an independent oracle, phase by phase, and did not survive in its strong form: the linear engine measured the topology of the graph, not the semantics of the data; the lattice version was right because it was reading the answer; and the «separation from CALM» once announced was late detection with a blind spot. What stands is more modest and more useful: coordination avoidance by escrow, with a certificate that survives concurrency, partitions and crashes, routed over the real communication graph, and a safety statement that names the single physical assumption it rests on.

89tests: unitarios, de propiedades y de integracióntests: unit, property and integration
8fases, cada una con su documentophases, each with its own document
3reclamos retirados, con fecha y motivoclaims withdrawn, dated and explained
1supuesto físico nombradonamed physical assumption

Contenido

Contents

  1. La preguntaThe question
  2. Marco teóricoTheoretical frame
  3. El motor lineal y su falso positivoThe linear engine and its false positive
  4. Retículos: un acierto circularLattices: a circular success
  5. Detectar no es evitarDetecting is not avoiding
  6. Escrow: el certificadoEscrow: the certificate
  7. Seguro en movimientoSafe in motion
  8. La frontera física: el clonThe physical boundary: the clone
  9. El resultado y su contratoThe result and its contract
  10. Varios invariantes a la vezSeveral invariants at once
  11. El cuaderno, sin adornosThe notebook, undecorated
  12. Lo que queda abiertoWhat remains open
  13. ReferenciasReferences

01 · la preguntathe question

¿Hacía falta coordinar?

Was coordination needed?

Dos personas con la misma aplicación abierta y sin red entre ellas van a hacer cambios. Cuando la red vuelve, alguien tiene que decidir si los dos cambios pueden convivir. La respuesta corriente es coordinar antes —pedir permiso a un servidor, tomar un candado, correr un consenso— y eso deja sin trabajar a quien no tiene red. En un sistema local-first, donde la copia propia es la fuente de verdad y la red es una visita, esa respuesta es justo la que no sirve.

Two people with the same application open and no network between them are going to make changes. When the network comes back, somebody has to decide whether both changes can coexist. The usual answer is to coordinate first — ask a server, take a lock, run a consensus — and that leaves whoever has no network unable to work. In a local-first system, where one's own copy is the source of truth and the network is a visitor, that is exactly the answer that does not work.

hifas contesta la pregunta anterior: dado un conjunto de réplicas que editan copias locales de un estado compartido, ¿cuándo se pueden fundir esas copias en un estado global coherente sin coordinación, y cuándo existe una obstrucción que obliga a sincronizar? Para muchos invariantes la respuesta es que no hace falta, y se puede demostrar. Para los que sí —un saldo que no puede quedar negativo, un identificador que no puede repetirse— hifas no se limita a decir «coordina»: entrega un mecanismo con el que cada copia sabe cuánto puede hacer sola sin romper el invariante común, y mientras se mantenga adentro de su parte no necesita hablar con nadie.

hifas answers the question before that one: given a set of replicas editing local copies of a shared state, when can those copies be merged into a coherent global state without coordination, and when is there an obstruction that forces a sync? For many invariants coordination is not needed, and that can be proved. For the ones where it is — a balance that cannot go negative, an identifier that cannot repeat — hifas does not stop at «coordinate»: it hands over a mechanism by which each copy knows how much it can do alone without breaking the shared invariant, and while it stays inside its share it never needs to talk to anyone.

02 · marco teóricotheoretical frame

Tres teorías que hablan de lo mismo

Three theories about the same thing

CRDT (Shapiro, Preguiça, Baquero y Zawirski, 2011). Tipos de datos replicados cuya fusión es el join de un semirretículo: conmutativa, asociativa e idempotente. El ejemplo mínimo es el G-Counter: cada réplica incrementa sólo su casilla y fundir es tomar el máximo casilla por casilla. Nunca hay conflicto porque nunca se resta.

CRDTs (Shapiro, Preguiça, Baquero and Zawirski, 2011). Replicated data types whose merge is the join of a semilattice: commutative, associative and idempotent. The minimal example is the G-Counter: each replica only increments its own slot, and merging takes the slot-wise maximum. There is never a conflict because nothing is ever subtracted.

CALM (Hellerstein y Alvaro). Un programa admite una implementación consistente sin coordinación si y sólo si es monótono: sólo agrega conocimiento, nunca lo retracta. Borrar, reiniciar, sobrescribir o negar la vuelven necesaria. I-confluence (Bailis et al., VLDB 2014) es el refinamiento que mira el invariante: un conjunto de transacciones es I-confluente respecto de I si fundir dos estados válidos con un ancestro común da siempre un estado válido, y esa es la condición necesaria y suficiente para ejecutarlas sin coordinar.

CALM (Hellerstein and Alvaro). A program has a consistent coordination-free implementation if and only if it is monotone: it only adds knowledge, never retracts it. Deleting, resetting, overwriting or negating make coordination necessary. I-confluence (Bailis et al., VLDB 2014) is the refinement that looks at the invariant: a set of transactions is I-confluent with respect to I if merging two valid states with a common ancestor always yields a valid state, and that is the necessary and sufficient condition for running them without coordination.

Haces celulares (Hansen y Ghrist, 2019). Sobre el grafo de réplicas —el nervio— un haz asigna a cada réplica v su espacio de estado local F(v), a cada arista e el espacio del dato que esas dos réplicas comparten, y a cada incidencia un mapa de restricción que proyecta el estado de la réplica sobre ese dato. Con eso se arma el operador de cofrontera y su cohomología:

Cellular sheaves (Hansen and Ghrist, 2019). Over the replica graph — the nerve — a sheaf assigns each replica v its local state space F(v), each edge e the space of the datum those two replicas share, and each incidence a restriction map projecting the replica's state onto that datum. From that one builds the coboundary operator and its cohomology:

(δx)ₑ = F(u ⊴ e)·xᵤ − F(v ⊴ e)·xᵥ e = (u, v) H⁰ = ker δ estados globales coherentescoherent global states H¹ = C¹ / im δ obstrucciones a pegar lo localobstructions to gluing the local dim H¹ = dim C¹ − rank δ

La apuesta del proyecto —la Hipótesis H— era que, para un estado codificado linealmente, H¹ = 0 sobre el grafo de réplicas si y sólo si la configuración admite fusión sin coordinación. No es un teorema publicado: es una conjetura, y el proyecto se organizó para refutarla si era falsa. El criterio de éxito de cada pieza fue un test que pasa, nunca que «se vea bien»; el primero, obligatorio, fue que para el haz constante la cohomología reproduzca la topología del grafo: dim H⁰ = componentes·d y dim H¹ = β₁·d.

The project's bet — Hypothesis H — was that, for a linearly encoded state, H¹ = 0 over the replica graph if and only if the configuration admits coordination-free merging. It is not a published theorem: it is a conjecture, and the project was organised to refute it if it was false. The success criterion for every piece was a passing test, never that it «looks right»; the first, mandatory one was that for the constant sheaf the cohomology reproduces the graph's topology: dim H⁰ = components·d and dim H¹ = β₁·d.

03 · MVP lineal (M0–M3)linear MVP (M0–M3)

El motor lineal medía topología

The linear engine measured topology

Con aritmética exacta sobre GF(2) y un oráculo CRDT/CALM independiente, el motor lineal coincidió con el oráculo en toda una batería de más de veinte casos —compartición monótona acíclica y cualquier configuración no monótona— y discrepó en una familia precisa: un dato monótono compartido sobre un grafo con ciclos. Tres réplicas que comparten un G-Counter en triángulo no tienen nada que coordinar: el máximo casilla por casilla siempre existe y es único. El haz, sin embargo, reporta una obstrucción.

With exact arithmetic over GF(2) and an independent CRDT/CALM oracle, the linear engine agreed with the oracle across a battery of more than twenty cases — acyclic monotone sharing and any non-monotone configuration — and disagreed on one precise family: a monotone datum shared over a graph with cycles. Three replicas sharing a G-Counter in a triangle have nothing to coordinate: the slot-wise maximum always exists and is unique. The sheaf, however, reports an obstruction.

haz lineallinear sheaf r₀r₁r₂ H¹ β₁ = E − V + C = 3 − 3 + 1 = 1 «coordina» ✗«coordinate» ✗ semántica del dato (CALM)data semantics (CALM) r₀r₁r₂ max join = max ⟹ siempre pegaalways glues «corre libre» ✓«runs free» ✓
Figura 1. El mismo triángulo visto por las dos lentes. La codificación lineal convierte cada dato compartido en una restricción de acuerdo, y sobre un ciclo el haz constante tiene H¹ = β₁ = 1 sin importar qué dato viaja. CALM mira la fusión: un máximo nunca entra en conflicto.
Figure 1. The same triangle through both lenses. The linear encoding turns each shared datum into an agreement constraint, and on a cycle the constant sheaf has H¹ = β₁ = 1 no matter what datum travels. CALM looks at the merge: a maximum never conflicts.

La causa es la resta del cofrontera. Un semirretículo no tiene inversos; al linealizarlo, δ mide un desacuerdo que no existe e inventa obstrucciones alrededor de cada ciclo. Bajo esa codificación, H¹ = 0 ⟺ el grafo de compartición es acíclico: un enunciado puramente topológico. El error es conservador —el haz pide coordinar de más, nunca de menos; no se observó el fallo inverso—, pero es un error: el instrumento no estaba mirando el dato.

The cause is the subtraction in the coboundary. A semilattice has no inverses; once linearised, δ measures a disagreement that does not exist and invents obstructions around every cycle. Under that encoding, H¹ = 0 ⟺ the sharing graph is acyclic: a purely topological statement. The error is conservative — the sheaf asks for too much coordination, never too little; the reverse failure was never observed — but it is an error: the instrument was not looking at the data.

04 · retículos y Tarski (T5–T8a)lattices and Tarski (T5–T8a)

Un acierto perfecto que era circular

A perfect score that was circular

La cura natural fue quitar la resta: haces valuados en retículos, con las restricciones como conexiones de Galois, y el Laplaciano de Tarski (Ghrist y Riess, 2022) difundido hasta un punto fijo. El punto fijo es la mejor reconciliación coherente; la configuración corre libre si lo preserva sin colapsar al tope. Con esto el triángulo monótono dejó de ser un falso positivo, y el acuerdo con el oráculo pasó a ser total, sin excepción.

The natural cure was to remove the subtraction: lattice-valued sheaves, with restrictions as Galois connections, and the Tarski Laplacian (Ghrist and Riess, 2022) diffused to a fixed point. The fixed point is the best coherent reconciliation; a configuration runs free if it preserves it without collapsing to the top. With this the monotone triangle stopped being a false positive, and agreement with the oracle became total, without exception.

Un acuerdo perfecto con CALM es también exactamente lo que produce una codificación circular, y la pieza que cargaba el peso lo delataba: la «generación» de cada registro se sembraba con la componente del subgrafo monótono, o sea, la codificación leía la etiqueta monótono/reset —la misma información que usa CALM— y con ella fabricaba la incomparabilidad que hacía colapsar los reinicios. Era un espejo, no un teorema.

Perfect agreement with CALM is also exactly what a circular encoding produces, and the load-bearing piece gave it away: each register's «generation» was seeded with the component of the monotone subgraph, i.e. the encoding read the label monotone/reset — the very information CALM uses — and used it to fabricate the incomparability that made resets collapse. It was a mirror, not a theorem.

La corrección (T8a) derivó el orden mecánicamente de la fusión, sin tocar la etiqueta:

The correction (T8a) derived the order mechanically from the merge, without touching the label:

join(a, b) := merge(a, b) a ≤ b :⟺ merge(a, b) = b

Bajo ese orden un registro last-writer-wins es una cadena, y en una cadena la difusión siempre reconcilia al máximo. Ocho veredictos se dieron vuelta, todos en el mismo sentido —de «coordina» a «corre libre»—, y ninguno al revés. Es correcto e incómodo a la vez: todo CRDT puro corre libre en cualquier grafo, con ciclos incluidos, y la pista de retículos, tal como estaba, no medía nada que CALM no midiera. La obstrucción real no vive en el tipo de dato: vive en un invariante global que la fusión no preserva.

Under that order a last-writer-wins register is a chain, and on a chain diffusion always reconciles to the maximum. Eight verdicts flipped, all in the same direction — from «coordinate» to «runs free» — and none the other way. It is correct and uncomfortable at once: every pure CRDT runs free on any graph, cycles included, and the lattice track, as it stood, measured nothing CALM did not. The real obstruction does not live in the data type: it lives in a global invariant that the merge does not preserve.

05 · I-confluence (T8) y su retractación (T9)I-confluence (T8) and its retraction (T9)

Detectar no es evitar

Detecting is not avoiding

T8 añadió el invariante: con los estados válidos V = {s : I(s)}, el veredicto pasó a ser «corre libre ⟺ el punto fijo cae en V». Con una cuenta de 100 y el invariante saldo ≥ 0, retiros de 10 y 10 corrían libres y retiros de 60 y 60 pedían coordinar: el mismo programa, veredictos distintos según los valores. Se anunció como la «versión fuerte», un instrumento más fino que CALM. Ese reclamo era falso y está retirado.

T8 added the invariant: with the valid states V = {s : I(s)}, the verdict became «runs free ⟺ the fixed point lands in V». With an account of 100 and the invariant balance ≥ 0, withdrawals of 10 and 10 ran free and withdrawals of 60 and 60 asked for coordination: the same program, different verdicts depending on the values. It was announced as the «strong version», an instrument finer than CALM. That claim was false and has been withdrawn.

Por dos razones. Primera: fundir dos estados ya divergidos y comprobar el resultado es detección reactiva, no evitación; si los retiros fueron de 60, ya se aceptaron, y repararlos es compensación, que es coordinación. Y I-confluence cuantifica sobre todos los estados alcanzables: «retirar con saldo ≥ 0» no es I-confluente porque existe un 60/60 que rompe el invariante, igual que dice CALM. Segunda, peor: el invariante era global pero se había codificado sobre aristas de a pares, y al partir el grafo la restricción desaparecía del haz justo cuando el acoplamiento seguía intacto.

For two reasons. First: merging two already-diverged states and checking the result is reactive detection, not avoidance; if the withdrawals were 60 each they have already been accepted, and repairing them is compensation, which is coordination. And I-confluence quantifies over all reachable states: «withdraw with balance ≥ 0» is not I-confluent because a 60/60 exists that breaks the invariant, just as CALM says. Second, and worse: the invariant was global but had been encoded over pairwise edges, and when the graph split the constraint vanished from the sheaf exactly while the coupling remained.

cuenta de 100 · invariante saldo ≥ 0 · dos réplicas sin redaccount of 100 · invariant balance ≥ 0 · two replicas, no network r₀r₁ ✕ −60−60 100 − 120 = −20 detector (T8)detector (T8) «corre libre» — no ve el acople«runs free» — blind to the coupling escrow [50, 50] (T9)escrow [50, 50] (T9) rechaza: puede gastar 50rejects: may spend 50 el caso más peligroso, reportado como segurothe most dangerous case, reported as safe
Figura 2. La fila 3 de COMPARISON.md, verificada por tests/comparison.rs. Sin aristas no queda ninguna restricción en el haz, y el detector da verde sobre un sobregiro de 20. El escrow no depende de que haya arista: el presupuesto de cada réplica es suyo.
Figure 2. Row 3 of COMPARISON.md, verified by tests/comparison.rs. With no edges no constraint is left in the sheaf, and the detector gives a green light to a 20 overdraft. Escrow does not depend on an edge existing: each replica's budget is its own.
#EscenarioScenarioRetirosWithdrawalsDetector (T8)Detector (T8)Escrow [50, 50] (T9)
1conectado, cabenconnected, fits10, 10corre libreruns freelocallocal
2conectado, sobregiroconnected, overdraft60, 60coordinacoordinaterebalanceorebalance
3particionado, sobregiropartitioned, overdraft60, 60corre libre ⚠runs free ⚠rebalanceorebalance
4particionado, cabenpartitioned, fits10, 10corre libreruns freelocallocal

06 · escrow (T9)

Repartir antes, en vez de reparar después

Share out first instead of repairing later

La evitación real tiene nombre desde hace cuarenta años: el método de escrow (O'Neil, 1986), materializado como Bounded Counter por Balegas y coautores (SRDS 2015). Para un invariante valor ≥ K se calcula la holgura global, se reparte en presupuestos por réplica, y cada réplica gasta lo suyo sin preguntarle a nadie —también particionada—. La única coordinación aparece cuando una réplica agota su parte y pide presupuesto a un vecino: local, entre dos, nunca un consenso global.

Real avoidance has had a name for forty years: the escrow method (O'Neil, 1986), materialised as the Bounded Counter by Balegas and co-authors (SRDS 2015). For an invariant value ≥ K one computes the global slack, splits it into per-replica budgets, and each replica spends its own without asking anyone — partitioned too. The only coordination appears when a replica exhausts its share and asks a neighbour for budget: local, between two, never a global consensus.

S = valorvalue − K holguraslack Σᵢ bᵢ ≤ S, bᵢ ≥ 0 reparto válidovalid split spentᵢ ≤ bᵢ ∀i ⟹ valorvalue = inicialinitial − Σ spentᵢ ≥ inicialinitial − Σ bᵢ ≥ inicialinitial − S = K

Ese es el certificado, y vale para toda ejecución, todo orden de fusión y toda partición: no se descubre tarde, se garantiza por construcción. Escrow tampoco «vence» a CALM: transforma la operación —de «retirar sin límite», que no es I-confluente, a «retirar dentro del presupuesto», que sí lo es— a cambio de un rebalanceo ocasional.

That is the certificate, and it holds for every execution, every merge order and every partition: it is not discovered late, it is guaranteed by construction. Escrow does not «beat» CALM either: it transforms the operation — from «withdraw without limit», which is not I-confluent, to «withdraw within budget», which is — in exchange for an occasional rebalance.

holgura S = 100 − 0, repartida en [50, 50]slack S = 100 − 0, split into [50, 50] spent₀ = 30b₀ = 50 spent₁ = 20b₁ = 50 0 = K100 r₀ pide 40 más:r₀ asks for 40 more: con ruta → 20 propios + 20 rebalanceados desde r₁ · Spentwith a route → its own 20 + 20 rebalanced from r₁ · Spent sin ruta → Rejected { spendable: 20 }no route → Rejected { spendable: 20 } En ningún orden ni partición el valor baja de K: Σ spent ≤ Σ b ≤ S.In no order or partition does the value drop below K: Σ spent ≤ Σ b ≤ S.
Figura 3. El certificado, dibujado. Cada réplica gasta dentro de su franja; la suma de las franjas no puede pasar la holgura. Un gasto que no cabe se cubre por rebalanceo si hay ruta, o se rechaza diciendo cuánto sí se puede gastar —nunca se sobregira y nunca se cuelga. (Valores ilustrativos sobre la cuenta de 100 de los tests.)
Figure 3. The certificate, drawn. Each replica spends within its band; the sum of the bands cannot exceed the slack. A spend that does not fit is covered by rebalancing if there is a route, or rejected stating how much can be spent — never an overdraft, never a hang. (Illustrative values over the tests' account of 100.)

Donde el grafo sí se gana el sueldo: el ruteo

Where the graph does earn its keep: routing

El presupuesto es una 0-cocadena sobre las réplicas, y un rebalanceo es un flujo por las aristas que conserva el total, así que el certificado no se toca. La presión para rebalancear es el gradiente de presupuesto a través de las aristas, y el Laplaciano del grafo lo suaviza de manera proactiva para que las réplicas rara vez lleguen a cero; cuando una se seca, se localiza el flujo mínimo que la repone desde vecinas con excedente. Es la misma máquina lineal que en el MVP era un detector con falso positivo, ahora puesta en el problema correcto.

The budget is a 0-cochain over the replicas, and a rebalance is a flow along edges that conserves the total, so the certificate is untouched. The pressure to rebalance is the budget gradient across edges, and the graph Laplacian smooths it proactively so replicas rarely reach zero; when one runs dry, the minimal flow that refills it from neighbours with surplus is located. It is the same linear machine that in the MVP was a detector with a false positive, now applied to the right problem.

x ← x − α·L·x L = D − A 1ᵀL = 0 ⟹ Σ x se conservais conserved
antesbefore 7020 1030 Σ = 130 diffuse despuésafter 4535 2822 Σ = 130
Figura 4. Cuatro réplicas en camino. La difusión mueve presupuesto sólo por aristas existentes y conserva la suma: no crea disponibilidad, la reparte para que ninguna réplica quede seca frente a su demanda. Es rendimiento, no corrección: el certificado aguanta cualquier reparto válido. (Valores ilustrativos.)
Figure 4. Four replicas on a path. Diffusion moves budget only along existing edges and conserves the sum: it does not create availability, it spreads it so no replica runs dry against its demand. It is performance, not correctness: the certificate holds for any valid split. (Illustrative values.)

07 · escrow dinámico (T10)dynamic escrow (T10)

Seguro en movimiento, no sólo en una foto

Safe in motion, not just in a snapshot

El certificado de T9 valía para un reparto congelado y probado en secuencia. T10 cerró la brecha entre lo estático y lo dinámico con un presupuesto con procedencia: cada transferencia vive entera en su celda (granted[from][to], monótona), cada gasto también (spent[i], monótono), y lo disponible se deriva. Como la suma de lo disponible no depende de las transferencias, es imposible fabricar presupuesto al fusionar e imposible perderlo en una caída.

T9's certificate held for a frozen split tested sequentially. T10 closed the gap between static and dynamic with a budget with provenance: each transfer lives whole in its own cell (granted[from][to], monotone), each spend too (spent[i], monotone), and what is available is derived. Since the sum of what is available does not depend on the transfers, it is impossible to fabricate budget by merging and impossible to lose it in a crash.

Σᵢ availᵢ = Σᵢ b0ᵢ − Σᵢ spentᵢ (invariante a todo grant)(invariant under every grant)

El teorema se prueba entrelazando gastos, transferencias concurrentes, caídas y particiones en órdenes de fusión arbitrarios: valor = inicial − Σ spent ≥ K en todo momento, y lo disponible total nunca es negativo. Bajo partición, si no hay ruta hacia excedente el gasto se rechaza y la réplica queda limitada a su presupuesto local: con la cuenta de 100 repartida en [50, 50], una réplica aislada que pide 60 recibe Rejected { spendable: 50 }; conectada, recibe Spent (50 propios y 10 de la vecina). Es CAP en su forma cotidiana: bajo partición se sacrifica consistencia o disponibilidad, y el escrow elige, explícitamente, no sobregirar. No promete liveness: que un rechazo se convierta en gasto depende de que la red vuelva.

The theorem is tested by interleaving spends, concurrent transfers, crashes and partitions in arbitrary merge orders: value = initial − Σ spent ≥ K at every moment, and total availability is never negative. Under partition, if there is no route to surplus the spend is rejected and the replica is limited to its local budget: with the account of 100 split [50, 50], an isolated replica asking for 60 gets Rejected { spendable: 50 }; connected, it gets Spent (50 of its own and 10 from its neighbour). It is CAP in its everyday form: under partition one gives up consistency or availability, and escrow explicitly chooses not to overdraw. It promises no liveness: whether a rejection becomes a spend depends on the network coming back.

08 · fuente monótona (T11)monotone source (T11)

La frontera física: el clon

The physical boundary: the clone

El teorema de T10 daba por hecho que cada spent es durable y monótono en su origen. T11 lo nombró y lo defendió en tres partes. Durabilidad: un gasto sólo se confirma después de escribirse en un registro adelantado (WAL); al recuperarse, spent vuelve como mínimo al último confirmado, y un retroceso por debajo se rechaza. Una réplica por dispositivo: la identidad es un conjunto de celdas, cada una con un solo escritor, así que dos dispositivos de la misma persona gastan sin serializarse. El clon: un dispositivo restaurado en dos copias vivas que no se hablan.

T10's theorem took for granted that every spent is durable and monotone at its source. T11 named that and defended it in three parts. Durability: a spend is acknowledged only after being written to a write-ahead log; on recovery, spent returns to at least the last acknowledged value, and a rollback below it is refused. One replica per device: identity is a set of cells, each with a single writer, so two devices of the same person spend without serialising. The clone: a device restored into two live copies that do not talk.

Ningún mecanismo local puede detectar un clon silencioso antes de que los clones se comuniquen. No local mechanism can detect a silent clone before the clones communicate.

Es CAP otra vez, ahora dentro de una celda. Lo mejor posible —y lo que hace hifas— es acotar y delatar: cada arranque incrementa una época propia del dispositivo, persistida en el WAL; el gasto se indexa por dispositivo y época; y al fusionar, dos linajes del mismo dispositivo con épocas distintas delatan el clon. La época es local a propósito: una época global pediría consenso, que es justo lo que se evita. A diferencia del fencing token clásico, que supone un recurso linealizable que rechaza tokens viejos, acá el control vive en la fusión, y por eso la garantía es más débil y está dicha tal cual.

It is CAP again, now inside a single cell. The best possible — and what hifas does — is to bound and expose: each boot increments a device-local epoch, persisted in the WAL; spends are indexed by device and epoch; and on merge, two lineages of the same device with different epochs expose the clone. The epoch is local on purpose: a global epoch would require consensus, which is exactly what is being avoided. Unlike the classic fencing token, which assumes a linearisable resource that rejects stale tokens, here enforcement lives in the merge, so the guarantee is weaker and is stated as such.

d · e3 snapshot e4 e3′ gasta ≤ bspends ≤ b gasta ≤ b (doble gasto)spends ≤ b (double spend) sin redno network merge CloneDetected sobregiro ≤ una celdaoverspend ≤ one cell
Figura 5. Sin fencing, el doble gasto de un clon es silencioso e ilimitado. Con fencing por época queda acotado a una celda por clon no detectado —overspend() ≤ budget, verificado por propiedades— y se delata al reconectar. CloneDetected es una alarma, no una recuperación: el daño de esa celda ya ocurrió, y compensarlo es coordinación de la capa de aplicación, que puede fracasar.
Figure 5. Without fencing, a clone's double spend is silent and unbounded. With epoch fencing it is bounded to one cell per undetected clone — overspend() ≤ budget, property-tested — and exposed on reconnect. CloneDetected is an alarm, not a recovery: that cell's damage has already happened, and compensating it is application-layer coordination, which may fail.

09 · el resultado (M4)the result (M4)

El enunciado honesto, y el contrato que lo sostiene

The honest statement, and the contract that holds it

Seguridad sin coordinación, módulo un supuesto físico nombrado: cada celda de presupuesto tiene un único escritor durable. Bajo ese supuesto, el certificado dinámico aplica sin coordinar. Si se rompe —una copia clonada—, el daño queda acotado a una celda por clon no detectado, y se detecta al reconectar. Nunca silencioso ni ilimitado. Coordination-free safety, modulo one named physical assumption: each budget cell has a single durable writer. Under that assumption the dynamic certificate applies with no coordination. If it is broken — a cloned replica — the damage is bounded to one cell per undetected clone, and it is detected on reconnect. Never silent, never unbounded.

No es «seguro pase lo que pase», sino «seguro salvo esta condición física, y aquí está exactamente qué cuesta romperla». Todo eso se congeló detrás de una API, SovereignAccount, que tawasuyu consume en producción. Su contrato rehúsa antes de prometer de más:

Not «safe no matter what», but «safe unless this physical condition breaks, and here is exactly what breaking it costs». All of it was frozen behind an API, SovereignAccount, which tawasuyu consumes in production. Its contract refuses rather than over-promise:

CláusulaClauseCómo se cumpleHow it holds
Requiere WAL durable por dispositivoRequires a durable per-device WALopen rehúsa con NoDurabilityopen refuses with NoDurability
Requiere identidad = conjunto de dispositivosRequires identity = set of devicesopen rehúsa con NoDeviceIdentityopen refuses with NoDeviceIdentity
Garantiza el invariante sin coordinarGuarantees the invariant without coordinatingvalue() ≥ floor en toda ejecuciónin every execution
Acota y delata el clon (no lo previene)Bounds and exposes the clone (does not prevent it)sync → CloneDetected
Limita la disponibilidad bajo particiónLimits availability under partitionspend → Rejected { spendable }

10 · alcance multi-invariante (experimental)multi-invariant reach (experimental)

Varios invariantes a la vez

Several invariants at once

Balegas señala como no resuelto el caso de restricciones sobre varios contadores a la vez. Se atacó de frente, y con el Laplaciano de haces vectorial a propósito, aceptando el riesgo de repetir el patrón. El resultado: la corrección no necesita haces. Basta un escrow por restricción sobre el politopo: presupuesto vectorial por dispositivo, y un gasto es seguro localmente si cabe en el presupuesto de cada restricción que toca.

Balegas flags constraints over several counters at once as unsolved. It was attacked head-on, and with the vector sheaf Laplacian on purpose, accepting the risk of repeating the pattern. The outcome: correctness does not need sheaves. An escrow per constraint over the polytope suffices: a vector budget per device, and a spend is locally safe if it fits the budget of every constraint it touches.

C ≥ 0, C·Σᵥ bᵥ ≤ slack, sᵥ ≤ bᵥ ⟹ C·consumed ≤ slack Lhazsheaf = Lgrafograph ⊗ I (restricciones identidad)(identity restrictions) ker L = los totales conservadosthe conserved totals = H⁰

Con las restricciones que tiene un presupuesto real —la identidad—, difundir un presupuesto vectorial es literalmente correr el ruteador escalar una vez por recurso. El haz sólo se separaría de eso con restricciones no triviales: dispositivos que miden recursos acoplados en bases incompatibles, un requisito que ningún sistema de presupuestos conocido tiene. Lo único genuinamente bonito es una conexión: el núcleo del Laplaciano son las cantidades que la difusión conserva, el mismo H⁰ del primer motor. Es interpretación, no un teorema nuevo.

With the restrictions a real budget has — the identity — diffusing a vector budget is literally running the scalar router once per resource. The sheaf would only separate from that with non-trivial restrictions: devices measuring coupled resources in incompatible bases, a requirement no known budget system has. The only genuinely beautiful thing is a connection: the kernel of the Laplacian is the quantities diffusion conserves, the very H⁰ of the first engine. It is interpretation, not a new theorem.

11 · el cuadernothe notebook

El arco, sin adornos

The arc, without decoration

FasePhasePrometíaPromisedTerminó siendoTurned out to beDocumentoDocument
MVP linealLinear MVPdetectar coordinación por H¹detect coordination via H¹medía topología (H¹ = β₁); falso positivo en ciclosmeasured topology (H¹ = β₁); false positive on cyclesDISCREPANCIES
RetículosLatticescerrar la brechaclose the gapcircular: la codificación leía la etiquetacircular: the encoding read the labelFLIPS
I-confluencesuperar a CALMbeat CALMdetección, no evitación; punto ciegodetection, not avoidance; blind spotSTRONG_RESULT
Escrowevitación realreal avoidancecertificado sobre el politopo, ruteo por el grafocertificate over the polytope, routing over the graphT9 · COMPARISON
Escrow dinámicoDynamic escrowseguro en una fotosafe in a snapshotseguro bajo concurrencia, partición y caídasafe under concurrency, partition and crashT10 · AVAILABILITY
Fuente monótonaMonotone sourceseguro sin mássafe, full stopseguro módulo un supuesto físico nombradosafe modulo one named physical assumptionT11 · BOUNDARY
AdaptadorAdapter—API congelada; rehúsa si no hay durabilidadfrozen API; refuses without durabilityM4
Multi-invarianteMulti-invariantnovedad vía hacesnovelty via sheavescorrección = escrow; el haz colapsa al ruteador escalarcorrectness = escrow; the sheaf collapses to the scalar routerREACH

El patrón se repitió hasta el final y conviene nombrarlo: cada vez que el haz fue protagonista, no fue lo que sostuvo la garantía. La corrección vino del trabajo previo del área bien implementado —CRDT, CALM, I-confluence, escrow— y de nombrar con precisión las fronteras; el haz fue, en el mejor de los casos, una lente o una comodidad de ruteo. Nada de lo que queda es novedad teórica: es O'Neil 1986, Balegas 2015 y Bailis 2014 bien implementados, conscientes de la topología y honestos sobre sus límites.

The pattern repeated to the end and is worth naming: every time the sheaf took the lead, it was not what held the guarantee. Correctness came from the field's prior art implemented well — CRDTs, CALM, I-confluence, escrow — and from naming the boundaries precisely; the sheaf was, at best, a lens or a routing convenience. Nothing that remains is theoretical novelty: it is O'Neil 1986, Balegas 2015 and Bailis 2014 implemented well, topology-aware and honest about their limits.

Un cuaderno de laboratorio confiable vale más que un resultado fuerte reclamado de más. A trustworthy lab notebook is worth more than a strong result claimed too loudly.

Cada reclamo que hubo que retirar está escrito en los documentos de diseño, con su fecha y su motivo, y se conserva a propósito.

Every claim that had to be withdrawn is written in the design documents, with its date and its reason, and is kept on purpose.

12 · estadostatus

Qué hay hoy, y lo que queda abierto

What exists today, and what remains open

A lo que apunta

What it aims at

13 · referenciasreferences

Sobre los hombros de

On the shoulders of

  1. M. Shapiro, N. Preguiça, C. Baquero, M. Zawirski. A Comprehensive Study of Convergent and Commutative Replicated Data Types. INRIA, 2011.
  2. J. M. Hellerstein, P. Alvaro. Keeping CALM: When Distributed Consistency is Easy. Communications of the ACM, 2020.
  3. P. Bailis, A. Fekete, M. J. Franklin, A. Ghodsi, J. M. Hellerstein, I. Stoica. Coordination Avoidance in Database Systems. VLDB, 2014. arXiv:1402.2237.
  4. P. E. O'Neil. The Escrow Transactional Method. ACM Transactions on Database Systems, 1986.
  5. V. Balegas, D. Serra, S. Duarte, C. Ferreira, M. Shapiro, R. Rodrigues, N. Preguiça. Extending Eventually Consistent Cloud Databases for Enforcing Numeric Invariants. SRDS, 2015.
  6. J. Hansen, R. Ghrist. Toward a Spectral Theory of Cellular Sheaves. Journal of Applied and Computational Topology, 2019.
  7. R. Ghrist, H. Riess. Cellular Sheaves of Lattices and the Tarski Laplacian. Homology, Homotopy and Applications, 2022.
  8. R. Ghrist. Elementary Applied Topology. 2014.
  9. M. Kleppmann. Designing Data-Intensive Applications. O'Reilly, 2017 (tokens de fencingfencing tokens).

tawasuyu.net ↗