HarmonyOSArkTSConcurrencyGoodCRM

After Hitting THREAD_BLOCK_6S: Moving GoodCRM's HarmonyOS RelationalStore Off the Main Thread

On HarmonyOS, running full state validation on the UI thread triggered a real THREAD_BLOCK_6S freeze. Moving RelationalStore and AsyncLibraryService into a ThreadWorker solves the hang only if requests freeze raw bytes before the first await and fence late replies with scope, epoch, and lease revisions.

GoodCRM (1.0) is live on the US App Store (id6837223780) for iPhone, iPad, and Mac, while the native HarmonyOS build for phones and tablets is still in preparation. Because there are no developer-operated CRM servers, the HarmonyOS client persists everything locally through ArkTS and RelationalStore.

Early on, the shared execution path ran StateValidation and duplicate checks directly on the UI main thread. Once exercised on a phone, it hit a real THREAD_BLOCK_6S freeze — not an out-of-memory crash, just a main thread stuck past six seconds.

Moving RelationalStore into a background ThreadWorker sounds straightforward until you trace what changes across the boundary: the UI thread can no longer share live domain objects with the store, and it can no longer retry blindly when a Worker vanishes mid-commit.

Freeze Raw Request Bytes Before the First await

Under the v4 boundary documented in ASYNC_LOCAL_SERVICE.md, openExisting, initialize, full State decoding and validation, and AsyncLibraryService all run inside a single ThreadWorker.

The UI thread is limited to lightweight Preferences descriptor checks and read-only display projections. Before any write crosses the Worker boundary in WorkerLibraryClient.ts (call()) and LibraryWorkerProtocol.ts, the caller’s inputs are frozen synchronously:

scope = freezeWorkerScope(invocation);
const request: LibraryWorkerRequest = {
  method,
  binding: this.binding(),
  scope,
  envelope_text: envelope === null ? null : freezeWorkerEnvelope(envelope),
  token: token === null ? null : copyWorkerToken(token),
  operation_id,
  migration
};

That freeze completes before the first await.

If a user keeps typing or mutates a form object while an asynchronous send is suspended, the queued Worker request must stay untouched. freezeWorkerEnvelope rejects duplicate UTF-8 keys and nesting deeper than 253 levels (RESOURCE_LIMIT), preventing pathological payloads from entering the RPC layer. Likewise, PreparedToken’s envelope_utf8 (Uint8Array) is copied via envelope_hex in wireToken/fromToken, so zeroing out the caller’s buffer immediately after executePrepared never corrupts the pending execution.

Serializing One Handle Still Needs Epoch and Lease Fencing

Inside the Worker, AsyncLibraryService.ts serializes mutations through a tail FIFO queue (enqueue), and RelationalWorkerCoordinator.ts serializes querySubjects and consumeSubjectIndex over the same single handle through dispatchRelationalWorkerRequest. Cross-session exclusivity still rests on SQLite IMMEDIATE transactions.

A single FIFO queue does not stop stale results across reconnects or competing sessions:

  1. Client epoch fencing: Calling reconnect() in WorkerLibraryClient.ts increments this.epoch. If an older readSnapshot finishes after reconnection, epoch !== this.epoch causes it to return WORKER_CONNECTION_SUPERSEDED instead of overwriting the fresh snapshot or quarantining the healthy connection.
  2. Lease fencing (lease_owner_session_id + pending_revision): A PreparedToken binds store_id, local_copy_id, operation_id, material_sha256, pending_revision, and the AsyncLibraryService instance’s session_id UUID. If another session reclaims the pending row via recoverOriginal or recoverPreparation, pending_revision increments and ownership transfers, causing any late executePrepared with the old token to fail with PREPARED_TOKEN_STALE.

On the query side, RelationalWorkerProtocol.ts verifies scope.binding, editing_session_id, and request_id on every response, rejecting mismatches with WORKER_RESPONSE_SCOPE_MISMATCH.

Unknown-Commit Recovery: Quarantine Rather Than Guess

The nastiest failure window is a Worker crash (worker_exit) during submit or executePrepared — it might die before dispatch, or right after SQLite COMMIT succeeds before the ACK reaches the UI thread.

WorkerLibraryClient.ts refuses to speculate: any transport failure in an uncertain phase returns result_unknown (WORKER_OUTCOME_UNKNOWN, retained_pending: 'unknown') and flips the client handle to quarantined, blocking new mutations with SESSION_QUARANTINED.

The UI is not allowed to mint a fresh operation_id and resend, which would duplicate records if the original commit had already landed. Instead, recovery follows two explicit paths:

  • recoverPreparation(originalEnvelope, scope) reconnects and re-submits the caller’s exact frozen original envelope. If state.receipts already contains that operation_id, duplicate() returns the stored receipt while reading the business Clock zero times (any clock read triggers RECOVERY_CLOCK_FORBIDDEN). If it never committed, it persists or re-leases the pending row; attempting to reuse the same operation_id with modified bytes fails with OPERATION_REUSED.
  • recoverOriginal(operation_id, scope) reconnects, reads the durable pending row by operation_id, and issues a fresh lease without guessing intermediate state.

Shutdown is ordered too: close() sets this.closing = true to reject new callers immediately, awaits every promise in this.inflight (including in-flight COMMIT ACKs), and only then closes the transport.

What the Host Suite Proves — and What It Doesn’t

In apps/harmony/tests/library-worker.test.ts (docs/review/execution-20261109/rdb-native/worker-review/), npm run typecheck exited 0 and all 14/14 RPC tests passed:

  • All 14 command families (CreateOrganization, CreateContact, CreateMatter, CreateAction, SaveInteraction, ReviewWaiting, RescheduleAction, ResolveAction, ArrangeNext, ReopenAction, ContinueWithNext, CancelAction, EditContactMethods, CloseMatter) verified against an independent full-entity write-set oracle.
  • Fault injections covering worker_exit before and after COMMIT, mismatched local_copy_id or request_id, malformed JSON, late old-epoch replies, revoked leases, and depth 251–254 envelope boundaries.

The boundary is explicit: library-worker.test.ts runs against InProcessTransport and a mechanical row/lock fake to pin down protocol, lease, and recovery semantics. Real ThreadWorker scheduling, native RelationalStore commits, and physical device cold restarts are verified separately on native HarmonyOS builds rather than inferred from this host suite.

✦

Comments

  • Loading…

Comments are reviewed before publishing; email is visible only to me.