# Revision Compatibility and Historical Replay

## 1. Status and Purpose

This is a design record with an implemented offline checker (Section 9),
`request_time()` (Section 3) and deprecated API admission (Section 4).
[Managed Local Source Migration](migration.md) now supplies a strict, no-pending
activation protocol. Timestamp-gated history and replay-only deprecated
APIs are the agreed approaches. State migration, semantic projections and
more general activation policies remain design requirements and open questions.

The current runtime rejects a database whose program fingerprint differs from
the supplied program. A new deployment has independent state. Neither behavior
should be silently relaxed outside the explicit migration protocol. See
[API Server Semantics](api_server_semantics.md) for current durability and
external-call behavior.

The goal is to let a new program explain an existing history correctly. This is
not limited to transferring the old program's final memory into the new one.
Historical behavior can remain in the program, selected by recorded request
metadata or by the historical API name.

## 2. The Smallest Example

The original program is valid current TSP:

```tsp
let total = 0

start() {
}

api add(amount: number) {
  total = total + amount
  return ok(total)
}
```

Two distinct requests execute in order:

| Request | Outcome | Committed state |
| --- | --- | --- |
| `add(5)` | `ok(5)` | `total = 5` |
| `add(-2)` | `ok(3)` | `total = 3` |

The desired new rule rejects negative additions. Installing that rule without a
historical branch would reject the second request during replay, changing both
its outcome and the final state. Starting a fresh deployment would instead reset
the state to zero. Neither is the intended compatible upgrade: retain three,
then enforce the new rule for new requests.

## 3. Approach One: Recorded Request Time

The runtime assigns a timestamp to admitted API requests. `request_time()` exposes
that original time, rather than a continually advancing wall clock, during API
execution and replay. It returns an exact integer of Unix nanoseconds, persisted
as a signed 64-bit integer. The following uses implemented TSP syntax:

```tsp
let total = 0

start() {
}

api add(amount: number) {
  if request_time() >= 1800000000000000000 {
    if amount < 0 {
      return error("Amount must not be negative.")
    }
  }
  total = total + amount
  return ok(total)
}
```

Both historical requests predate the cutoff, so replay still returns five and
three. A new negative request at or after the cutoff returns an error without
changing three. Equality belongs to the new branch.

Required properties:

- The runtime assigns and durably binds the timestamp to the original request
  before execution. It is not a client-controlled business argument.
- Replay and UUID retry retain the original timestamp. A retry is not a new
  request and does not reclassify the request under the current date.
- The cutoff is an explicit policy constant, for example an intended deployment
  activation time. It is not recomputed on every compile or restart.
- Timestamp precision does not imply uniqueness or establish execution order.
  The journal's execution order must still be preserved.

Admission time is sampled under the server lock, after JSON/identity validation
and completed-UUID lookup, and durably committed with a pending intent before
the API body runs. Helpers share the request context. Initialization and
non-server execution cannot read it. A request admitted before the cutoff still
takes the old branch even if it completes afterwards. Clock rollback is not
clamped; clocks outside the signed 64-bit Unix-nanosecond range are rejected.

Old journals without time metadata remain valid for paths that do not need it.
If a checked historical path evaluates `request_time()` without recorded time,
the checker reports `unverifiable`; it never substitutes completion time or the
current clock. Runtime recovery similarly fails rather than inventing time.
See [API Server Semantics](api_server_semantics.md#10-deferred-decisions-and-current-implementation)
for pending-request and storage failure boundaries. A cutoff earlier than actual deployment may
also reclassify requests accepted by the old program; compatibility checking must
detect that discrepancy rather than assume a deployment-time label is enough.

## 4. Approach Two: Replay-Only Deprecated APIs

Where a time branch is awkward, retain the old API and introduce a new one.
The declarations and bodies below use implemented TSP syntax:

```tsp
let total = 0

start() {
}

deprecated api add(amount: number) {
  total = total + amount
  return ok(total)
}

api add2(amount: number) {
  if amount < 0 {
    return error("Amount must not be negative.")
  }
  total = total + amount
  return ok(total)
}
```

The required runtime policy is:

| Operation | Required behavior |
| --- | --- |
| Replay committed historical `add` | Execute its retained historical body |
| New request to `add` | Reject before executing its body |
| Matching retry of an already completed `add` UUID | Return its original recorded outcome |
| Recovery of already-admitted pending `add` | Finish the retained body with its original request context |
| New request to `add2` | Execute the new rule |

Thus replay restores three, and a new `add2(-2)` fails without mutation.
An old UUID reused with different request data is still a conflict, not an
exception to identity checking. Deprecation must not break a legitimate retry.

The same modifier works on queries: `deprecated readonly api get_total()`.
Readonly historical outcomes still participate in compatibility checking.
Discovery retains deprecated declarations, adding `deprecated: true`; active
declarations omit the field. An otherwise valid new call receives HTTP 410 with
`ok: false`, `phase: "admission"` and `error.code: "APIDeprecated"`. Rejection is
before parameter decoding/execution and creates no request-history entry.
Malformed transport requests and identity errors retain their earlier checks.

The modifier itself implements admission and retained-body behavior, not upgrade activation.
The offline checker still refuses snapshots with pending work, and ordinary
startup still refuses a changed source fingerprint. Handling unresolved work
while changing revisions remains part of the future upgrade protocol; the
pending recovery rule is not permission to bypass those guards.

Cross-version pending recovery is explicitly deferred. See
[Pending Requests Across Source Upgrades](pending_request_upgrades.md) for the
uncertain-external-call problem, shutdown versus upgrade boundaries, and future
options that have not been adopted.

## 5. Compatibility Is More Than Successful Execution

There are three distinct intentions; they must not silently share one approval
criterion:

1. Preserve historical behavior with the same state representation.
2. Change the representation while preserving relevant observable behavior.
3. Intentionally correct an old bug, accepting specified historical differences.

Completing replay without an interpreter exception is only a minimum check.
For the counter, a historical `ok(3)` becoming an ordinary `error(...)` is a
compatibility failure even though both are valid API outcomes.

With an unchanged representation, the default expectation is equal reconstructed
state and equal historical outcomes. An intentional correction must identify
the accepted differences explicitly; it must not be mislabeled as unchanged
semantics. Previously delivered UUID results cannot simply be overwritten to
match a new calculation. How correction interacts with those durable results
requires a separate decision.

### Readonly Observations

The user's stronger observational criterion includes historical readonly calls:
they should yield the same values against the corresponding reconstructed
historical states, even when internal memory differs. Checking only the final
state or returning cached readonly replies does not demonstrate this property.

Current recovery does not re-execute readonly calls or final failures. However,
the SQLite request journal already stores their API names, arguments, results
and shared `seq` order alongside successful mutations. The runtime serializes
API execution, so this order places each observation at its historical state.
The offline checker uses that complete order, rather than the mutation-only
recovery reader. A matching UUID retry does not append a second execution record;
even a request without a client key receives an internal key and is recorded.
This covers finalized calls reaching the runtime, not transport-level rejections.

The existing `ts_unix_ms` is a completion-time millisecond timestamp. It is not
the frozen admission time now stored separately in `request_times.unix_ns` and
accessible through `request_time()`. Legacy rows are not backfilled.

Even checking all recorded observations establishes compatibility for that
history, not a proof that every possible future query is equivalent.

### Changed Data Representation

Let `s1` be the old state and `s2` the new state. For every agreed property `p`,
require `p(s1) = p(s2)`. Where the representations differ, the old and new
programs need corresponding observation/projection functions expressing the same
property; raw memory equality is not the test.

Examples include the same open-chore count, the same titles for stable chore IDs,
or the same balance for each account. Choosing these properties still requires
domain judgment. A finite property suite is evidence, not a universal proof.

## 6. Migration, start(), and Fingerprints

An offline migration program with the server stopped is a legitimate baseline.
Using `start()` to express migration is an idea to investigate, not a decided
extension of its current initialization role. It would need explicit answers:

- Which old state and types are accessible, and when relative to replay?
- Does initialization create a new representation from history, or transform an
  existing snapshot? How is applying both accidentally prevented?
- How is migration recorded exactly once across crashes and restarts?
- How are failed validation, rollback and subsequent recovery handled?

Type-theoretic work should inform this design: structural type compatibility,
explicit conversions, abstraction relations between representations, and
refinement obligations may support useful checks or proofs. The specific type
system, proof machinery and fingerprint format are not chosen here.

A source fingerprint establishes identity, not semantic equivalence. Equal state
types also do not establish behavioral compatibility: the counter changes no
types. A future admission decision may combine exact identity, structural checks,
replay evidence, property checks and explicit approval. This is not a proposal
to recognize arbitrary program equivalence by hashing source or types.

## 7. Durable and External Boundaries

Validation must be isolated from the live store and must not issue new external
side effects. Current replay uses recorded external outcomes, including readonly
results, and checks the recorded call sequence and request descriptors. An
upgrade must not rerun those reads against today's external state or create new
child UUIDs to repeat historical mutations.

A changed outbound call sequence or target is a compatibility issue even if the
local final state matches. The initial policy strictly requires identical call
counts, order, targets and encoded arguments, using frozen service declarations
and recorded outcomes. Each target is checked against the endpoint recorded for
that call, not the current service configuration. A deployment address change
alone therefore neither invalidates completed history nor causes network replay.
Legacy records still use their original binding; history is not rewritten.
This intentionally rejects some potentially safe refactorings;
any relaxation needs explicit identity/equivalence rules later. This restricts
historical replay, not new execution paths for future requests. Pending history
cannot be discarded as part of migration.

Final historical errors are included in upgrade checking. Skipping them might be
a future explicit option, but is not the initial policy: local rollback does not
erase an observed error or a previously committed external side effect.

Admission must eventually define a stable validation boundary: new writes cannot
race with a checked history and then disappear at cutover. Atomic activation,
crash recovery, retention of original evidence and rollback are required design
topics. No online upgrade or zero-downtime guarantee is made here.

## 8. Initial Acceptance Matrix

This is the overall design acceptance matrix. Section 9 describes the implemented
subset, including timestamp switching and deprecation. Managed activation without
pending work is documented separately; representation migration remains future work.

| Case | Expected evidence |
| --- | --- |
| Original counter history | Outcomes five/three; final total three |
| Timestamp-gated revision | Same history, new negative request rejected |
| Timestamp exactly at cutoff | New rule applies |
| Retry/restart across cutoff | Original time and UUID outcome preserved |
| Replay-only old API | History succeeds; fresh call rejected; completed retry works |
| Ungated new negative check | Compatibility validation rejects historical divergence |
| Same final state, changed intermediate readonly result | Observation validation detects difference |
| New representation | Explicit projections agree for selected properties |
| Intentional bug correction | Differences reported; no silent outcome-cache rewrite |
| History with external calls | Recorded results used; no new outbound mutation |
| Pending request or missing historical evidence | Explicit unresolved boundary, not implicit approval |
| Crash during validation/activation | Old confirmed history retained; no partial activation |

## 9. Implemented Offline Checker

```bash
make build
./bin/teaspoon check-upgrade \
  --old old/main.tsp \
  --new new/main.tsp \
  --database snapshots/working.sqlite \
  --revision working
```

Use a stopped, checkpointed database or a complete offline SQLite snapshot. Do
not copy only the main `.sqlite` file while committed data still resides in its
WAL. With the SQLite CLI installed, after stopping the owner, SQLite's `.backup`
command can produce a standalone snapshot that includes committed WAL contents:

```bash
mkdir -p snapshots
sqlite3 .teaspoon/logs/working.sqlite '.backup snapshots/working.sqlite'
```

Snapshot creation is separate from the checker. Keep original files intact and
do not edit/delete journals to bypass a failure. The snapshot must remain
unchanged throughout checking. This tool is for trusted local source/databases,
not a sandbox or a resource-limited service for untrusted programs.

The checker takes a shared runtime lock if the existing `.lock` file is present,
refuses nonempty WAL/rollback journals and opens SQLite read-only/immutable. It
does not create a lock, journal or database, configure HTTP clients, load secrets,
write fingerprints, resolve pending work or activate a new deployment. A snapshot
without a lock is supported; the caller must ensure no process writes it.

`--revision` defaults to `working` and must identify the original runtime revision,
not the candidate's intended revision. The old parsed program must match the
stored fingerprint, which includes the parser filename and source locations.
Keep the original old filename or pass `--source-name original.tsp` if its file
has been renamed. Comments may change in the candidate, but the old input must
still reproduce the original identity.

Checking proceeds as follows:

1. Validate stored identity, request records, frozen bindings and completed child
   outcomes. Refuse pending requests, orphaned children and detected incomplete
   or malformed records. This is not an authenticity proof: a deleted history
   suffix with no remaining evidence cannot in general be detected. Preserve a
   complete, trusted snapshot.
2. Initialize the original program and replay every finalized request in `seq`
   order. Verify that it reproduces the recorded outcomes and call traces. A
   baseline mismatch is unverifiable history, not blame assigned to the candidate.
3. Independently initialize the candidate and replay the same requests without
   UUID-cache shortcuts. Normal readonly/error rollback semantics are retained.
4. Compare final global names, value kinds and values exactly. Representation
   migrations and user-supplied equivalence projections are not supported yet.

For success, the value envelope is compared. For errors, comparison includes
phase, code, safe message and business payload, but excludes source locations,
snippets, suggestions, stack frames and diagnostic globals. Revision labels are
not semantic output differences. Successful mutation classification must also
match. APIs appearing in history must retain their readonly/transactional kind
even if every recorded outcome was an error: completed HTTP retries still need
the original method. Runtime/decode errors already present in the finalized
journal are checked as well as explicit business errors.

Runtime/decode messages are normalized to the runtime's fixed description for
the error code on both sides, including legacy records. Historical free-form
diagnostic text can contain private values and is not business output. This
allows old detailed failure records to be checked without recreating snapshots
or reproducing sensitive descriptions. Error codes and phases must still match;
explicit business error messages and values still compare exactly. A genuinely
different outcome remains a mismatch, including a historical response-budget
failure that cannot be reproduced under the current execution behavior.

For keyed readonly records that could have originated from HTTP, reconstruct
query values and require the candidate HTTP decoder to produce the same JSON
arguments. Otherwise the same URL and UUID could become a cache conflict after
upgrade, even when replayed decode errors compare equal. Native-only shapes
remain subject to replay but not this query check. Parameter reordering and
changes that preserve encoding for the recorded inputs are not rejected merely
because the declarations differ. Unkeyed calls have no client retry identity.

All external calls consume only saved results with the original child identity.
Removed calls, extra calls, reordered calls or changed HTTP targets/arguments are
rejected. In particular, an external success followed by a local error retains
its call trace; neither that mutation nor a readonly external request is sent
again. Frozen bindings are used without discovery. Passing is not a check of
deployment readiness or newly introduced dependencies on unexercised paths.

Output is a JSON report with `status`, `stage`, `checked` and `reason`. The first
request discrepancy includes `sequence` and `api`; outcome/final-state mismatches
also include `expected` and `actual`. Reports may contain application data and
must be treated as private. `checked` counts candidate requests verified before
the first discrepancy, not UUID retries or baseline calls.

| Status | Exit | Meaning |
| --- | --- | --- |
| `compatible` | 0 | This history and final state match under the strict policy |
| `incompatible` | 1 | Candidate validation, execution, trace or state differs |
| `unverifiable` | 2 | Invalid input, unavailable/incomplete/corrupt history, wrong old identity, or baseline mismatch |

A source that cannot be parsed is an input failure (exit 2); a parsed candidate
that fails static checking or initialization is incompatible (exit 1). Report
output failure also exits 2. Ordinary runtime startup still rejects changed
fingerprints even after a compatible report. This is not migration, an admission
certificate, or a proof about unrecorded/future inputs.

Tests cover comment-only changes and added APIs; historical success, readonly
and error differences; mutation classification and final globals; local rollback
after remote success; outbound additions/removals/order/target/argument changes;
offline replay, corrupt and pending history, lock/journal refusal, unchanged
input bytes and CLI exit/report behavior. Request-time tests cover nanosecond
precision, retry/restart, killed-process recovery, failed intent/completion writes,
timestamp cutoffs and missing legacy metadata. The checker supplies original
admission times when present and reports missing required times as unverifiable.
Deprecated API tests cover both kinds, admission refusal, retained completed
success/error/readonly responses, pending recovery, committed mutation replay,
and readonly/error history verification. The offline checker alone never
activates source; managed activation is documented in [Migration](migration.md).
