Files
thd/hd-joe/test_offline_handling.py
2026-10-15 17:27:46 +02:00

249 lines
9.8 KiB
Python

#!/usr/bin/env python3
"""The scenario Joakim reported: edit a note, go offline mid-session, keep
typing, quit. Simulates "offline" by having the fake server keep the
connection open but stop acking anything (StoppableFakeServer.go_silent) --
tried an actual server shutdown() first; python-socketio's client doesn't
reliably notice an already-established websocket has gone away within a
short test timeout, since shutdown() stops accepting new connections
without necessarily tearing down ones already open. Withholding acks is
deterministic and exercises exactly what matters here (drain_pending()'s
timeout and everything downstream of it), even though it doesn't exercise
actual transport-level disconnect detection -- see test_disconnect_hook.py
for that, tested directly against HedgeDocClient rather than through a
full pty+JOE session.
Verifies:
- the tracked cache (.hd/notes/<id>.md) is NOT overwritten with the
unacknowledged offline text (the false-sync/poisoning bug)
- the offline text is NOT just lost -- a recovery file under
.hd/offline-recovery/ contains it
- a clear warning is printed to the terminal after JOE exits
"""
import glob
import json
import os
import shutil
import socket as socketmod
import sys
import tempfile
import threading
import time
from pathlib import Path
import pexpect
import socketio
from werkzeug.serving import make_server
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
from hd_client import apply_operation
from hd_core import Config, Cookies, State, NoteState, content_hash
JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/repo/joe-patch/build/joe-4.8/joe/joe")
AGENT = str(Path(__file__).resolve().parent / "hd_joe_agent.py")
def apply_operation_strict(text, op):
for c in op:
if isinstance(c, bool):
raise ValueError(f"unknown operation: {c!r}")
if isinstance(c, int) and c == 0:
raise ValueError(f"unknown operation: {c!r}")
return apply_operation(text, op)
class StoppableFakeServer:
"""`go_silent` deterministically simulates "offline" from the CLIENT's
point of view without depending on how fast (if at all) a graceful
werkzeug shutdown() actually severs an already-established websocket --
tried that first; it's not reliable within a short test timeout, since
shutdown() stops accepting new work without necessarily tearing down
connections already open. Withholding acks is deterministic: the
connection stays technically up, but nothing the client sends after
go_silent is True ever gets acknowledged -- exactly what matters for
drain_pending()'s timeout and everything downstream of it.
"""
def __init__(self, port, initial_text):
self.text = initial_text
self.revision = 0
self.lock = threading.Lock()
self.go_silent = False
self.silently_received = []
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
@self.sio.event
def connect(sid, environ, auth):
with self.lock:
self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid)
@self.sio.on("operation")
def on_operation(sid, base_revision, operation, selection):
with self.lock:
if self.go_silent:
self.silently_received.append(operation)
return # accepted at the transport level, never acked
if base_revision != self.revision:
return
try:
self.text = apply_operation_strict(self.text, operation)
except Exception as exc:
print("[fake server] rejected:", exc, operation)
return
self.revision += 1
self.sio.emit("ack", self.revision, to=sid)
self.app = socketio.WSGIApp(self.sio)
self.srv = make_server("127.0.0.1", port, self.app, threaded=True)
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
def start(self):
self.thread.start()
def stop(self):
self.srv.shutdown()
def free_port():
s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM)
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port
def main():
port = free_port()
note_id = "n1"
initial_content = "---\ntitle: Masten\ntags: sl6cv\n---\n\nonline content"
server = StoppableFakeServer(port, initial_content)
server.start()
time.sleep(0.2)
tmpdir = Path(tempfile.mkdtemp(prefix="hd-offline-test-"))
root = tmpdir / "notes"
hd_dir = root / ".hd"
(hd_dir / "notes").mkdir(parents=True)
Config(url=f"http://127.0.0.1:{port}", email=None).save(hd_dir)
Cookies(header="session=1").save(hd_dir)
state = State()
(hd_dir / "notes" / f"{note_id}.md").write_text(initial_content)
state.notes[note_id] = NoteState(
title="Masten", tags=["sl6cv"], symlinks={"sl6cv": "Masten"},
content_hash=content_hash(initial_content), last_seen_time=1,
)
state.save(hd_dir)
tag_dir = root / "sl6cv"
tag_dir.mkdir(parents=True)
(tag_dir / "Masten").symlink_to(Path("..") / ".hd" / "notes" / f"{note_id}.md")
ok = True
child = None
try:
log_path = "/tmp/hd-joe-offline-test.log"
try:
os.remove(log_path)
except OSError:
pass
cmd = f'python3 {AGENT} "Masten" --joe {JOE_BIN} --log {log_path} --debug'
env = {**os.environ, "TERM": "xterm", "HD_DRAIN_TIMEOUT": "2.0"}
child = pexpect.spawn(cmd, cwd=str(tag_dir), env=env, dimensions=(24, 80), timeout=15)
time.sleep(1.0)
# --- while online: type something, confirm it reaches the server ---
child.send("\x0bv") # EOF
time.sleep(0.3)
child.send(" online-edit")
time.sleep(0.6)
check1 = "online-edit" in server.text
print("online edit reached server:", check1)
ok &= check1
# --- go "offline": the server keeps accepting the connection but
# stops acking anything from here on -- see StoppableFakeServer's
# docstring for why this, not an actual server shutdown, is the
# reliable way to simulate it in a test ---
server.go_silent = True
# --- keep typing -- this is the part that used to silently vanish ---
child.send(" OFFLINE-TEXT-SHOULD-BE-RECOVERED")
time.sleep(0.8)
# --- quit ---
child.send("\x0bx")
time.sleep(0.4)
child.send("\r")
try:
# expect(EOF), not wait(): we need pexpect to actually READ and
# buffer everything printed up to process exit (including the
# plain print()s the agent makes after JOE's own curses UI has
# torn down) so it ends up in .before -- wait() alone just
# blocks for the exit code without reading any output at all.
child.expect(pexpect.EOF, timeout=10)
except pexpect.TIMEOUT:
pass
pty_output = child.before.decode("utf-8", errors="replace") if child.before else ""
if child.isalive():
child.terminate(force=True)
time.sleep(0.3)
# --- the tracked cache must NOT contain the offline text ---
cache_text = (hd_dir / "notes" / f"{note_id}.md").read_text()
check2 = "OFFLINE-TEXT-SHOULD-BE-RECOVERED" not in cache_text
print("tracked cache does NOT contain offline text (not poisoned):", check2, repr(cache_text[-40:]))
ok &= check2
# NOT "still has the online edit": update_note_cache() is currently
# all-or-nothing -- any unacked pending operation (even one that
# arrived after other, already-acked edits in the same session)
# blocks the cache update entirely, so the cache stays at whatever
# the last fully successful sync left it at. Safe (never poisons),
# just not maximally granular -- a possible future refinement would
# track acked-vs-optimistic text separately and cache the acked
# portion. Asserting the ACTUAL current (conservative) behavior here.
check3 = cache_text == initial_content
print("tracked cache unchanged from before this session (conservative, not poisoned):", check3)
ok &= check3
# --- state.json's hash must still match the (unpoisoned) cache file ---
reloaded = State.load(hd_dir)
check4 = reloaded.notes[note_id].content_hash == content_hash(cache_text)
print("state.json hash matches the actual (unpoisoned) cache file:", check4)
ok &= check4
# --- a recovery file must exist, containing the offline text ---
recovery_files = sorted(glob.glob(str(hd_dir / "offline-recovery" / f"{note_id}-*.md")))
check5 = len(recovery_files) == 1
print("exactly one recovery file found:", check5, recovery_files)
ok &= check5
if recovery_files:
recovery_text = Path(recovery_files[0]).read_text()
check6 = "OFFLINE-TEXT-SHOULD-BE-RECOVERED" in recovery_text
print("recovery file contains the offline text:", check6)
ok &= check6
# --- a clear warning was printed to the terminal after JOE exited ---
check7 = "NOT saved to the server" in pty_output and "recovery" in pty_output.lower()
print("terminal warning printed after quit:", check7)
if not check7:
print("--- captured output tail ---")
print(pty_output[-800:])
ok &= check7
finally:
if child and child.isalive():
child.terminate(force=True)
try:
server.stop()
except Exception:
pass
shutil.rmtree(tmpdir, ignore_errors=True)
print("\nPASS" if ok else "\nFAIL")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())