Skip to content

Commit 724f877

Browse files
committed
Support durable runtime maintenance freeze
1 parent a39a780 commit 724f877

11 files changed

Lines changed: 391 additions & 4 deletions

File tree

‎.github/workflows/test.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,14 @@ jobs:
4040
with:
4141
go-version-file: pocketcontext/go.mod
4242
cache-dependency-path: pocketcontext/go.sum
43+
- name: Test maintenance entrypoint
44+
run: python3 taskcontext/tests/maintenance_entrypoint.py
4345
- name: Build server
4446
working-directory: pocketcontext
4547
# The flags of pocketcontext's Makefile.
4648
run: CGO_ENABLED=1 go build -tags sqlite_math_functions -o bin/pocketcontext ./cmd/pocketcontext
49+
- name: Test maintenance freeze and frozen restart
50+
run: python3 taskcontext/tests/maintenance.py --binary pocketcontext/bin/pocketcontext
4751
- name: Test issue tracker
4852
run: python3 taskcontext/tests/integration.py --binary pocketcontext/bin/pocketcontext
4953
- name: Test skill

‎Dockerfile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ RUN go build -trimpath -tags sqlite_math_functions -ldflags '-s -w' -o /out/pock
6464

6565
FROM debian:trixie-20260918-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a
6666
RUN apt-get update \
67-
&& apt-get install -y --no-install-recommends ca-certificates tini \
67+
&& apt-get install -y --no-install-recommends ca-certificates tini python3 \
6868
&& rm -rf /var/lib/apt/lists/* \
6969
&& test -x /usr/bin/tini
7070

‎POCKETCONTEXT_VERSION‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
a92b0de5e1b66b6d3b6135b90092d2d6da5f7cc8
1+
976ddf71a4734530adefe4a56633658a0894b449

‎README.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,3 +251,36 @@ Install uv, then run `uv venv` and `uv pip install -e .`. Activate `.venv` befor
251251
The implementation and bundled schema live in `src/taskcontext_client/`; keep its schema snapshot identical to `skills/taskcontext/references/schema.json`. Publish and test the package commit before updating the launcher to that commit. The ObserveContext dependency is pinned separately. Tracing is inactive unless explicitly enabled by `observecontext capture -- taskcontext ...`; capture failures must preserve the command result.
252252

253253
For a released launcher, run `python3 tests/skill.py --binary /absolute/path/to/pinned/pocketcontext --client /absolute/path/to/copied/taskcontext`. This uses a fresh uv cache and isolated synthetic records. Put the real uv binary on `PATH` when a version-manager shim depends on `HOME`; authentication tests deliberately use temporary home directories. Source/schema mutation checks use a private package copy.
254+
255+
## Runtime maintenance freeze
256+
257+
Superusers inspect `GET /api/context/maintenance` and toggle with
258+
`PUT /api/context/maintenance` using `{"readOnly":true,"expectedGeneration":N}`.
259+
Use the returned generation; wait for confirmed `read_only` before taking a final
260+
migration snapshot. Active writes drain, subsequent mutations return 503, and
261+
authorized SQL reads and original downloads remain available. Existing sessions
262+
can refresh; login flows requiring writes may fail. Thaw explicitly with
263+
`readOnly:false` and the current generation. Stale generations return 409.
264+
265+
The private `pb_data/maintenance.json` marker must travel with a recovery snapshot.
266+
Frozen startup preserves the existing database, settings, OAuth identities and
267+
operator credentials; it skips restore and bootstrap provisioning and refuses
268+
missing databases, unsafe markers or pending migrations. This is not cross-host
269+
fencing: pause CD and stop/disable the source writer before activating a replacement.
270+
271+
Release gates use synthetic data:
272+
273+
```sh
274+
python3 tests/maintenance_entrypoint.py
275+
python3 tests/maintenance.py --binary /absolute/path/to/pinned/pocketcontext
276+
```
277+
278+
Maintenance tests also verify that a frozen restart does not provision newly
279+
configured required users, existing operator/user tokens survive, pending migrations
280+
fail, and rejected issue creation does not consume the next issue number. The
281+
server maintenance suite covers in-flight write draining and managed SQLite guards.
282+
283+
Replicated startup waits for an initial Litestream IPC sync before serving. An
284+
unreachable replica fails startup. Fresh Google-only databases are initialized
285+
before this handshake; frozen starts always require the existing database. This
286+
ensures clean shutdown can sync even before the first periodic monitor tick.

‎docker/entrypoint.sh‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ app_flags() {
3333
}
3434

3535
serve() {
36+
# Initialize this supervisor's replica before accepting any application writes.
37+
# Litestream otherwise may stop before its first monitor tick and miss final sync.
38+
if [ "${LITESTREAM_DISABLED:-}" != true ]; then
39+
if ! litestream sync -wait -timeout 60 -socket /run/litestream.sock "$DB_PATH" >/dev/null 2>&1; then
40+
die "initial replica synchronization failed; refusing to serve"
41+
fi
42+
log "initial replica synchronization complete"
43+
fi
3644
# The server needs neither the replica credentials nor the superuser password.
3745
# Litestream copies its credentials into AWS_* for its own use; drop those as well.
3846
unset LITESTREAM_ACCESS_KEY_ID LITESTREAM_SECRET_ACCESS_KEY \
@@ -66,6 +74,44 @@ fi
6674
cd "$APP_DIR"
6775
mkdir -p "$DATA_DIR"
6876

77+
# Read only the shared maintenance contract, never application settings or secrets.
78+
# Malformed state stops startup rather than accidentally reopening a frozen app.
79+
if ! frozen=$(python3 - "$DATA_DIR/maintenance.json" <<'PY'
80+
import json
81+
import os
82+
from pathlib import Path
83+
import stat
84+
import sys
85+
86+
path = Path(sys.argv[1])
87+
try:
88+
try:
89+
info = os.lstat(path)
90+
except FileNotFoundError:
91+
info = None
92+
if info is None:
93+
print('false')
94+
else:
95+
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_size > 4096:
96+
raise ValueError('maintenance state must be a private regular file')
97+
state = json.loads(path.read_text())
98+
if (not isinstance(state, dict) or set(state) != {'readOnly', 'generation'}
99+
or type(state.get('readOnly')) is not bool
100+
or type(state.get('generation')) is not int
101+
or not 0 <= state['generation'] <= 18446744073709551615):
102+
raise ValueError('invalid maintenance state')
103+
print('true' if state['readOnly'] else 'false')
104+
except Exception:
105+
sys.exit(1)
106+
PY
107+
); then
108+
die "invalid maintenance state; startup stopped"
109+
fi
110+
if [ "$frozen" = true ]; then
111+
[ -f "$DB_PATH" ] || die "frozen startup requires the existing database"
112+
log "read-only maintenance state: preserving the existing database and credentials"
113+
fi
114+
69115
replicate=true
70116
if [ "${LITESTREAM_DISABLED:-}" = true ]; then
71117
replicate=false
@@ -86,7 +132,7 @@ else
86132
export LITESTREAM_REGION LITESTREAM_ENDPOINT LITESTREAM_SYNC_INTERVAL
87133
fi
88134

89-
if [ "$replicate" = true ]; then
135+
if [ "$replicate" = true ] && [ "$frozen" != true ]; then
90136
if [ -f "$DB_PATH" ]; then
91137
log "database exists in the volume: no restore"
92138
else
@@ -106,7 +152,9 @@ if [ "$replicate" = true ]; then
106152
fi
107153
fi
108154

109-
if [ -n "${TASKCONTEXT_SUPERUSER_EMAIL:-}" ] && [ -n "${TASKCONTEXT_SUPERUSER_PASSWORD:-}" ]; then
155+
if [ "$frozen" = true ]; then
156+
log "read-only maintenance state: skipping superuser provisioning"
157+
elif [ -n "${TASKCONTEXT_SUPERUSER_EMAIL:-}" ] && [ -n "${TASKCONTEXT_SUPERUSER_PASSWORD:-}" ]; then
110158
log "upserting the superuser from TASKCONTEXT_SUPERUSER_EMAIL"
111159
# shellcheck disable=SC2046 # see serve
112160
if ! "$SERVER" superuser upsert $(app_flags) -- "$TASKCONTEXT_SUPERUSER_EMAIL" "$TASKCONTEXT_SUPERUSER_PASSWORD"; then
@@ -119,6 +167,12 @@ elif [ -n "${TASKCONTEXT_SUPERUSER_PASSWORD:-}" ]; then
119167
fi
120168

121169
if [ "$replicate" = true ]; then
170+
# Google-only fresh starts also need a database before the IPC handshake.
171+
# Frozen starts already required their existing database above.
172+
if [ ! -f "$DB_PATH" ]; then
173+
# shellcheck disable=SC2046
174+
"$SERVER" migrate up $(app_flags) || die "initial database migration failed"
175+
fi
122176
log "starting Litestream, which starts and supervises the server"
123177
exec litestream replicate -config "$LITESTREAM_CONFIG_FILE" -exec "$SELF serve"
124178
fi

‎docker/litestream.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
# Private container-local IPC for the startup replication handshake.
2+
socket:
3+
enabled: true
4+
path: /run/litestream.sock
5+
permissions: 0600
16
# Litestream 0.5.x configuration (single `replica:` key; 0.3.x used a `replicas:` list).
27
# The entrypoint validates the variables and sets the optional ones before Litestream reads
38
# this file. The credentials are not written here: Litestream reads LITESTREAM_ACCESS_KEY_ID

‎docker/smoke.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,24 @@ def smoke(image, tmp, run_id):
310310
check_records(client, project, issue)
311311
text = check_logs(name)
312312
check('pbinstall' not in text, 'the logs contain no superuser installation link')
313+
step('freeze and restart the real container without rotating the operator token')
314+
token = superuser_token(base, env['TASKCONTEXT_SUPERUSER_EMAIL'], env['TASKCONTEXT_SUPERUSER_PASSWORD'])
315+
status, _, state = http('GET', base + '/api/context/maintenance', token=token)
316+
check(status == 200 and state['state'] == 'writable', 'maintenance starts writable')
317+
status, _, frozen = http('PUT', base + '/api/context/maintenance',
318+
{'readOnly': True, 'expectedGeneration': state['generation']}, token=token)
319+
check(status == 200 and frozen['state'] == 'read_only', 'container enters drained read-only mode')
320+
stop(name)
321+
docker('start', name)
322+
base = wait_up(name)
323+
status, _, state = http('GET', base + '/api/context/maintenance', token=token)
324+
check(status == 200 and state['state'] == 'read_only' and state['generation'] == frozen['generation'],
325+
'frozen container restart preserves the operator token and maintenance generation')
326+
status, _, _ = http('POST', base + '/api/collections/users/records', {}, token=token)
327+
check(status == 503, 'frozen container rejects mutations')
328+
status, _, state = http('PUT', base + '/api/context/maintenance',
329+
{'readOnly': False, 'expectedGeneration': frozen['generation']}, token=token)
330+
check(status == 200 and state['state'] == 'writable', 'operator explicitly thaws the restarted container')
313331
stop(name)
314332

315333

‎pb_hooks/deploy.pb.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ routerAdd("GET", "/up", (e) => require(`${__hooks}/deploy.js`).up(e), $apis.skip
88
// Runs for every command (serve, superuser, migrate) after the database is open and the settings are loaded.
99
onBootstrap((e) => {
1010
e.next();
11+
// Preserve durable maintenance state, stored settings and existing identities.
12+
if (e.app.store().get("pocketcontextMaintenanceReadOnly") === true) return;
1113
require(`${__hooks}/deploy.js`).settings(e.app);
1214
require(`${__hooks}/deploy.js`).googleOAuth(e.app);
1315
require(`${__hooks}/required_users.js`).ensure(e.app, true);

‎tests/integration.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ def request(method,path,body=None,token=None,expected=200):
5454
time.sleep(.1)
5555
else: raise AssertionError('Server startup timed out')
5656
request.base_url = f'http://127.0.0.1:{port}'
57+
request.data_dir = Path(tmp)/'pb_data'
5758
yield request
5859
finally:
5960
proc.terminate();proc.wait(timeout=15)

‎tests/maintenance.py‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
#!/usr/bin/env python3
2+
"""Exercise migration freeze with synthetic application content over HTTP."""
3+
import argparse
4+
import json
5+
import os
6+
import shutil
7+
import socket
8+
import sqlite3
9+
import subprocess
10+
import tempfile
11+
import time
12+
from pathlib import Path
13+
import urllib.error
14+
import urllib.request
15+
16+
from integration import ROOT, server
17+
18+
19+
def frozen_restart(binary, request, admin, token, frozen):
20+
"""A fresh process preserves a frozen snapshot despite changed deploy settings."""
21+
with tempfile.TemporaryDirectory(prefix='taskcontext-frozen-restart-') as tmp:
22+
data = Path(tmp) / 'pb_data'
23+
data.mkdir()
24+
for source in request.data_dir.glob('*.db'):
25+
with sqlite3.connect(source.as_uri() + '?mode=ro', uri=True) as read:
26+
with sqlite3.connect(data / source.name) as write:
27+
read.backup(write)
28+
shutil.copy2(request.data_dir / 'maintenance.json', data / 'maintenance.json')
29+
if (request.data_dir / 'storage').exists():
30+
shutil.copytree(request.data_dir / 'storage', data / 'storage')
31+
def config_rows(path):
32+
with sqlite3.connect(path.as_uri() + '?mode=ro', uri=True) as db:
33+
return (db.execute('SELECT * FROM _params ORDER BY id').fetchall(),
34+
db.execute('SELECT * FROM _collections ORDER BY id').fetchall(),
35+
db.execute('SELECT * FROM users ORDER BY id').fetchall(),
36+
db.execute('SELECT * FROM _superusers ORDER BY id').fetchall())
37+
stored = config_rows(data / 'data.db')
38+
with socket.socket() as sock:
39+
sock.bind(('127.0.0.1', 0))
40+
port = sock.getsockname()[1]
41+
env = dict(os.environ, BASE_URL='https://must-not-apply.example.test',
42+
TASKCONTEXT_GOOGLE_CLIENT_ID='synthetic-changed-client',
43+
TASKCONTEXT_GOOGLE_CLIENT_SECRET='synthetic-changed-secret',
44+
TASKCONTEXT_REQUIRED_USERS='[{"email":"must-not-create@example.test","name":"Must not create"}]')
45+
common = [str(Path(binary).resolve()), '--dir', str(data),
46+
'--migrationsDir', str(ROOT / 'pb_migrations'), '--hooksDir', str(ROOT / 'pb_hooks')]
47+
# New application migrations must not silently change a frozen snapshot.
48+
pending = Path(tmp) / 'pending_migrations'
49+
shutil.copytree(ROOT / 'pb_migrations', pending)
50+
(pending / '9999999999_frozen_pending.js').write_text(
51+
'migrate((app) => { app.db().newQuery("CREATE TABLE forbidden_frozen_write (id TEXT)").execute(); }, () => {});')
52+
rejected = subprocess.run([str(Path(binary).resolve()), '--dir', str(data),
53+
'--migrationsDir', str(pending), '--hooksDir', str(ROOT / 'pb_hooks'),
54+
'serve', '--http', f'127.0.0.1:{port}'], cwd=ROOT, env=env,
55+
capture_output=True, text=True, timeout=20)
56+
assert rejected.returncode != 0, 'pending migration started during freeze'
57+
assert config_rows(data / 'data.db') == stored, 'pending migration changed stored settings'
58+
def call(method, path, body=None, identity=admin):
59+
req = urllib.request.Request(f'http://127.0.0.1:{port}' + path,
60+
data=None if body is None else json.dumps(body).encode(),
61+
headers={'Content-Type': 'application/json', 'Authorization': identity}, method=method)
62+
with urllib.request.urlopen(req, timeout=10) as response:
63+
return json.loads(response.read())
64+
with (Path(tmp) / 'server.log').open('w+') as log:
65+
process = subprocess.Popen(common + ['serve', '--http', f'127.0.0.1:{port}'],
66+
cwd=ROOT, env=env, stdout=log, stderr=log)
67+
try:
68+
for _ in range(150):
69+
if process.poll() is not None:
70+
log.seek(0)
71+
raise AssertionError(log.read())
72+
try:
73+
state = call('GET', '/api/context/maintenance')
74+
break
75+
except (OSError, ValueError):
76+
time.sleep(.1)
77+
else:
78+
raise AssertionError('frozen restart timed out')
79+
assert state['state'] == 'read_only' and state['generation'] == frozen['generation'], state
80+
assert config_rows(data / 'data.db') == stored, 'frozen bootstrap changed configuration'
81+
assert call('POST', '/api/context/query', {'sql': 'SELECT id FROM projects'}, token)['rows']
82+
# Existing operator tokens can thaw after a full process restart.
83+
state = call('PUT', '/api/context/maintenance', {
84+
'readOnly': False, 'expectedGeneration': frozen['generation']})
85+
assert state['state'] == 'writable', state
86+
finally:
87+
process.terminate()
88+
process.wait(timeout=15)
89+
90+
91+
def main():
92+
parser = argparse.ArgumentParser()
93+
parser.add_argument('--binary', required=True)
94+
args = parser.parse_args()
95+
with server(args.binary) as request:
96+
records = '/api/collections/'
97+
admin = request('POST', records + '_superusers/auth-with-password', {
98+
'identity':'admin@example.com', 'password':'SyntheticAdminPassword123!'})['token']
99+
def account(email):
100+
user = request('POST', records + 'users/records', {
101+
'email':email, 'name':'Synthetic', 'verified':True,
102+
'password':'SyntheticPassword123!', 'passwordConfirm':'SyntheticPassword123!'}, admin)
103+
token = request('POST', records + 'users/auth-with-password', {
104+
'identity':email, 'password':'SyntheticPassword123!'})['token']
105+
return user, token
106+
user, token = account('reader@example.test')
107+
outsider, other = account('outsider@example.test')
108+
payload = {'key':'FREEZE','name':'Synthetic freeze'}
109+
row = request('POST', records + 'projects/records', payload, token)
110+
issue = request('POST', records + 'issues/records', {'project':row['id'],'title':'Before freeze'}, token)
111+
assert issue['key'] == 'FREEZE-1'
112+
query_sql = 'SELECT id FROM projects'
113+
write_table = 'projects'
114+
status = request('GET','/api/context/maintenance',token=admin)
115+
for identity in (None,token):
116+
request('GET','/api/context/maintenance',token=identity,expected=(401,403))
117+
request('PUT','/api/context/maintenance',{'readOnly':True,'expectedGeneration':status['generation']},identity,(401,403))
118+
frozen = request('PUT','/api/context/maintenance',{'readOnly':True,'expectedGeneration':status['generation']},admin)
119+
assert frozen['state'] == 'read_only'
120+
assert request('POST','/api/context/query',{'sql':query_sql},token)['rows'] == [[row['id']]]
121+
request('POST', records + 'users/auth-refresh', {}, token)
122+
for identity in (token,admin):
123+
request('POST',records + write_table + '/records',payload,identity,503)
124+
request('PATCH',records + write_table + '/records/' + row['id'],{'expected_revision':1},identity,503)
125+
request('POST','/api/batch',{'requests':[{'method':'POST','url':records + write_table + '/records','body':payload}]},identity,503)
126+
request('POST', records + 'issues/records', {'project':row['id'],'title':'Blocked'}, token,503)
127+
frozen_restart(args.binary, request, admin, token, frozen)
128+
request('PUT','/api/context/maintenance',{'readOnly':False,'expectedGeneration':status['generation']},admin,409)
129+
thawed = request('PUT','/api/context/maintenance',{'readOnly':False,'expectedGeneration':frozen['generation']},admin)
130+
assert thawed['state'] == 'writable'
131+
issue = request('POST', records + 'issues/records', {'project':row['id'],'title':'After thaw'}, token)
132+
assert issue['key'] == 'FREEZE-2'
133+
print('PASS: maintenance authorization, mutation rejection, read access, frozen restart and thaw')
134+
135+
136+
if __name__ == '__main__':
137+
main()

0 commit comments

Comments
 (0)