Exercise unpaused typing and concurrent replica writes with random SIGKILL
3 files changed,
+56
−10
docs/testing/k3-evidence.md+16 −0native/apple/Tests/DocsKitTests/OfflineKillTests.swift+22 −7native/scripts/test-offline-kill.py+18 −3
CI passed — run details
diff --git a/docs/testing/k3-evidence.md b/docs/testing/k3-evidence.md| index 2aa16a2..77f2f02 100644 |
| --- a/docs/testing/k3-evidence.md |
| +++ b/docs/testing/k3-evidence.md |
| @@ -126,3 +126,19 @@ moved aside for full gates, preserved, then restored; Docs targets, framework, |
| - All 24 durability tests passed. Logs: `/tmp/k3-docs-review-{red,green}.log` (ephemeral); the red run had five expected assertions across three tests. The existing key-loss test was adjusted to create a fresh sealed store on simulated process restart: reusing the old instance now intentionally retains its cached key. |
| - Native pins (all five) advance to `0ff1de9d542ce96430e158708e62be04d87d65a4`; native final-head local `make ci` passed (119 Swift tests and remaining platform/Go/Python gates). Its hub runner still fails before tests on missing unzip / absent macOS infrastructure. |
| - Deferred as directed: review finding 4 (WASM decode per writer tick) belongs to K4/K7; finding 6 (sessionRestored on existing-account/window access) belongs to K5. No new K3 spec departure. |
| + |
| + |
| +Random SIGKILL mode: `native/scripts/test-offline-kill.py --random --seed 17` |
| +leaves typing unpaused and runs concurrent replica writer ticks. The controller |
| +kills after a seeded random delay, without a writer-side sleep/handshake. Recovery |
| +must contain the last atomically recorded durable text as a prefix, contain exactly |
| +the ordered k3 tokens (no gaps/duplicates/torn edits), then equal the real server. |
| +Failing-first control: stub the outbox write in DocsPersistence.enqueue while still |
| +advancing commandsDurable. Seed 17 killed at 0.260992 s; recovery was empty and |
| +failed the durable-prefix and ordered-token assertions (two failures). Restore the |
| +write: the same seed passed offline recovery and exact server convergence. Logs: |
| +`/tmp/k3-docs-review-kill-{red,green}.log`. The stub is not committed. |
| + |
| +Final-head gates and repeated kill runs are reported on #69; local logs use |
| +`/tmp/k3-docs-review-final-{gate,native,kill*}.log`. Build stages run serially, |
| +with rustup cargo first and TMPDIR=/tmp; xcodegen runs before xcodebuild. |
diff --git a/native/apple/Tests/DocsKitTests/OfflineKillTests.swift b/native/apple/Tests/DocsKitTests/OfflineKillTests.swift| index 6fbc1d1..89fd585 100644 |
| --- a/native/apple/Tests/DocsKitTests/OfflineKillTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/OfflineKillTests.swift |
| @@ -11,6 +11,7 @@ final class OfflineKillTests: XCTestCase { |
| guard let directory = env["DOCS_KILL_DIR"], let mode = env["DOCS_KILL_MODE"] else { |
| throw XCTSkip("Run native/scripts/test-offline-kill.py") |
| } |
| + let randomKill = env["DOCS_KILL_RANDOM"] == "1" |
| let root = URL(fileURLWithPath: directory) |
| let config = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: root.appendingPathComponent("connection.json"))) |
| let client = NativeHTTP(origin: URL(string: config["origin"]!)!, credential: NativeSession(name: config["name"]!, value: config["value"]!)) |
| @@ -29,25 +30,39 @@ final class OfflineKillTests: XCTestCase { |
| path.send(.unsatisfied) |
| while connectivity.isPathSatisfied { try await Task.sleep(for: .milliseconds(5)) } |
| try String(ProcessInfo.processInfo.processIdentifier).write(to: root.appendingPathComponent("pid"), atomically: true, encoding: .utf8) |
| - for index in 1...200 { |
| + // Exercise I1a with writer ticks racing command/enqueue. No sleep |
| + // or handshake freezes the typing process in random mode. |
| + let writer: Task<Void, Never>? = randomKill ? Task { |
| + while !Task.isCancelled { await model.persistReplica(); await Task.yield() } |
| + } : nil |
| + defer { writer?.cancel() } |
| + for index in 1...(randomKill ? 10_000 : 200) { |
| model.didRender(model.projectionGeneration) |
| let text = model.projection?.children.map(\.plainText).joined() ?? "" |
| XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(Double(text.utf16.count)), "length": .number(0), "text": .string("k3-\(index);")])) |
| - while model.hasPendingInput { try await Task.sleep(for: .milliseconds(2)) } |
| - if index == 12 { |
| + while model.hasPendingInput { await Task.yield() } |
| + if randomKill || index == 12 { |
| let expected = model.projection?.children.map(\.plainText).joined() ?? "" |
| try expected.write(to: root.appendingPathComponent("expected"), atomically: true, encoding: .utf8) |
| try Data().write(to: root.appendingPathComponent("kill-now"), options: .atomic) |
| // The controller kills us in the middle of this typing run, |
| // before the two-second replica writer can run. |
| - try await Task.sleep(for: .seconds(1)) |
| + if !randomKill { try await Task.sleep(for: .seconds(1)) } |
| } |
| - try await Task.sleep(for: .milliseconds(15)) |
| + if !randomKill { try await Task.sleep(for: .milliseconds(15)) } |
| } |
| XCTFail("The controller did not kill the typing process") |
| } else { |
| let expected = try String(contentsOf: root.appendingPathComponent("expected"), encoding: .utf8) |
| - XCTAssertEqual(model.projection?.children.map(\.plainText).joined(), expected, "Offline reopen must include every durable keystroke exactly once") |
| + let reopened = model.projection?.children.map(\.plainText).joined() ?? "" |
| + if randomKill { |
| + XCTAssertFalse(expected.isEmpty, "The controller must observe durable typing before killing") |
| + XCTAssertTrue(reopened.hasPrefix(expected), "Offline reopen must preserve the last recorded durable prefix") |
| + let tokens = reopened.split(separator: ";") |
| + XCTAssertEqual(reopened, (1...max(1, tokens.count)).map { "k3-\($0);" }.joined(), "Recovered text must have no gaps, torn edits, or duplicates") |
| + } else { |
| + XCTAssertEqual(reopened, expected, "Offline reopen must include every durable keystroke exactly once") |
| + } |
| path.send(.satisfied) |
| while !connectivity.isPathSatisfied { try await Task.sleep(for: .milliseconds(5)) } |
| await model.retry() |
| @@ -58,7 +73,7 @@ final class OfflineKillTests: XCTestCase { |
| try reply.requireSuccess() |
| let server = CRDTReplica(guid: model.detail!.guid) |
| let projected = try await server.open(update: reply.data) |
| - XCTAssertEqual(projected.children.map(\.plainText).joined(), expected, "Real server converges after the killed client's lane drains") |
| + XCTAssertEqual(projected.children.map(\.plainText).joined(), reopened, "Real server converges after the killed client's lane drains") |
| await server.close(); await model.stop(); account.drainer.stop() |
| } |
| } |
diff --git a/native/scripts/test-offline-kill.py b/native/scripts/test-offline-kill.py| index 8857691..294b624 100755 |
| --- a/native/scripts/test-offline-kill.py |
| +++ b/native/scripts/test-offline-kill.py |
| @@ -3,6 +3,8 @@ |
| against real authenticated Docs handlers, and compare the server snapshot. |
| Requires the CRDT framework built by check-native.sh; never touches user data. |
| """ |
| +import argparse |
| +import random |
| import os |
| from pathlib import Path |
| import signal |
| @@ -10,6 +12,12 @@ import subprocess |
| import tempfile |
| import time |
| +parser = argparse.ArgumentParser(description=__doc__) |
| +parser.add_argument("--random", action="store_true", help="kill during unpaused typing and concurrent replica writes") |
| +parser.add_argument("--seed", type=int, default=None, help="reproduce the controller's random delay") |
| +args = parser.parse_args() |
| +seed = args.seed if args.seed is not None else random.SystemRandom().randrange(2**32) |
| +kill_delay = random.Random(seed).uniform(0, .5) |
| root = Path(__file__).resolve().parents[2] |
| def wait_for(path, process, timeout=300): |
| @@ -23,7 +31,7 @@ def wait_for(path, process, timeout=300): |
| with tempfile.TemporaryDirectory(prefix="docs-k3-kill-", dir="/tmp") as tmp: |
| scratch = Path(tmp) |
| - env = dict(os.environ, DOCS_KILL_DIR=tmp, TMPDIR="/tmp") |
| + env = dict(os.environ, DOCS_KILL_DIR=tmp, DOCS_KILL_RANDOM="1" if args.random else "0", TMPDIR="/tmp") |
| server_log = (scratch / "server.log").open("w") |
| server = subprocess.Popen(["go", "test", "./internal/docs", "-run", "^TestNativeKillServer$", "-count=1", "-timeout=8m"], cwd=root, env=env, stdout=server_log, stderr=subprocess.STDOUT, start_new_session=True) |
| writer = None |
| @@ -34,11 +42,18 @@ with tempfile.TemporaryDirectory(prefix="docs-k3-kill-", dir="/tmp") as tmp: |
| writer = subprocess.Popen(command, cwd=root, env=dict(env, DOCS_KILL_MODE="write"), stdout=log, stderr=subprocess.STDOUT, start_new_session=True) |
| wait_for(scratch / "kill-now", writer) |
| assert ": error:" not in (scratch / "writer.log").read_text(), "typing assertions failed before kill" |
| + if args.random: |
| + # Only the controller waits; the editing process never pauses |
| + # for us and can die during a command, enqueue, or writer tick. |
| + time.sleep(kill_delay) |
| pid = int((scratch / "pid").read_text()) |
| os.kill(pid, signal.SIGKILL) |
| result = writer.wait(timeout=20) |
| assert result != 0, "typing process unexpectedly succeeded" |
| - print("SIGKILL delivered after 12 durable edits, before coalesced replica write", flush=True) |
| + if args.random: |
| + print(f"SIGKILL during unpaused typing + writer ticks (seed={seed}, delay={kill_delay:.6f}s)", flush=True) |
| + else: |
| + print("SIGKILL delivered after 12 durable edits, before coalesced replica write", flush=True) |
| recovered = subprocess.run(command, cwd=root, env=dict(env, DOCS_KILL_MODE="recover"), capture_output=True, text=True, timeout=120) |
| if recovered.returncode: |
| print(recovered.stdout) |
| @@ -46,7 +61,7 @@ with tempfile.TemporaryDirectory(prefix="docs-k3-kill-", dir="/tmp") as tmp: |
| raise RuntimeError("offline recovery / real server convergence failed") |
| (scratch / "done").touch() |
| assert server.wait(timeout=15) == 0, "real server fixture failed" |
| - print("PASS: offline reopen exact; real server converged; no duplicate text", flush=True) |
| + print("PASS: offline reopen preserves recorded prefix; real server equals reopened replica; no gaps or duplicate text", flush=True) |
| except Exception: |
| # Logs contain only test-generated state. Never print connection.json. |
| for name in ("server.log", "writer.log"): |