Release changes with staging, checks and a return path
Restore compatible views, preserve newer business data and handle observed intermediate states deliberately.

Publication needs a rollback path that actually works
A successful preview establishes that a change works under particular conditions. It does not yet explain how the switch interacts with existing data or how a later fault can be handled. A dependable release workflow therefore connects a bounded candidate, appropriate preflight, a controlled switch and an actually investigated return path. A backup name alone cannot demonstrate that the previous application still works with the data now present.
Our original experiment uses a small versioned view definition and a fixed shared runtime. Version one shows identifiers and titles. Version two adds notes and requires an additive schema extension. This is explicitly not deployment of an arbitrary complete program, server or container. The small boundary nevertheless makes the relationship between version, schema and data directly testable rather than merely illustrated in a diagram.
Fifty executed Python/SQLite conditions and eight real HTTP requests investigate this workflow. A staging copy stays separate from the running example data. Rollback retains later records. A post-switch fault returns to the previous view, while a detected intervening foreign state is preserved for review. Every mutation belongs to the original fictional fixture rather than a real hosting environment.
Identify the release and its prerequisites precisely
A release.json contains exactly the version name, minimum required schema and a Boolean deciding whether notes appear. Values have fixed types and the version name has a narrow format rather than accepting an arbitrary path. Rendering selects one of two column lists hardcoded in the shared runtime. The definition supplies no freely executable SQL or Python program. This keeps the small release contract readable.
The caller supplies the expected SHA-256 digest of the reviewed file. Before using it, the manager compares the bytes actually read with that expectation and rejects a mismatch. In the experiment the pin comes from original trusted preparation. It is not a digital signature and does not identify a publisher by itself. The trustworthiness of the expected value’s source remains a separate prerequisite.
This design separates mutable business data from the versioned view. A real application release would additionally identify executable code, dependencies and compatible runtime requirements. One configuration file does not cover that larger supply chain. The example instead shows a bounded part whose switch and compatibility can be exercised concretely. Its modest scope is useful because every stronger deployment claim would need additional evidence.
Read the current state before changing it
The workflow receives an expected active pointer containing release, digest and generation. It first compares that value with the actual file. A caller with stale expectations cannot simply overwrite an intervening change. It also executes the current view against the real database. An already unreadable initial state is therefore not silently accepted as a healthy starting point for a new release.
Generation distinguishes states even when a switch and rollback return to the same named release. An old operation expecting version one does not become current again merely because version one reappears later. Each switch increments generation in this example. That prevents identical visible names from accidentally making an earlier expectation valid after an intervening transition.
A version comparison is not access control for the entire environment. The process already needs authorized filesystem and database access. Someone able to alter those resources freely outside the contract has different capabilities. These checks coordinate the intended workflow and detect the exercised intermediate changes. They do not protect against every manipulation possible on a compromised operating system or an unrestricted noncooperating writer.
Keep staging genuinely separate from running data
Stage creates a separate database through SQLite’s backup API. It refuses the source path as destination and refuses to overwrite an existing staging file. Migration and candidate rendering operate only on that copy. The resulting clone has schema two while the running example still has schema one. The test inspects both actual databases rather than relying on their directory names.
The active pointer also remains unchanged. A further real HTTP request still reports version one after staging completes. These observations establish the separation more concretely than two folders labelled test and production. A real system must also configure mail, payments and other external effects separately. A copied database does not automatically isolate services that exist outside it.
Our fixture contains fictional records only. Real staging inventories need a decision about necessary data and information that should be reduced or replaced. Production credentials should not be copied incidentally into another environment. Relevant similarity should enable the test without creating an uncontrolled second system that performs real production effects. Matching the database schema is only part of that broader operational decision.
Treat backup and view rollback as different operations
Before the production-like switch, the manager creates another database snapshot through the backup API. The experiment actually reads it and restores it into a separate verification destination. That destination contains the expected original inventory and stays separate from the running database, which subsequently receives newer records. Backup existence is therefore supported by a real readability and restoration observation.
View rollback does not use that snapshot as a blanket replacement for current data. New business actions may have happened after publication. Copying the older database over the current one would lose them. Our return path switches only the compatible view definition. The added note column and later records remain present. The difference matters even when an older page looks perfectly healthy after replacement.
Database restoration can be necessary for other failures, but it needs its own justified procedure. Recovery point, subsequent changes and downstream effects must fit that decision. The tested snapshot is an additional available option rather than evidence that every fault can safely be fixed by restoring the same old file. Calling both operations rollback should not hide their very different effects on business state.
Extend the schema so the previous view keeps working
The original migration adds a text note column with an empty default. It removes or renames no existing field. Both views select explicit columns: version one continues to read id and title, while version two also reads note. The older view can therefore operate against the expanded data. This is an observed property of the particular queries and migration, not an assumption attached to the word additive.
Migration uses its own immediate write transaction and updates the known schema version. It supports only the explicitly defined starting states one and two. Running it again at two does not add the column a second time. Other starting versions are rejected rather than optimistically reshaped. This narrow contract keeps the example’s actual behavior understandable and avoids inventing a universal migration engine.
Not every data change is backward compatible this way. Removing a field or changing existing values’ meaning can prevent a return to old code. A real release should exercise both old and new application behavior against the intended shared schema. An additive-migration label alone cannot establish compatibility if actual queries or business interpretations still cease to fit. Those dependencies belong in the release decision.
Check the candidate and return path again after migration
After expansion, the manager renders the new candidate against the actual example database. It then renders the previous view against that same expanded schema. Switching occurs only if both work and the active pointer still matches the expected original state. The return path is therefore part of a concrete pre-switch check rather than something assumed available because old files were retained.
An intentionally unsuitable candidate requests schema three while the supplied migration reaches only two. Candidate preflight fails and the pointer remains on version one. The already committed additive migration nevertheless remains present. The previous view then works against schema two. This important observed result is not represented as a complete reversal of every earlier step; the database has genuinely changed even though the view switch never occurred.
The pointer file and database are not one atomic overall transaction here. Their order and compatibility are developed explicitly. Treating them as unrelated and copying old files back after any error could overlook that dependency. The fixture makes the actual completion boundaries visible, including changes deliberately retained after an aborted release attempt. That clarity is more useful than a broad but inaccurate atomic-deployment claim.
Coordinate cooperating writers through owned exclusion
The manager creates a lock file using exclusive creation. A second cooperating deployment receives writer_busy while the first owns it, instead of taking over the existing lock. Normal completion releases the lock acquired by that operation. The experiment actually holds the lock and invokes the rejected second path, so the contention condition is executed rather than inferred from a filename.
A hard process termination could leave such a file behind. The displayed core does not remove it automatically based on a guessed age. Real operation needs an appropriate recovery and ownership decision for that state. This lock is intentionally neither a universal distributed-lock service nor complete management of every crashed instance. Its useful contract concerns the cooperating local writers that actually follow it.
All participating writers must respect that contract. A process that ignores the lock and directly changes the pointer is outside its serialization. Additional expectation checks detect the intervening switch exercised in our fault case. They cannot atomically prevent every later action by an uncooperative writer. Honest documentation should preserve that boundary instead of describing a sequence of comparisons as an all-purpose compare-and-swap primitive.
Replace the active pointer as one bounded file
The new pointer is first written into a uniquely named temporary file in the same directory. Its contents are fully written and the file is synchronized before os.replace replaces the active file. The temporary is cleaned up on ordinary success and error paths. The example needs no directory links or hidden parallel project locations to perform this one-file switch.
Actual parallel testing on Windows exposed brief PermissionError states while opening the pointer. The read path therefore retries that specific error within a fixed bound. Replacement likewise handles a temporary permission block with bounded retries. A persistent failure remains a failure after eight attempts. The test explicitly establishes that behavior using a controlled blocked reader rather than assuming contention always resolves.
One hundred fifty actual overlapping reads and twenty replacements exercise the fixture. Completed read paths return whole known states. This does not establish a guarantee against power loss, every filesystem or every possible Windows blocker. The source has a narrower investigated job and reports an error when its limited retry mechanism is insufficient. A retry should improve a known contention path without converting permanent failure into apparent success.
Check the actual access path after switching
Switching does not finish the workflow. Its smoke function calls the original running HTTP service, whose answer is generated from the active pointer and shared data. The test observes version two, schema two and the appropriate fields after the switch. Merely writing the pointer file successfully would be weaker evidence that the resulting access path works.
The service is deliberately an isolated JSON view using a fixed runtime. It implements no login, payments or external delivery. A real smoke test should choose important actual visitor and business paths for the product. A reachable homepage does not automatically test a changed form or protected request. Evidence should connect to the behavior that the particular release can affect.
A post-switch check is not unconditional availability assurance. In the controlled failing case, version two is briefly visible over HTTP before the return path runs. The fixture therefore claims neither an invisible risk-free switch nor measured perfect uptime. It shows the limited release and recovery sequence actually executed. Other rollout architectures need their own routing, compatibility and observation evidence.
Preserve later business data on the return path
After a successful switch, the experiment creates another fictional item with a note. Version two actually returns it over HTTP. The previous view definition is then activated again. The next real response reports version one, schema two and both item titles. The later record is therefore present after rollback rather than disappearing along with the new presentation.
The older view does not display the note but does not delete it. A direct database query confirms its retained value. This distinguishes a simpler old presentation from losing newer information. An old homepage would be insufficient evidence if recent operations silently disappeared behind it. The investigation checks the business inventory separately from the release label for exactly this reason.
Another controlled failure writes a new record during the post-switch check and then raises an error. Automatic view recovery retains that record as well. The experiment thus goes beyond a convenient quiet database. The earlier backup is still restored only into a separate verification destination, never over the running inventory containing these newer writes. Recovery decisions remain specific to the effect they are meant to address.
Do not roll back an intervening foreign state as your own work
Before automatic recovery, the manager checks whether the active pointer still exactly equals its own proposed state. In the counterexample, a controlled uncooperative operation installs another generation before error handling begins. The manager detects that difference and does not overwrite it. It returns a conflict requiring review rather than pretending to have safely restored its own earlier state.
An explicit later view rollback also requires the expected current pointer. A stale call carrying generation two cannot overwrite the generation-three state already produced by a return. The experiment checks this rejection. Seeing the same release name again is not sufficient evidence that an old operation still owns the current transition.
The conflict behavior preserves foreign work in the exercised case. It does not authorize unrestricted parallel mutation outside the lock contract. Real publication processes should identify their authoritative writers and permitted mutation paths clearly. Reducing hidden competing paths makes actual intermediate states easier to explain and resolve. The operational discipline complements the code rather than being something a pointer comparison can fully replace.

Read fifty conditions and eight HTTP requests as concrete evidence
The report identifies Python and SQLite versions, actual source digests and answers returned by the original HTTP view. It records separate staging state, the original snapshot and the newer inventory retained after returning to the older view. The explanatory diagram is built from those observations, without an invented availability curve or generic safety score. It is a reviewable account of an original small experiment.
The number of conditions describes the exercised scope. A full operating-system upgrade, distributed hosting and a damaged storage device were not tested. Records and release definitions are fictional. Copying, migration, file replacement, HTTP access and restoration into a separate destination did actually occur. This distinction keeps the implementation evidence separate from claims that would require different infrastructure or failure scenarios.
The following two Python files provide the small manager and isolated HTTP runtime in full. The invoking application supplies approved view definitions and their trusted digests. A real product extends scope, external effects and important access paths deliberately. A return path deserves that description only when the old version actually functions with the data that exists at the time it is needed.
release.py
import contextlib
import hashlib
import json
import os
import pathlib
import re
import sqlite3
import time
import uuid
class ReleaseError(Exception):
pass
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def connection(path):
return sqlite3.connect(path, isolation_level=None, timeout=5)
def definition(root, name, expected):
if not re.fullmatch(r"[a-z0-9-]{1,40}", name):
raise ReleaseError("release_name")
base = (root / "releases").resolve()
directory = base / name
path = directory / "release.json"
if directory.is_symlink() or directory.resolve().parent != base or path.is_symlink() or path.resolve().parent != directory.resolve():
raise ReleaseError("release_path")
raw = path.read_bytes()
if sha(raw) != expected:
raise ReleaseError("artifact_digest")
data = json.loads(raw)
if set(data) != {"version", "minimum_schema", "show_note"}:
raise ReleaseError("definition_shape")
if data["version"] != name or type(data["minimum_schema"]) is not int or type(data["show_note"]) is not bool:
raise ReleaseError("definition_types")
return data
def render(root, db_path, pointer):
config = definition(root, pointer["release"], pointer["sha256"])
with contextlib.closing(connection(db_path)) as db:
schema = db.execute("PRAGMA user_version").fetchone()[0]
if schema < config["minimum_schema"]:
raise ReleaseError("schema_too_old")
columns = "id,title,note" if config["show_note"] else "id,title"
items = [dict(zip(columns.split(","), row)) for row in db.execute("SELECT " + columns + " FROM items ORDER BY id")]
return {"release": config["version"], "schema": schema, "items": items}
def atomic_pointer(path, value):
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
try:
with temporary.open("xb") as stream:
stream.write(json.dumps(value, sort_keys=True).encode())
stream.flush()
os.fsync(stream.fileno())
for attempt in range(8):
try:
os.replace(temporary, path)
break
except PermissionError:
if attempt == 7:
raise
time.sleep(0.01)
finally:
if temporary.exists():
temporary.unlink()
@contextlib.contextmanager
def writer_lock(root):
lock = root / "release.lock"
try:
handle = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError as error:
raise ReleaseError("writer_busy") from error
try:
os.write(handle, b"owned release operation")
yield
finally:
os.close(handle)
lock.unlink()
def migrate_to_two(db_path):
with contextlib.closing(connection(db_path)) as db:
db.execute("BEGIN IMMEDIATE")
try:
schema = db.execute("PRAGMA user_version").fetchone()[0]
if schema == 1:
db.execute("ALTER TABLE items ADD COLUMN note TEXT NOT NULL DEFAULT ''")
db.execute("PRAGMA user_version=2")
elif schema != 2:
raise ReleaseError("unsupported_schema")
db.execute("COMMIT")
except BaseException:
db.execute("ROLLBACK")
raise
def deploy(root, db_path, name, trusted_digest, expected_pointer, smoke):
# A deliberately small release: immutable view definition, shared runtime.
root = pathlib.Path(root)
active = root / "active.json"
with writer_lock(root):
old = read_pointer(active)
if old != expected_pointer:
raise ReleaseError("active_changed")
definition(root, name, trusted_digest)
render(root, db_path, old) # Existing release must be readable.
backup = root / ("before-" + uuid.uuid4().hex + ".sqlite")
with contextlib.closing(connection(db_path)) as source, contextlib.closing(connection(backup)) as target:
source.backup(target)
migrate_to_two(db_path)
proposed = {"release": name, "sha256": trusted_digest, "generation": old["generation"] + 1}
render(root, db_path, proposed) # Candidate before switch.
# For this additive migration, the old view must still work as well.
render(root, db_path, old)
if read_pointer(active) != old:
raise ReleaseError("active_changed_after_preflight")
atomic_pointer(active, proposed)
try:
smoke(proposed)
except BaseException:
if read_pointer(active) != proposed:
raise ReleaseError("rollback_conflict_requires_review")
restored = dict(old, generation=proposed["generation"] + 1)
atomic_pointer(active, restored)
render(root, db_path, restored)
raise ReleaseError("smoke_failed_view_rolled_back")
return {"state": "view_release_switched", "pointer": proposed, "backup": str(backup)}
def rollback_view(root, db_path, target, expected_pointer):
root = pathlib.Path(root)
with writer_lock(root):
active = root / "active.json"
current = read_pointer(active)
if current != expected_pointer:
raise ReleaseError("rollback_active_changed")
restored = dict(target, generation=current["generation"] + 1)
render(root, db_path, restored)
atomic_pointer(active, restored)
return restored
def stage(root, source_database, staging_database, name, trusted_digest):
root = pathlib.Path(root)
source_database, staging_database = pathlib.Path(source_database), pathlib.Path(staging_database)
if source_database.resolve() == staging_database.resolve() or staging_database.exists():
raise ReleaseError("staging_target")
definition(root, name, trusted_digest)
with contextlib.closing(connection(source_database)) as source, contextlib.closing(connection(staging_database)) as target:
source.backup(target)
migrate_to_two(staging_database)
pointer = {"release": name, "sha256": trusted_digest, "generation": 0}
return render(root, staging_database, pointer)
def read_pointer(path):
# Windows can briefly deny opening the file during a replacement.
for attempt in range(8):
try:
return json.loads(path.read_bytes())
except PermissionError:
if attempt == 7:
raise
time.sleep(0.01)
fixture_http.py
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from release import render, read_pointer
def server_for(root, database):
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
if self.path != "/":
self.send_error(404)
return
try:
pointer = read_pointer(root / "active.json")
result = render(root, database, pointer)
body = json.dumps(result, ensure_ascii=False).encode("utf-8")
self.send_response(200)
except Exception:
body = b'{"error":"view_unavailable"}'
self.send_response(503)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return ThreadingHTTPServer(("127.0.0.1", 0), Handler)
Document the concrete deployment state
A release record connects the reviewed candidate, prerequisites and expected initial state. After switching, it records the actual outcome and identifies which files a return changes while retaining business data. An incomplete switch also needs a precise finding: the old view may remain active even though a compatible schema extension has committed. A generic failure label would hide that distinction.
GitHub documents one CI-environment model involving protection rules and environment access, with feature availability depending on repository and plan. Our original fixture requires no such platform and claims no CI integration. The transferable idea is deliberate scope: connect a reviewed candidate to its actual target and verify that production effect separately instead of inferring it from an unrelated successful preview.
Actual states after key transitions
| Step | View | Schema and data |
|---|---|---|
| Initially | Version one | Schema one, one item |
| Expanded staging copy | Live remains version one | Only clone has schema two |
| Successful switch | Version two | Schema two, later two items |
| View rollback | Version one | Schema two and both items remain |
| Post-switch check failure | Version one again | Item written during check remains |
| Unsuitable candidate before switch | Version one remains | Additive schema two remains |
| Foreign intermediate state detected | Not overwritten | Conflict requires review |
Release and return-path checklist
- Record candidate and authoritative digest from a trusted source.
- Compare the actual initial pointer including generation.
- Keep staging data and external effects separate.
- Read snapshots and restore into a separate verification target.
- Exercise old and new views against the intended schema.
- Coordinate cooperating writers through explicit ownership.
- Test bounded file switching and relevant Windows errors.
- Operate the actual affected access paths after switching.
- Deliberately retain newer business data on rollback.
- Document conflicts, unsuitable candidates and limits accurately.
Primary sources and review scope
Primary sources reviewed on 9 November 2026. Original versioned view definitions and fixed runtime, fifty executed Python/SQLite conditions and eight actual HTTP requests. One hundred fifty overlapping pointer reads and twenty replacements on Windows with bounded sharing-error handling. No full hosting deployment, power-loss test or uptime guarantee.








