Compare commits

...
Author SHA1 Message Date
swung0x48 e6c51d0711 [MG_Test, CI] (P6): the last two readers the role split left behind
build-linux-verify could not compile PipeStatsTest: RoleDerivedJsonDumpPathForTesting is DISAGGREGATED-only and the verify flavour is deliberately monolith. The case name stays registered and GTEST_SKIPs there, matching the PIPE_PUSH pattern, so ctest -N still matches between flavours.

runtime_mode_proof.py logs opened MOBILEGL_LOG_FILE_PATH as a file. After the split that name is a base and the sink writes <base>.client.log / <base>.server.log, so the inproc proof died on FileNotFoundError after a green lane. It now reads through split_log_paths' role helpers and names the paths it looked for when none exist.
2026-09-22 04:40:03 -04:00
swung0x48andClaude Fable 5.1 2ec8e7f4a1 [docs] (P6): the closeout - gates 7 and 8 are measured and P6 is closed
The device gate: Redmi 2f7cbe2e, reboot-clean, paired A/B in one thermal
window (arms interleaved, best-of-3 then best-of-2), rd12 + DirectGLES.
inproc vs spawn client CPU p50 7.880/7.889 vs 7.876/7.869 (-0.15%) and
7.987/7.989 vs 7.992/8.009 (+0.16%) - a tie inside the 0.2-4.2% within-
arm spread, sign flipping with arm order, recorded and not gated.
monolith is ~30% dearer. 22/22 runner exits clean, 44/44 PINNED, zero
Fatal.

The three mandatory numbers: socket doorbell vs condvar is a tie too -
client 121.1 waits/frame identical across transports, server 10 866-11
963 (inproc) vs 10 415-10 416 (spawn) waits/frame, and the contract's
'converting that into ~4 blocking reads may be cheaper' did not pay off;
the only column where the socket is worse is clipark/f (6.07 vs 5.60/5.75).
SEG_STAGE bytes/frame: 130.8 KB median / 8.01 MB steady (OpenRA), 816.2
KB / 1.53 MB (rd12). Records/frame post-chunking: 211/206 and 7 497/7
504. maxrec stays 1808 - the 8 MiB chunk budget is never reached. Both
framings reported throughout (the startup window runs ~7x the steady
state) rather than the flattering one.

MEASUREMENTS.md gains section 12 with the full protocol and tables; the
6.3 'no post-chunking distribution exists' gap now points there.
CURRENT_STAGE_PROGRESS.md marks gates 7/8 met and records the closeout
work plus two structural limits (spawn client windowed fields are zero
by construction - OnPresent runs in the server process - though its run
totals are valid stores; the stats dump is role-derived). ROADMAP marks
P6 closed in the stage table, the header and the milestone.

Evidence: notes/p6/gate7-device-ab.md, gate8-doorbell-device.md,
gate8-wire-counters.md, git-worktree-fix.md. check_doc_citations: 82
citations in the three documents, 0 problems.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 03:38:17 -04:00
swung0x48andClaude Fable 5.1 bf3e6f8ad3 [MG_Util, MG_Remote, tools] (P6): the wire counters and the spawn server's stats latch
Gate 8's last two numbers (SEG_STAGE bytes/frame, records/frame post-
chunking) had no producer at all: the summary line's byte classes are
backend-to-driver bytes and maxrec is a max, not a per-frame. Two push-
guarded counters answer them at their single choke points - ByteClass::
StageSegmentBytes at PipeWireCodec's StageAllocate (the only allocation
behind StageBytes, so every buffer walk, texture slab and CSO archive
lands there and emitters cannot double-count) and CallClass::WireRecords
on EncodeRecord's committed path (post-chunking an emitter no longer
knows how many records its one call produced). A staged-blob histogram
rides along. G1 holds: symbols 0/0/0/0, .text byte-identical, pull build
carries no MG_Remote symbols.

The spawn server never counted anything: PipeStats::Init() is a step of
MobileGL::Initialize(), which ServerMain never reaches, so every Enabled()
site in that process - including ServerLoop's own ServerWaits/ServerParks
publish - stayed false and the server log carried no summary line at all
(a zero that means 'another process' printed in the shape of one that
means 'never waited' is the milder misreading; the line was simply
absent). ServerMain now arms and closes PipeStats at its role boundary -
after MG_ConfigLoader::Init (Init latches from the parsed config), after
the server-role latch (the log sink's role), and before ::_exit(0).
Red-once: 0 server summary lines before, 29 after, SSIM 1.0 unchanged.

MOBILEGL_PIPE_STATS_FILE now derives per role through the log sink's
exported RoleLogPath rule - run.client.json / run.server.json, the bare
name resolves to no file - because both roles reach FormatJson() and ofstream
trunc made the second writer replace the first. G1 caught three separate
leaks on the way (a string temporary in the monolith body, one resized
Shutdown() from unequal #if arms, two rewritten MGLOG_W literals in
.rodata); the pull arm is statement-for-statement the original.

Device tooling for the paired A/B lands with it: pin_device.sh gains a
measured 2f7cbe2e entry (this board clamps the GPU at 1050 MHz -
thermal_pwrlevel writes 0 and reads back 1, max_gpuclk is read-only;
absolute times are not comparable with the 1100 MHz-era rows), and
tools/device_bench/p6/ carries the session collector and renderer beside
run_android_retrace_local.py's MOBILEGL_TRACE_PACKAGE override.

Unit 2367/2367 (PipeStats 25/25), spawn integration 102/102.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 03:37:51 -04:00
swung0x48andClaude Fable 5.1 2bd86664ec [docs] (P6.5): the design for the first wave - all-TCP transport, WSL client to adb-device server
ROADMAP gains the section "the immediate next item": a design, not an
implementation, for running the frontend on an x86_64 WSL process and the
backend on the Redmi over TCP, with the integration lane and the CI retrace
subset as the acceptance. The P6.5 row now points at it.

What the design rests on, verified in the tree: the control plane already
treats the rendezvous as a NAME with two ordered connections (SocketTransport),
ClientSession::StartOverSocket already separates "how the socket came" from the
handshake, MGPBlobRef addresses kSegStage only through one ResolveOrFatal, the
reply header and the event heads are already wire-shaped, LogLine exists in
CtrlMsg with no producer, goldens are shared between desktop and device, and
the trace APK can already exec libMobileGLServer.so from nativeLibraryDir.

What it does not rest on, stated rather than assumed: ILink is declared and
unused beyond LinkProgress, ShmLink does not exist, both sessions hold
SessionSegments directly - the lk seam body from the end-state review was never
built and is this wave's first package (lk2). The manifest has no INTERNET
permission.

The mechanism: StreamLink as mirrored private segments replicated by messages -
same sizes both ends, same offsets, so the codec, the watermark rules, the apply
thread and the encoder do not change; RingControl becomes Progress frames sent
on flush-on-idle (the recorded amendment to "appliedSeq is never lazy": late by
at most one flush, never early); replies become seq-stamped messages; the event
ring is mirrored with the P5e blocking rule intact. Cross-architecture makes
the PipeFields.def layout digest mandatory (wf). Server logs on another machine
make LogLine forwarding mandatory (lf) so the 34 server-log readers stay
unchanged. A --serve supervisor forks one child per session on the device,
started by a foreground Service in the trace APK.

Packages lk2 -> wf -> ct -> sl -> lf -> sv -> t65, each with red-once; the gate
list, the mandatory numbers (kWaitReply per frame x RTT, SEG_STAGE bytes/frame
against the link, PRESENT_CREDIT 1..3), the two-sided configuration runbook and
the risks (RTT per reply row, single large uploads, AP isolation) are in the
section. check_doc_citations: 74 citations, 0 problems.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 03:04:50 -04:00
swung0x48andClaude Fable 5.1 2d86e07ab6 [docs, MG_Remote] (P6->P6.5): the end state is TCP across machines, and the transport stack has two axes
The end state is re-ruled: client and server may sit on different machines,
OSes and architectures, joined over TCP. The AVF pVM / AF_VSOCK end state the
P6 end-state review assumed is withdrawn (retraction at its head, form D added
to its table, the vsock probe and both external unknowns struck).

The transport stack becomes two independently selectable axes, negotiated in
the handshake and mixable: control plane (ITransport: fork / unix:<path> /
tcp://host:port) and data plane (ILink: ShmLink / StreamLink). On one machine
control over TCP with data over shared segments is a legal pair; ShmLink brings
its own AF_UNIX aux rendezvous for SCM_RIGHTS, so ITransport narrows to control
frames. `auto` is decided by a successful segment delivery, never by inspecting
addresses, and a fall-back is named. Nothing above Transport/ may branch on the
link kind. ARCHITECTURE.md gains 11.9 for this; CONTRACT-P6.md gains 10.3.

ROADMAP: P6.5 and Ph get rows (both were referenced by the contract and absent
from the stage table); the IPC track becomes P6 -> P6.5 -> Ph -> P12 -> P9 ->
P10 -> P11(same-machine arm). Every later row is reconciled against the tree:
items already landed are struck (client vertex arrays, client-minted query
handles, credit default 1, SEG_EVENT overflow mechanism), the unreachable P7
gate (`nm | grep glslang` on a server image that IS libMobileGL.so) is replaced
by the 184-symbol ratchet share, fixed-width wire form moves from P7 to P6.5,
P12 is cut down per the review (server-owned display, no Surface passing), and
the debt table's stale claims are corrected: class C is down to two slots, not
15 and not 511; PACK-PBO and the 2 MiB reply cap are P9's, not P6's.

Verified against the tree and recorded honestly: the contract's three hs rows
(LinkTerms, Refuse, the fingerprint split) never landed - protocol.fbs has
neither - so CURRENT_STAGE_PROGRESS.md's claim that S6 ran red is withdrawn and
the rows move to P6.5; the 184-symbol ratchet gate does not exist in CI; the
server process never initialises PipeStats, so gate 8's `srv=0 srvpark=0` is a
structural zero (fix in progress in the tree, not in this commit).

check_doc_citations.py: 159 citations, one pre-existing basename ambiguity.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 02:17:18 -04:00
swung0x48andClaude Opus 5 71aa995128 [MG_Util, MG_IntegrationTest, CI] (P6): the readers the role split left behind
The per-role log split renamed BOTH halves so that an un-updated reader would
fail loudly instead of silently reading half a session. It worked: CI found
four readers this way. This is them.

- MG_Util/Debug/Log.h: the role vocabulary now exists in the PULL build too,
  header-only. It was wholly inside #if MOBILEGL_BUILD_DISAGGREGATED, so
  PipeInputsTest - which builds in the verify flavour - could not name
  ReadRoleLogs and took the whole build-linux-verify job down at compile time.
  Inline rather than out-of-line because of G1: nothing in the library calls
  these, so an inline definition emits code into the readers and NOTHING into
  libMobileGL.so. Verified: pull symbols 30570 -> 30570, 0 added / 0 removed,
  .text still 0xa52203, and zero role-log symbols in the pull library.

- PipeStatsWindow.h: the harness copy of the naming rule is now flavour-aware.
  It derived `.client` in BOTH flavours, so in the verify build - one role,
  MOBILEGL_LOG_FILE_PATH written unchanged - it opened a file that never
  existed. The copy has to stay a copy: MG_Util's RoleLogPath is `t` (local)
  in the shipping .so this module links, so calling it does not link.
  Added LogMark/MarkLaneLog/ReadLaneLogSince: one offset PER ROLE, because a
  single scalar over the concatenation slides by whatever the other role wrote.

- The four arming scenarios: they asserted on lines the BACKEND emits, and
  under inproc the backend runs on the apply thread - the server role - so the
  line lands in the server's log. Reading only the client's half reported the
  emulation unarmed, i.e. accused the product of a defect the reader invented.
  Four copies of the same private helper pair now delegate to the harness.

- scripts/ci/magma_runahead_checks.py: it unlinked and read the base name as
  if it were a file, so the negative arm saw an empty log and could not prove
  the knob took. It now imports split_log_paths' derivation - the authoritative
  one - rather than becoming a third copy.

Local verification (WSL, lk-split + c6-pull):
  - the 4 CI-red entries: 10/10 PASS under inproc, 10/10 under monolith
  - unit role-log readers: 510/510 PASS
  - magma_runahead_checks negative: run_ahead_0 EXPECTED_RED, restored GREEN
  - the 5 affected TUs compile clean with MOBILEGL_BUILD_DISAGGREGATED=0
  - G1: 0/0/0/0, .text 0xa52203

Red-once is the CI run itself (35677991453), which failed for each of these
reasons before the change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 00:37:39 -04:00
swung0x48andClaude Opus 4.8 98d0b96cbe [docs] (P6): the roadmap and the current-stage doc record P6 as landed-not-closed
All ten P6 packages (a6/c6/lk/so/sm/cp/hs/dl/st/t6) are on feat/disaggregated
through 16bfab10. The two docs now say so honestly:

- ROADMAP.md (cumulative): the status line, the P6 stage row, and a new
  milestone bullet record every package landed, exit-gate items 1-6 met, and
  items 7 (device paired A/B in one thermal window) and 8 (the three mandatory
  perf numbers) still pending -- so P6 is "implementation complete, exit
  perf/device numbers pending", NOT closed.
- CURRENT_STAGE_PROGRESS.md: rewritten to hold ONLY the current stage. All
  P5* history is gone (it lives in ROADMAP.md and the P5* reports); what
  remains is P6's package table, the CONTRACT-P6 section-9 gate with each
  item's honest status, the device results, the per-role log split, and the
  explicitly-not-P6 list.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 22:02:15 -04:00
swung0x48andClaude Opus 4.8 16bfab1032 [MG_Remote] (P6/dl): record the Session::Fail funnel as landed in the contract
§5.2 gains a LANDED note: the three steps (the FatalFamilies.def vocabulary,
the SessionFail funnel that byte-identically routes ~90 aborts through one
place, and the SessionFault frame that names the family to the peer), and the
one deliberate deviation from the prose - seq/op are not threaded through the
90 sites because the message already names the op, so the frame carries code,
family and message rather than a field that is always zero.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:52:18 -04:00
swung0x48andClaude Opus 4.8 91d0cb78c7 [MG_Remote] (P6/dl): a dying session names itself to the peer
Step three of CONTRACT-P6 5.2, the funnel's whole point: instead of the peer
reading a bare EOF and guessing, the session publishes a SessionFault frame
that names the family before it aborts.

THE WIRE CHANGE IS D2's, exactly: `table Fatal` appends `family: string`,
append-only, so an older peer still reads `code` and `message`. `code` stays
the coarse seven-value projection; `family` carries the full word.

SessionFail publishes it before the abort, on whichever session's control
plane is active - the client has a ClientSession, the server a ServerSession,
so under spawn the frame reaches the far side whichever role is dying. Under
inproc both exist and it goes to an in-process transport the aborting process
will never read, which is harmless and cheaper than a special case that would
then be the untested one. Best-effort by nature: this thread is about to die,
so a send that blocks or fails changes nothing.

seq/op from the prose are NOT threaded through the 90 sites: the message
already names the op where it matters, so the frame carries what it can name
honestly (code, family, message) rather than a field that is always zero.

The client recognizes it: RunRemoteSurfaceControlFrame's reply loop, which
already demuxes CapsSnapshot from SurfaceReply, gains a Fatal arm that logs the
family and detail, latches device-lost from it, and returns transport-closed.
A server that DETECTS a fatal condition and aborts itself now tells the client
why; a kill -9 still bypasses abort entirely and is caught by dl's hangup
witness instead - the two cover the two ways a server can die.

The census learns SessionFail: a SessionFail call, like a WireLogFatal call,
must carry a Fatal{ word in its string, so the enum and the string cannot
disagree. FatalFunnel.{h,cpp} join the funnel exemption. Baseline is 4 aborts.

FatalFamilyTest gains the wire round-trip: every family's frame carries its
word and its projected code across encode/verify/decode.

G1 re-measured after the schema change: 0 symbol diff, .text unchanged at
0xa52203. Unit 2359 (one pre-existing environmental failure), integration-split
186/186, integration-spawn 102/102, retrace 6/6, census 0 unmarked.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:51:50 -04:00
swung0x48andClaude Opus 4.8 5968863fb9 [MG_Remote] (P6/dl): every session death goes through one funnel
Step two of CONTRACT-P6 5.2. The ~90 scattered `MGLOG_F("...Fatal{...}"); std::abort();`
pairs under MG_Remote/ become one call each to SessionFail(MGFatalFamily, fmt, ...),
which logs, echoes to stderr, counts, and aborts in one place. a6's census
found no single chokepoint existed; now there is one, and step three hangs the
SessionFault-to-peer publish off it.

THE MESSAGE STRING IS PASSED VERBATIM. The contract requires the log lines, the
CI greps and every red-once byte-identical, so SessionFail does not compose the
line from the family - it takes the SAME string the site handed MGLOG_F and
forwards it unchanged. The family enum rides alongside, redundantly, so the
funnel has the coarse wire FatalCode without parsing the string. The census now
checks that redundancy the way it checks WireLogFatal: every SessionFail call's
string must carry a Fatal{ word, so the enum and the string cannot silently
disagree.

The conversion was mechanical - 89 sites by a transform that injects the family
as MGLOG_F's new first argument and drops the trailing abort - with three sites
fixed by hand that the transform would have broken: a stub macro, and two
if/else-then-shared-abort blocks (PersistentMapTracker's adopt-tier and
SurfaceOpCodec's three surface-error branches) where a naive rewrite stole the
abort from the earlier branches and would have let them fall through. The
death tests are the safety net for byte-identity, and every one stayed green.

Four std::abort() remain under MG_Remote/, all inside the two funnels
(WireLog.cpp, FatalFunnel.cpp); the census exempts both files because their
callers carry the family word, and its baseline drops from 93 aborts to 4.
SessionFaultCount() is the one telemetry point S8 will assert zero over a good
run.

G1 re-measured: 0 symbol diff, .text unchanged at 0xa52203 (FatalFunnel and
FatalFamily live under MG_Remote/, compiled only in the disaggregated build).
Unit 2358 (one pre-existing environmental failure), integration-split 186/186,
integration-spawn 102/102, retrace 6/6, census 0 unmarked.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:44:17 -04:00
swung0x48andClaude Opus 4.8 f98f2067db [MG_Remote] (P6/dl): the Fatal-family vocabulary as a table, projected onto the wire's seven codes
CONTRACT-P6 5.2's D2 ruling, step one of the Session::Fail funnel: the internal
vocabulary before the funnel that routes through it.

a6 censused thirty family words against a seven-value wire FatalCode, so
Session::Fail(FatalCode, detail) cannot carry the vocabulary in its first
argument - the word would collapse to one of seven and the log would say
ProtocolCorruption where the code said UnmigratedVerb. FatalFamilies.def is the
internal enum; the wire keeps FatalCode; each row carries the coarse code the
PEER is told when that family ends the session.

THE PROJECTION IS A TOTAL TABLE, NOT A SWITCH WITH A DEFAULT. This build has no
-Werror anywhere, so a default arm would silently swallow a family added
without a code. A row IS the arm; a family with no row is not a value of the
enum. FatalFamily.h generates the enum, the projection and the name from the
one .def, so a family, its word and its code cannot drift apart.

The buckets are documented per row in the .def: ProtocolCorruption for
malformed records / unimplemented verbs / role invariants / reply-contract
breaks; RingOverrun for a ring or event channel overrun; SegmentMismatch for a
segment too small for what a role must place in it; AbiMismatch for layout or
version disagreement; ServerCrashed for the liveness ends a WAITING peer
attributes to the other side. DeviceLost gets no row on purpose - it is armed
from the doorbell (5.3), never raised as a Fatal, and a test asserts no family
projects onto it so an abort can never masquerade as a device loss.

Five tests, all walking the table so a new row is covered without editing them:
count agreement, every family projects to a non-None code, none projects onto
DeviceLost, names distinct and non-empty, and a handful of anchors pinned by
meaning so a bulk-edit drift is caught.

No call site changes yet; the funnel that uses this is the next step.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:33:05 -04:00
swung0x48andClaude Opus 4.8 b3155525e8 [MG_Util, MG_Test, MG_IntegrationTest, CI] (P6): one log per role, and every reader moved with it
The spawn work had the two roles append to one MOBILEGL_LOG_FILE_PATH under
O_APPEND. It was correct - two processes at one offset would corrupt the file,
O_APPEND made each write atomic - but it put two sessions' lines in one place
and made every per-side assertion a search. This splits the sink: the client
role writes <base>.client.log and the server role writes <base>.server.log.

THE BASE NAME NAMES NO FILE ANY MORE, AND THAT IS THE POINT. Leaving the
client at the old unsuffixed path would have been the compatible choice and the
wrong one: a reader that was not updated would go on finding a file, go on
passing, and go on seeing only half the session - and a refusal census that
reports a confident zero for the half it cannot see is worse than one that
fails. With both names moved, an un-updated reader gets "file not found" and
says so. There were 34 such readers; every one is moved here.

THE ROLE IS PER-THREAD, not per-process, because under inproc both roles are
threads of one process. Log.cpp keys the sink on a thread-local role: the apply
thread declares itself server (ServerLoop.cpp), a spawned image is server for
its whole life (MOBILEGL_IPC_ROLE=server, read once), and everything else is
the client. The naming rule (RoleLogPath) and the two whole-log operations
(ReadRoleLogs / TruncateRoleLogs) are EXPORTED from the library, so no reader
reimplements the derivation - a second copy is the copy that falls behind.

Readers, by how they read:
 - unit mains set MOBILEGL_LOG_FILE_PATH and read a role file: they keep the
   base in the env and derive the client path from the library helper.
 - the death-test child runners (ReadLog) now concatenate BOTH roles: a death
   test asserts the CHILD said something, and the applier's refusals - the very
   diagnostics these check - are written under the server role.
 - the offset-based Emit readers derive the client path once after setenv.
 - PipeStatsWindow reads both, because draws/vbs increment in the backend's
   PrepareForDraw - the apply thread, the server role - so the summary line is
   in the server file even under inproc.
 - run_trace_case.cmake's split census reads both files; the client keeps the
   transport markers.
 - split_log_paths.py (and its self-test, and the control stub) derive both
   role files from the declared base.
 - the Android script pulls both role files off the device and concatenates
   them, so every downstream check is unchanged - and it judges a role file by
   CONTENT, because `run-as test -f` through `exec-out` returned 0 for a missing
   file on the device and `exec-out` folds cat's own not-found line into stdout.
   The monolith arm legitimately has no server file, and that is a silent skip
   rather than a one-line server log.

Guarded so a pull build is untouched: RoleLogPath and the role sink are wholly
inside MOBILEGL_BUILD_DISAGGREGATED; a non-disaggregated build writes the base
path exactly as before. G1 re-measured - 0 symbol diff, .text unchanged at
0xa52203.

Verified on device 2f7cbe2e: monolith writes only the client log (no phantom
server log), inproc and spawn each write both and pass their transport proofs
(spawn: server role in pid 16125). Unit 2353 (one pre-existing environmental
failure), integration-split 186/186, integration-spawn 102/102, retrace 6/6,
control smoke 12/12, split-log-paths self-test 9/9.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-21 21:26:05 -04:00
swung0x48andClaude Opus 5 8cd00f42fd [MG_IntegrationTest, CI] (P6/t6): integration-spawn, and the set identity made structural instead of maintained
Exit gates 9.2 and 9.3. Until now nothing ran the integration suite across a
process boundary at all - the spawn shape was proven only by the retrace lane,
which exercises one trace per case and no scenario assertions.

integration-spawn: 102 cases, 102 green.

THE SET IDENTITY IS THE POINT, AND IT IS NOT MAINTAINED BY HAND. 9.2 asks that
the spawn lane's case-name set equal the split lane's. Registering the spawn
arm as a second copy of each block would satisfy that today and drift the first
time somebody adds a scenario to one of them - and a spawn lane covering LESS
goes green while proving less, with nothing about a smaller green lane looking
wrong. The eleven split-environment blocks become eleven calls to one macro
that emits BOTH arms from one filter, so a case added to either is added to
both or to neither.

scripts/ci/spawn_lane_parity.py asserts it anyway, because a macro is one edit
from a hand-written block. It compares SETS rather than counts - a count can
agree while the membership does not - and carries exactly one sanctioned
asymmetry, named in the file: integration-split also labels the PUSH-MONOLITH
arm, whose scenario is monolith-only by construction. R-16: introduce a
split-only block and it reds naming the case and the macro to use.

THREE CASES SKIP UNDER SPAWN, BY NAME. CtWireScenario reads PipeApplier's
in-process tallies through ServerVerbs(); under spawn those live in the SERVER's
process and this one's copy is 0 forever, so the assertions were failing about
somebody else's memory. That is a harness limit, not a product defect - the
records themselves cross, which the retrace lane proves. They are SKIPPED and
not deregistered: a case dropped from the registration would make the two sets
differ silently, which is the drift the macro exists to prevent. What retires
the skip is cross-process telemetry, which is also what S8's SessionFaultCount
needs.

TWO REAL REGRESSIONS THE EXISTING GATES CAUGHT, both from this refactor:

  * the macro dropped the per-block TEST_LIST variables, which were what
    SplitLogPaths fed to give every entry a PRIVATE MOBILEGL_LOG_FILE_PATH.
    SplitLogPaths.PrivateAndDistinct went red naming the first orphan. The
    macro accumulates list NAMES now, so a block added later is covered without
    anyone remembering to extend a list - and the names have to be unique,
    because gtest_discover_tests' TEST_LIST is populated when CTEST runs, not
    at configure time, so one shared variable held only the last block's
    entries. That matters more on the spawn arm: there TWO PROCESSES append to
    the path, so a shared file interleaves two sessions rather than merely
    being ambiguous.

  * the configure_file that substitutes those names ran BEFORE the F1 and Ct
    blocks registered, so it captured neither. Same gate, naming
    F1WireScenario.ClearBufferfiPixels. It now runs last.

junit_tally gains --require-spawn-ran beside --require-split-ran: the prefix IS
the arm, and a shared flag would let one lane tally the other's entries and call
itself run. Verified to discriminate - the spawn junit reads 96/0/5 under its
own flag and 0/0/0 under the split flag, which correctly fails.

Two death tests follow the ADOPT_TIER message the census commit retagged with
Fatal{UnimplementedAdoptTier}; their regexes asserted the old wording.

Unit 2353 (one pre-existing environmental failure), integration-split 186/186,
integration-spawn 102/102, retrace 6/6, fatal census 0 unmarked, G1 0 symbols
and .text unchanged at 0xa52203.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 20:20:24 -04:00
swung0x48andClaude Opus 5 e50463dc5c [MG_Remote, CI] (P6/dl): the Fatal census gate, and the one death under MG_Remote that named nothing
Exit gate S7, and the precondition for CONTRACT-P6 5.2's funnel rather than
its replacement.

S7 says "a bare abort() added outside Session::Fail -> the census gate goes
red". Session::Fail does not exist: it is the 93-site refactor 5.2 describes,
and it is not in this commit. What IS checkable today is the property that
funnel exists to guarantee and that every consumer already depends on - every
death under MG_Remote/ names a FAMILY, in a Fatal{Word} marker a grep can
find. run_trace_case.cmake reds a split retrace on any `Fatal{` line, the
retrace lane's refusal census counts them by name, and MEASUREMENTS quotes
the distinct words. A death with no word is invisible to all three.

TWO RULES, BECAUSE ONE WOULD LAUNDER THE OTHER. An abort must carry a marker
within twelve lines; and every WireLogFatal call must carry one in its format
string. WireLog.cpp's own abort is exempt from the first rule ONLY because its
five callers satisfy the second - a funnel that accepted an unmarked string
would be a hole shaped exactly like the rule.

THE BASELINE BOUNDS SILENCE, NOT DEATHS. Abort sites may grow freely; a new
family word may not appear unrecorded. Freezing the total would make every new
guard a gate change, which is how a gate stops being run. The wire's FatalCode
has seven values and the internal vocabulary is thirty-two, which is the
divergence D2 exists to bound - so growing it has to be an act, not an
accident.

THE CENSUS ALSO CORRECTS ITSELF. Its first run reported WireLog.h's own PROSE
as an unmarked death: the comment explaining why the stderr echo exists
contains the words std::abort(). So the scanner strips comments before
matching, with a character-level pass rather than a regex - a `"http://"`
inside a string literal is not a comment - while KEEPING string literals,
because the markers it looks for live in them. Real numbers after that fix:
93 abort sites, 32 family words, 0 unmarked. a6 had counted 92 and 30 from a
scan that did not make the distinction.

AND THE ONE REAL FINDING. a6 named two aborts with no marker at all;
WireLog.cpp's is the sanctioned funnel, so the genuine one is
PersistentMapTracker's invalid-MOBILEGL_IPC_ADOPT_TIER death. It now carries
Fatal{UnimplementedAdoptTier}, which is what makes the census zero.

R-16 both ways, run: a bare std::abort() reds it naming the file and line, and
a new family word reds it naming the word and how to record it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:42:18 -04:00
swung0x48andClaude Opus 5 743d1facba [MG_Pipe, MG_Backend, MG_Impl] (P6/sm, P6/st): four guards that were compiled in and could never arm, and the crash behind one of them
CONTRACT-P6 3.2 (D1c), 3.3 (D13) and 3.4 (D10).

Every guard below asked a question a SERVER PROCESS answers wrongly - "is a
ClientSession active" (never, there) or "am I on the apply thread" (every
thread is, there) - so all four were present, compiled, and permanently
disarmed in the one shape they exist for. That is worse than absent: it reads
as coverage.

D13 FIRST, THEN THE WIDENING. MGPipeRoleSplitActive() meant "the REHEARSAL
knob is on AND the transport is real", so widening it in place would have left
a narrow name describing a wide predicate. It is renamed to
MGPipeRoleSplitRehearsalActive() across its 12 sites - including the
DualBlockScenario assertion message that embeds it - and the wider predicate
is introduced BESIDE it.

MGPipeBlocksAreDistinct() IS TRUE FOR TWO DIFFERENT REASONS, which is the
whole point: under the rehearsal the two blocks are distinct objects in one
process; under SPAWN they are distinct because they are in different ADDRESS
SPACES, and no knob is involved. The spawn retrace runs with
role-split-state=0 - measured off the lane's own log - so every guard gated on
the rehearsal was off there.

THE CRASH. MGPipeServerBlockNoteIdentity early-returned on the rehearsal, so a
spawn server's gPipeInputs.ContextIdentity() stayed nullptr for the life of the
process. DirectGLES' framebuffer binding-slot memo compares that identity FIRST
and with NO generation, against a cache variable that also starts nullptr - so
nullptr == nullptr reads as a CACHE HIT and the function returns a slot pointer
nothing ever filled. `sm` widens the gate; `st` lands the named Fatal
PipeInputs.h had already asked for, so a reopening says which memo and which
identity instead of corrupting memory three frames later. Guarded on
MOBILEGL_PIPE_PUSH: in a pull build that identity is the live GLContext's
address and is never null, so the test would be dead code and G1 measures that.

DISJUNCTS, NOT SUBSTITUTIONS - and this was measured the hard way. The first
attempt REPLACED OnApplyThread() with MGPipeServerArm() and
ClientSession::Active() with MGPipeSessionLive(). 14 RemoteGuards and
RemoteClientControls cases went green by omission: a ServerLoop fixture with no
client session has only the original facts, so swapping them out disarmed every
test that drives the apply thread directly. The originals stay; the new
predicates are added beside them.

AND THE PROBE HAD TO BE THE RIGHT ONE. Installing
ClientSession::ApplyThreadIsInsideApplier as the apply-thread probe made every
GL-thread call a role violation whenever the applier happened to be busy - the
inproc retrace died on Fatal{RoleViolation, "MGPipeSlots"} raised from the GL
thread. "Am I the apply thread" and "is the apply thread inside the applier"
are different questions; the second is R-1's mutual-exclusion probe and is
about another thread entirely. ServerLoop::OnApplyThread is the one the guards
mean.

Three of D1c's six predicates land here, the three the four guards need. The
other three (MGPipeSplitActive, MGPipeShouldDial, MGPipeBackendIsLocal) have no
D10 site and are not added as dead code; their call sites are ContextEpoch and
ActiveXfbState, which this commit does not touch.

D14 holds: the non-disaggregated build gets constexpr false definitions, not
runtime-false predicates, so every consult folds at compile time. G1
re-measured - 0 symbol diff, .text unchanged at 0xa52203.

Two test names added, both falsifiable by construction: the spawn case asserts
the blocks are distinct with the rehearsal knob OFF, and the monolith case
asserts the predicate is not simply a constant. Unit suite 2353 tests, one
pre-existing environmental failure. All six OpenRA arms green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:38:19 -04:00
swung0x48andClaude Opus 5 570ebde9bc [MG_Remote] (P6/hs): the build stamp that was silently empty, and two asymmetries the handshake never checked
CONTRACT-P6 4.2 and 4.3. Three defects, all of them things the handshake
believed it was checking and was not.

1. THE BUILD STAMP WAS "" AND NOTHING SAID SO. CMakeLists took the git hash
   through an execute_process with NO RESULT_VARIABLE, so a failed
   `git rev-parse` yielded the empty string. Verified live rather than
   inferred: this worktree's `.git` is a file holding a WINDOWS path, WSL's
   git answers `fatal: not a git repository`, result 128 - and every WSL build
   mixed "" into its ABI fingerprint. Two builds from different commits then
   agreed exactly, which is the one thing the stamp exists to prevent. The
   already-failing SessionHandshakeTest was reporting this the whole time.

   The fix may NOT touch GIT_COMMIT_HASH_SHORT: it is baked into
   glGetString(GL_VERSION), so redefining it changes an application-visible GL
   string and the pull build's .rodata - a behaviour leak and a G1 break at
   once. MGGitHash.h.in gains a SECOND pair instead, consumed only by the
   fingerprint, plus -DMOBILEGL_BUILD_STAMP for trees git cannot read (CI has
   ${GITHUB_SHA} in hand). A stampless build is now a configure-time WARNING
   naming the consequence, not silence.

   MOBILEGL_BUILD_STAMP_PRESENT IS MIXED AS ITS OWN FIELD. "this build cannot
   name its commit" and "this build's commit is the empty string" are different
   claims, and collapsing them is how every stampless build in the world agreed
   with every other. The test asserts the flag moves the fingerprint in EITHER
   build state, and the `BuildStamp = ""` perturbation is now guarded - in a
   stampless build production's value already IS "", so that assertion was
   passing while proving nothing.

2. THE CLIENT NEVER READ abiMajor/abiMinor. Hello has carried them since P5
   and the SERVER checks them; the client compared only the fingerprint. The
   fingerprint mixes AbiVersion so a mismatch would fire anyway - but as
   "struct shapes", which sends the reader looking for a layout change that is
   not there. Under spawn the peer is a SEPARATE IMAGE the operator chose with
   MOBILEGL_IPC_SERVER_PATH, so this is exactly the failure that needs its own
   sentence. Both handshake sites call one helper; there are two sites, and
   only one of them was reachable before `sm`, which is how the gap survived.

3. Hello::pid WAS 0 AND Welcome::serverPid ECHOED IT. So both were always 0 and
   neither named anything, while §9.5's arm-proof gate wants exactly the child
   pid. Both now carry real ids, and the pair is the cheapest arm proof in the
   protocol: under spawn they MUST differ, and a same-process session cannot
   produce two different values. The client keeps what the server STATED -
   local launcher knowledge is a different fact from one that crossed the wire,
   and only the second can be asserted from the server's own mouth.

R-16 both ways: revert serverPid to echoing hello->pid() and the new test reds
on both halves, naming 4.3. G1 re-measured after the CMake and header changes:
0 symbol diff, .text unchanged at 0xa52203.

Unit suite goes from two long-standing failures to one - the remaining
PipeCatalogue.FrontendNeverTakesAnApplierAddress is an environmental path
problem in this tree, unrelated. All six OpenRA arms still green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:21:43 -04:00
swung0x48andClaude Opus 5 e766351299 [MG_Remote, MG_Impl] (P6/dl): the device-lost latch, taken from a descriptor and never from a deadline
Before this, CONTRACT-P6 5.3's own sentence held: "a dead server leaves the
client silently DECLINE-ing every verb forever with glGetError clean".
FatalCode::DeviceLost had zero producers and zero consumers and
glGetGraphicsResetStatus returned GL_NO_ERROR unconditionally, so an
application had no way to learn that the process holding its GPU objects was
gone. Measured cost of that: a server killed on its first Clear left the
client waiting out the full 120 s barrier and reporting Fatal{BarrierTimeout}
- the wrong diagnosis, two minutes late. It now notices in 0.01 s.

THE MACHINERY WAS ALREADY THERE. Doorbell::Wait breaks out on Dead(),
SessionProducer::Park turns that into SessionWait::ShutDown, and ClientSession
already had the named DECLINED path. What did not exist was the death FACT:
D5c's finding is that the client parks on clientBell[0] and rings ITSELF
through clientBell[1], holding both ends, so EOF can never arrive on the one
descriptor it watches. A bell that can wake itself cannot hear a death.

SetDeathWitness(fd) fixes that with no new descriptor: the control socket's
far end is held only by the server. The subtlety is that the bell must watch a
socket it must NEVER read - the transport's reassembler owns those bytes and a
control reply is not a death. So the witness enters the poll set with
`events = POLLRDHUP` and nothing else: POLLHUP/POLLERR/POLLNVAL arrive in
revents unrequested, so the hangup is seen while POLLIN never is. Nothing is
recv'd from it and its ownership stays with SocketTransport.

Dead() AND PeerHungUp() ARE TWO FACTS. Park sets m_dead for POLLERR, POLLNVAL
and unrecognised revents too - each a fault in THIS process's descriptor - and
CondVarDoorbell::Kill() sets it on every orderly Stop(). A latch taken from
Dead() would report a lost GPU for a local fd bug and a context reset for
every clean exit, so only PeerHungUp() arms it.

GL_UNKNOWN_CONTEXT_RESET, not GUILTY or INNOCENT: those assign blame, and the
server died for a reason that never crossed the wire.

D5b, in the control-reply wait, which had the right comment and no code: EOF
on the control stream is device loss; a TIMEOUT with the socket still open is
"ALIVE BUT SILENT" and says so by name. 5.4 forbids calling a frozen or merely
slow peer dead, and under P5e run-ahead a server one frame behind is the
INTENDED steady state - a latch armed by a deadline would fire on a healthy
session under load.

MOBILEGL_IPC_RESPAWN is now a NAMED REFUSAL rather than a variable nothing
reads. The latch is one-way on purpose: every handle this client minted names
an object inside the server process, so recovery means re-pushing the world.

THREE TEST NAMES ADDED, none renamed (G14), and R-16 run both ways:
  * remove the witness -> AKilledServerLatchesDeviceLostFromTheHangupAndNot-
    ADeadline goes red, takes 2 s instead of 0.01 s, and names D5c.
  * collapse PeerHungUp() into Dead() -> ADeadBellIsNotAlwaysAHungUpPeer goes
    red naming the local-fd-bug consequence.
  * AnOrderlyStopIsNotADeviceLoss stays GREEN under that collapse, and its
    comment now says so. The first draft claimed it was the control for it;
    running the falsification proved otherwise - under spawn the self bell is a
    SocketDoorbell and Stop() never kills one. The comment was corrected rather
    than the claim quietly kept.

G1 RE-MEASURED, NOT ASSUMED: 0 symbol diff against the c6 baseline and .text
unchanged at 0xa52203. That measurement earned its keep - it caught a 16-byte
drift that had nothing to do with dl: P6's O_APPEND log-sink fix was compiling
into the PULL build, where a second process can never exist. Now guarded, and
.text is back to the baseline exactly.

Full unit suite: 2350 tests, the same two pre-existing environmental failures
and no others. All six OpenRA arms (2 backends x monolith/inproc/spawn) green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 18:49:56 -04:00
swung0x48andClaude Opus 5 15bd9a676c [CI, android-plugin] (P6): CI starts a second MobileGL process on a device
The Android retrace matrix gains a third lane, spawn-acceptance, beside
monolith-control and inproc-acceptance. Until now nothing in CI had ever
started a second MobileGL process on a device at all.

The apk.yml retrace job already carried a `transport` matrix dimension and
already branched on it, so the lane itself is three edits: a row in
github_transport_matrix, an elif in the retrace step, and a summary to render.
What needed thought was the gate.

THE SPAWN LANE IS APK-ONLY, and that is a statement about where evidence is
missing rather than about what spawn can do. Linux already has
test.yml's `retrace-split`, which is {backend, case, transport} over inproc AND
spawn with the two negative controls that make it mean anything. A spawn row in
the Linux transport matrix would pay for a second full sweep proving nothing -
and test.yml's `retrace` job stages no server image, so the lane would not
merely be redundant, it would be red. self_test_transport_matrices now asserts
the absence in both directions, because an accidental removal of the `if apk`
has to be caught in the self-test rather than in CI.

--require-spawn REQUIRES TWO SENTENCES, and the second is the one that matters.
ConfigLoader's marker proves the VALUE RESOLVED - it exists only in the Spawn
arm, which exists only under MOBILEGL_BUILD_DISAGGREGATED - but that is a
statement about a parser. `spawn ARMED - the server role runs in pid N` is
written only after the launch, the connect and the handshake have all
succeeded, and the pid in it is the SERVER's. It is the only line in the log a
same-process run cannot produce.

Both halves red once, measured:
  * a monolith run demanded to prove spawn: REFUSED, transport_resolution_marker
    false, server_pid null - while the retrace itself scored ssim=1.000000,
    which is exactly the trap. OpenRA matches its golden under monolith too, so
    the picture has never been the evidence.
  * the same run's real spawn log with the one ARMED line deleted: REFUSED,
    transport_resolution_marker TRUE and server_pid null. That is the
    "resolved the transport and then never left the process" case, isolated.

THE PROOF USES `any` WHERE THE inproc GATE USES `all`, and the difference is
load-bearing rather than a relaxation. Under spawn two processes append to one
MOBILEGL_LOG_FILE_PATH, and the launcher deliberately scrubs every
MOBILEGL_IPC_* from the child's environment (anti-recursion catch (b)) - so the
server's own `Config: IPC` line reads strict=0 role-split-state=0 BY
CONSTRUCTION. Demanding every line match would red every spawn run for the one
thing the design requires.

--use-pbuffer is not optional on this lane: until P12 a spawned server cannot be
handed a window, because an ANativeWindow* is a pointer into the CLIENT's
process (Rule H). MOBILEGL_IPC_SERVER_PATH is deliberately NOT passed -
nativeLibraryDir carries an install-time hash that nothing off the device can
spell, and the Activity resolves it.

The local runner now passes the same knobs and the same --require-* flag CI
does, so "it works locally" can no longer mean "it ran monolith locally". That
change immediately caught its own omission: the first local run with the gate
armed failed on client_ipc_line_present=false because the runner had been
sending MOBILEGL_TRANSPORT alone.

Verified on device 2f7cbe2e: OpenRA.DirectGLES spawn, ssim=1.000000,
mismatchPixels=0, "real spawn transport, server role in pid 9885, and zero
Fatal records confirmed".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 18:30:18 -04:00
swung0x48andClaude Opus 5 2afa000295 [MG_Remote, android-plugin] (P6): a real phone retraces a real trace across two processes
OpenRA.DirectGLES, transport=spawn, on a Redmi: ssim=1.000000,
mismatchPixels=0, zero Fatal{ lines, three runs for three. The server is a
process the client launched out of the APK's lib/arm64/, and the client's own
log names its pid.

Four things stood between the desktop green and the device green, and every
one of them was invisible on desktop for the same reason: a build tree is not
a deployment, and Linux is not Android.

1. THE SERVER COULD NOT LINK. It links libMobileGL.so and is EXEC'd, not
   dlopen'd, so it gets a fresh linker namespace with the DEFAULT search path
   - and an APK's lib/<abi>/ is not on it. `CANNOT LINK EXECUTABLE ...:
   library "libMobileGL.so" not found: needed by main executable`, before a
   single line of MobileGL ran. On desktop CMake had been giving the target an
   absolute build-tree RPATH, so the WSL server resolved its dependency
   through a path no phone has. $ORIGIN is asked for via BUILD_RPATH (a raw
   -Wl,-rpath,$ORIGIN reaches the generator unquoted and the SHELL eats it -
   the device linker said `normalize_path - invalid input: "$"`), and because
   the NDK drops RPATH from the link anyway, the LAUNCHER states
   LD_LIBRARY_PATH: it is the one component that has already resolved where
   the image lives, and a pair that is not co-located is not a pair.

2. THE RENDEZVOUS NEEDED A WRITABLE DIRECTORY. An Android app has no /tmp, so
   bind() in the child had nowhere to put the node and the client refused by
   name 20 s later. AF_UNIX endpoints now accept the ABSTRACT namespace with a
   leading '@' - the systemd/D-Bus convention - which has no filesystem
   presence at all: no directory, no mode bits, and no stale node to unlink
   after a crash, which is the bind() failure Listen() has been working
   around. Its reach is the network namespace, which for an app is the app.
   StartSpawned mints '@' names; an explicit path still works everywhere, and
   that is what P12's "connect to something somebody else is listening on"
   will use.

3. PBUFFER WAS A DirectGLES-ONLY KNOB. Twice over: trace-replay-ci.sh gated
   `--ez use_pbuffer true` on the backend name, and the JNI demanded a native
   window for DirectVulkan unconditionally. A surface SHAPE is not a backend
   property, and the coupling mattered because the Android GLWS makes a window
   surface whenever gNativeWindow is non-null - so handing Magma a window was
   the same as asking for one. Until P12 a spawned server cannot be given a
   window at all: an ANativeWindow* is a pointer into the CLIENT's process and
   SetWindowHandle is refused on the way across with Fatal{UnmigratedSurface,
   "AndroidNativeWindow@P12"} (Rule H). Which is exactly what happened, one op
   after the server had come up green.

4. THE RUNNER LOOKED IN ONE OF THE TWO OUTPUT DIRECTORIES. assembleTraceRelease
   writes apk/trace/release; CI has staged the same artifact under
   apk/trace/debug. A tree that has built locally has both, and picking the
   wrong one retraces last month's APK and says nothing about it. Newest of
   either, now.

MEASURED AND NOT FIXED: DirectVulkan on this device diverges under BOTH split
transports and does so nondeterministically - inproc scored ssim=0.988998 /
9836 px, spawn scored 0.976494 / 14658 px and then 0.988998 / 9836 px on a
repeat, while monolith with the same pbuffer surface scores 1.000000 / 0 px.
The two transports draw from the same set of outcomes, so this is the split
path on Magma against a real GPU, not the process boundary: P6 neither caused
it nor can fix it. DirectVulkan spawn IS green on desktop (lavapipe, 1.000000).

G14: one test name added, AnAbstractEndpointNeedsNoWritableDirectoryAndLeaves-
NoFile, which pins both halves - the handshake crosses an abstract name, and
nothing is left on the filesystem. A '@' mistaken for a path would have bound
a file of that literal name, passed here, and failed on the one platform this
exists for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 13:33:57 -04:00
swung0x48andClaude Opus 5 f6a0bd3024 [MG_Remote] (P6/dl): D5c - a bell that can wake itself cannot hear a death
Measured while running the 78-entry spawn matrix, not predicted.

minecraft-1.21.4-fabric-iris-iterationrp-in-world kills the SERVER process
outright on this machine - llvmpipe cannot lower the shader pack's
%llvm.x86.vcvtps2ph.256 and aborts at call 159429 - and the client did NOT
take the SessionWait::ShutDown path, which already exists and is already
correct. It sat out the full 120 s and reported Fatal{BarrierTimeout,
"ResourceRespecify"}: the wrong diagnosis, at two minutes a case, for a
server that had been gone since the first second. The same trace fails in 3 s
under monolith.

The cause is structural and is the price of `sm`'s two-fd bell. The client
parks on clientBell[0] and rings ITSELF through clientBell[1], so it holds
both ends of that socketpair. EOF arrives only when every writer closes and
the client is one of them, so that descriptor can never hang up no matter
what happens to the peer.

`dl` therefore needs a witness descriptor whose far end only the server
holds, polled beside the park fd and never read from, whose POLLHUP/EOF
latches Dead(). The control socket already is exactly that, so no new
descriptor is needed.

This is NOT a defect in `sm`: holding both ends is what self-notification
requires, and without it the server's control pump could not wake its own
apply thread - the bug that cost this branch an afternoon. The mistake would
be assuming one descriptor can answer both questions.

Recorded rather than fixed: it turns no red case green, and the only case
that reaches it fails identically in all three arms for a reason that is not
MobileGL's. `dl` owns the fix and S2 already names the red-once for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:42:03 -04:00
swung0x48andClaude Opus 5 1039502ee6 [MG_Remote, android-plugin] (P6): the device can run the split retrace, and only the app can spell the server's path
Two small pieces, so an Android spawn arm is a flag rather than a project.

THE RUNNER GAINS --transport. It already had a generic env passthrough - one
intent extra carries `K=V;K=V` all the way to setenv before the library is
dlopened - so the transport itself costs one entry and no new plumbing in the
five files between here and the device. monolith passes NOTHING rather than
MOBILEGL_TRANSPORT=monolith, so the default arm's environment stays
byte-identical to what it was before this option existed: a control that
changed when the option landed would not be one.

THE SERVER PATH CANNOT COME FROM THE HOST. Every other knob can, but this one
names a file that must be EXEC-ABLE, and on Android there is exactly one such
place: an APK's lib/<abi>/. W^X has forbidden the app's own data dirs since
API 29, and the packager only puts a file in lib/<abi>/ if it is named
lib*.so - which is why the server executable wears that name, and what P0
spike A proved on two devices. nativeLibraryDir contains an install-time
hash, so no host-side script can spell the path; the process about to launch
the server is the only one that can. TraceReplayActivity resolves it, and
only when the caller actually asked for spawn.

AN EXPLICIT MOBILEGL_IPC_SERVER_PATH STILL WINS. A caller that set one is
pointing somewhere deliberately - at a pushed build, say - and silently
replacing it would make that knob untestable on the one platform where it
matters most.

The APK must be built with -Pmobilegl.buildDisaggregated=ON or none of this
is reachable: without it ConfigLoader has no transport parser, accepts the
value, ignores it (CONTRACT-P5 rule 5), and the run is monolith under a name
that says spawn. The --transport help says so where somebody will read it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:34:34 -04:00
swung0x48andClaude Opus 5 94e2f2e0d8 [MG_Remote, CI] (P6): the split retrace lane becomes the whole CI matrix, both backends, both transports
It was one case on one backend under one transport: OpenRA, DirectGLES,
inproc. It is now every CI case, both backends, inproc AND spawn - 154 CI
entries, 156 local ctest entries - because every defect the spawn work turned
up was a question about the SERVER's process and not about any one trace or
either backend.

THE DirectVulkan ARM. tools/trace_replay/CMakeLists.txt carried "a
DirectVulkan arm would be measuring a server nobody has written yet". True
when P5 wrote it; false since P5f/P7 landed Magma's server consumers and its
run-ahead readiness gate. Leaving it would have shipped a split shape whose
second backend nothing ever ran - the same class of hole as a lane that runs
monolith under a name that says split. Magma now brings up a server process
of its own and OpenRA retraces across it at ssim=1.000000, which is only
possible because this branch also taught the child to load its config: before
that, a DirectVulkan session brought up a DirectGLES server and the two
halves disagreed about which backend the capability mask describes.

`split` BECOMES AN OPT-OUT. It began as an opt-in naming one case, because
one case was the work. Marking 39 cases `"split": true` would carry no
information and would reinstate the hole the key was written to close, only
mirrored: a case added later would get the monolith arms and be silently
absent from the split ones, and absent is the one state nothing reds on. A CI
case is now in the subset unless it says `"split": false`, which is a
reviewable claim that a trace cannot cross a role boundary.

THE CI MATRIX GAINS A THIRD DIMENSION. The job took {backend, case} and
hard-coded MOBILEGL_TRANSPORT=inproc in its own run block, so `spawn` had no
way into CI at all; the .SPAWN ctest entries existed only for a local build.
It is {backend, case, transport} now, the backends are the case's own
ci_backends rather than a hard-coded DirectGLES, and the artifact names carry
the transport or the two arms of one {backend, case} would overwrite each
other's uploads.

inproc STAYS AS THE CONTROL. Same library, same codec, same applier, same
picture; the only difference is which process the server role runs in.
Running only spawn would leave "did the transport break it?" and "did the
phase break it?" answerable only together - which is the question every
failure in this phase has turned on, including the SIGSEGV that D1 explained.

BOTH NEGATIVE CONTROLS FOLLOW THE ARM. retrace_pull_library_control.sh and
retrace_drop_draw_control.sh each exported MOBILEGL_TRANSPORT=inproc
themselves, so on a spawn job they would have gone on proving something about
the other arm while spawn ran unguarded. They read SPLIT_TRANSPORT now, and
default to inproc so a caller that sets nothing behaves exactly as before.
scripts/ci/control_smoke_test.sh: 22 passed, 0 failed against the stubbed
ctest, including the two modes that matter most - a red whose SSIM never fell
and a knob that armed and dropped nothing.

The spawn arm needs a second binary and the inproc arm needs none, so the job
places libMobileGLServer.so only on the spawn arm and a missing one is a
named failure there rather than a LaunchServer refusal 78 jobs deep.

Measured locally as this lands: 39 of the 78 SPAWN entries complete, all
green. The rest are still running.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:31:49 -04:00
swung0x48andClaude Opus 5 ea9fc7fa71 [MG_Remote] (P6/cp): a real trace retraces across two processes, pixel-for-pixel
OpenRA.DirectGLES.SPAWN is green: ssim=1.000000, mismatchPixels=0, zero
Fatal{ lines, against a server in a process the client started by name. The
inproc SPLIT arm stays beside it as the control, so "did the transport break
it" and "did the phase break it" remain separately answerable.

Five defects stood between the handshake and that picture. Each one was
silent in its own way, and none of them looked like what it was.

1. THE DOORBELL COULD NOT WAKE ITSELF. SocketDoorbell's one-fd form sends on
   the end it polls, so a write is delivered to the PEER - correct for waking
   the other process, useless for waking a thread in this one. The server's
   control pump posts into the apply thread's mailbox and must ring the bell
   that thread parks on. Symptom: every eglInitialize crossed, landed in the
   mailbox, and timed out at 5 s. The two-fd form (park on [0], notify on [1])
   is restored here, and the bell handover goes from two descriptors to THREE
   - the client needs the same split for the same reason. Seven offers now.

2. InitCapabilities HAD NO WIRE KIND. CONTRACT-P6 §2 predicted this exactly
   ("the request has a live client caller and the codec refuses to encode
   it"). SurfaceOpKind gains 11, append-only; the decode range's upper bound
   moves with it, or the new tag reads as out-of-range and surfaces as
   Fatal{ProtocolCorruption} rather than the missing row it is. The op's name
   loses its InprocOnly suffix, which stopped being true here.

3. THE CHILD LOADED NO CONFIG AT ALL. mobilegl_server_main calls
   InitServerRoleForSpawn directly, and MG_ConfigLoader::Init is a step of
   MobileGL::Initialize - so every MG_Config value in the server was its
   static default. MOBILEGL_BACKEND_TYPE survives the launcher's scrub on
   purpose and was read by nobody: a DirectVulkan session would have brought
   up a DirectGLES server and then disagreed with its client about which
   backend the capability mask describes.

4. AND THEREFORE Transport READ AS Monolith, which CONTRACT-P6 §3.1 (D1)
   forbids in as many words. a6 measured the cost: 226 live lines test
   `Transport != Monolith` to select the SERVER arm, 148 in MG_Backend.
   Monolith flips all of them to frontend glue in the one process with no
   frontend. Observed precisely as predicted - UnitTexturesByHandle() answered
   false, Clear took the legacy arm that dereferences borrowed FRONTEND slot
   pointers, and the apply thread took a SIGSEGV inside SyncNeccessaryTextures
   on the first Clear record of the trace. It is pinned in-process rather than
   through the environment because the environment is where it must NOT be:
   LooksLikeAClientEnvironment exits 65 on a surviving MOBILEGL_TRANSPORT, and
   that check is anti-recursion catch (b). Dial, not Transport, is that axis.

5. THE LOG WAS CORRUPT, NOT MERELY INTERLEAVED. Two processes opened the same
   MOBILEGL_LOG_FILE_PATH with "w" and each carried its OWN file offset, so
   they overwrote each other's bytes - half-lines like `ote client: CapsMirror
   generation 1 adopted`, and the server's whole startup block vanishing under
   the client's later writes. This cost real diagnosis time twice, because a
   missing line read as a code path not taken. O_APPEND now; the client still
   truncates once so a fresh run is not a pile of old ones, and the server
   never does - it would delete the very startup lines a failed session needs.
   run_trace_case.cmake's Fatal{ census reads exactly this file, so it was
   also reading a lie.

The retrace runner's split assertions become transport-aware: one row per
transport it admits, and a transport with no row is a FATAL rather than a
fall-through, because the fall-through is the accident the block exists to
prevent. The spawn row carries a SECOND sentence and it is the stronger half
- ConfigLoader's marker proves the value RESOLVED, while `spawn ARMED - the
server role runs in pid N` is written only after the launch, the connect and
the handshake all succeeded, and carries a pid that is not this process's.
inproc resolves its own marker while running the server role on a thread
here; nothing on that path can write this one.

G14: one test name added (TheEleventhFramedOpIsInitCapabilitiesAndItCrosses-
TheWire), none removed. The ten-op table keeps its name and its scope rather
than being renamed to eleven.

Two unit failures predate this change and are environmental in this tree:
PipeCatalogue.FrontendNeverTakesAnApplierAddress (the frontend source root
resolves empty) and SessionHandshakeTest.TheAbiFingerprintChangesWhenAnyOf-
ItsInputsDoes (GIT_COMMIT_HASH_SHORT is empty here, which a6 already recorded
as red in this configuration).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 12:23:41 -04:00
swung0x48andClaude Opus 5 b0f4f8b744 [MG_Remote] (P6/cp): EGL control frames cross to the other process, and answer
An eglInitialize issued in one process is dispatched in another and its answer
comes back. That is the last thing standing between the session and a native
context, because the server creates its context on the apply thread when the
client's first eglMakeCurrent crosses - and until now nothing crossed.

ONE SEAM, NOT TWELVE. a6 row A4-13 counted twelve Server* forwarders, each
ending in ServerLoopInstance().RunSurfaceControlFrame(frame) with no role
branch, and concluded twelve edits. They all funnel through that one function,
so the branch goes there and the forwarders are untouched.

A HOOK, NOT A CALL. ServerLoop::SetRemoteControlSink takes a function pointer
the client installs at handshake. The obvious alternative - the server half
asking ClientSession::Active() - would have added a fifth symbol to the six
MG_Remote already owes itself (a6-link-experiment §5), in the one file with a
clean reason not to.

The branch is BEFORE the local seq mint, deliberately. RunSurfaceControlFrame
numbers unnumbered local posts; a wire request must keep the CLIENT's number all
the way through dispatch and reply or its answer cannot be correlated
(CONTRACT-P6 §6.3, which says the client mints, always).

The client sink encodes with EncodeSurfaceOpFrame, sends, and waits for the
SurfaceReply carrying its own seq - under one mutex, because the twelve
forwarders are already caller-serialised on the server's m_callerMutex under
inproc and two replies racing for one correlation is the same bug on either
side. A CapsSnapshot arriving while it waits is ADOPTED rather than dropped:
the server republishes caps from inside its MakeCurrent dispatch (a6 row A4-30)
so a snapshot legitimately precedes the reply to the op that produced it. The
wait is bounded and its expiry is NOT fatal - a peer that is gone is a different
fact from a peer that is slow, and only the doorbell's death latch may say which.

The server's pump decodes and applies through ServerApplyWireSurfaceOp, which
a6 found had no production caller anywhere. It runs on ServerMain's own thread -
NOT the apply thread - which is what §6.2 asks for: a control arrival must not
wake the applier, and frame decode must not happen on the thread holding the
native context. A frame that is not a verifiable SurfaceOp ends the session
rather than being ignored, because a silent drop is the failure mode this
project refuses everywhere else.

THE TEST'S ASSERTION IS THE OUT-PARAMETERS, not the EGL result. A headless
machine has no display to initialise, so the op is expected to be refused - and
ServerInitializeEGLDisplay writes major/minor "whenever the dispatch ran,
success or not" (the forwarder's own comment). They move off -1 if and only if
a SurfaceReply came back from the other process; a transport failure returns
before the write-back. I got this backwards first and the test said so.

Gates: ServerSpawnTest 5/5; unit suite 2345 with the same two pre-existing
environmental failures; G1 pull 0 added / 0 removed, .text 10822147 unchanged.

Not TCP. It was considered and dropped for now: TCP has no SCM_RIGHTS, so the
four segments cannot cross it, and a TCP control plane would have to refuse a
data plane by name until StreamLink exists (P6.5). Recorded here so the reason
is on file rather than re-derived.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:50:28 -04:00
swung0x48andClaude Opus 5 207c31f6db [MG_Remote] (P6/sm): two INDEPENDENT processes, joined by a name, sharing memory
The cross-process session is up. A server process is started on its own with an
endpoint and nothing else, it listens; a client started separately connects to
that name; Hello crosses, Welcome comes back with four SegmentRefs, six
descriptors cross by SCM_RIGHTS, and the client maps memory another process
created. ClientSession::Active() is non-null at the end of it, which is the flag
that arms the thirty-seven wire emitters.

INDEPENDENT, NOT FORKED - and that is a correction to this package's first
shape. The version committed an hour ago forked the server and handed it fds
3..6. It worked, and it was less code, but inheritance can only ever produce a
server that is a CHILD OF ITS CLIENT, which is the one arrangement the end state
cannot use: there the server is a standing application and the client is
somewhere else entirely, possibly on another kernel. CONTRACT-P6 §3.1 called
this Dial == Connect and filed it as a later shape. It is the primary one, and
fork/execve survives only as a way to START a process - every descriptor it used
to carry is gone.

What that costs and buys, concretely: the rendezvous becomes a NAME, so
SocketTransport grows Listen/AcceptPair/ConnectTo, with a bounded connect retry
that is the CLIENT's (a launcher that waited for the server to be ready would be
coupling the two again by the back door). The bells stop being inherited fds and
are created by the server and handed over with the segments - slots 4 and 5 of
six SCM_RIGHTS offers. And the client connects TWICE to the same path: an fd
offer is a sendmsg whose ancillary data rides with specific bytes, so it may not
share a socket with the framed control stream, or the frame reassembler and the
descriptor receiver race for the same bytes.

The pieces behind it:
  - SessionSegments::AdoptFromDescriptors, which is the same Adopt+Map loop
    AttachInProcess has run on every inproc session since P5. That was the point
    of writing the inproc attach as dup+Adopt+Map rather than as an alias: only
    the origin of the descriptor is new.
  - ServerSession::SetExternalDoorbells, the narrow fix for a6 row A7-1 - the
    §3.9 accessors abort for every role but InProcess, so a spawn apply thread
    died before popping its first record. lk deletes them; until then an injected
    pair is honest about where the bells come from.
  - MG_Backend::InitServerRoleForSpawn: steps 1 and 2 of the split bring-up
    extracted so the server process runs the SAME code the inproc server role
    runs. The capability bits are a statement about the server's own backend and
    a second copy would diverge the first time a backend registers a slot.
  - ClientSession::FinishStartup: everything below the attach - producer, reply
    pool, event ring, segment table, encoder, first CapsSnapshot, emitter tables -
    shared verbatim between inproc and spawn. Its one parameter is not a
    transport question: under inproc the client starts the apply thread because
    there is no server-side main; under spawn there is one, and it started the
    thread before it sent the first descriptor.

G1 CAUGHT A REAL LEAK on the way: InitServerRoleForSpawn was guarded on the
inside, so the pull build still DEFINED the symbol - 2 added, 1 removed, .text
+16 bytes. The whole function and its declaration are now inside the guard.
"It returns false there" is not the same as "it is not there", and the gate is
what said so.

Gates: ServerSpawnTest 4/4; unit suite 2344 with the same two pre-existing
environmental failures; G1 pull 0 added / 0 removed, .text 10822147 unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:36:14 -04:00
swung0x48andClaude Opus 5 e156ea5f7a [MG_Remote] (P6/sm): two MobileGL processes, talking
The first time this project has had a second process. fork + execve of a real
server image, the control socket surviving the exec, bytes crossing a process
boundary, and the child exiting on EOF with nothing left behind.

mobilegl_server_main EXISTS NOW. a6 found ARCHITECTURE.md:488-496 had described
it for three phases while the symbol was nowhere in the tree, and the only
MobileGLServer target was the P0 spike stub, which links no MobileGL library at
all. The spike keeps its evidence and its name becomes MobileGLServerSpike; the
real image links the library, so an undefined symbol is a build error rather
than a dlsym failure in a child whose stderr is /dev/null.

WHAT sm OWNS AND WHAT IT LEAVES: the process, the inherited descriptors, the
transport and the exit discipline. Not the session, not the applier, not the
four segments - wiring those from ServerMain before lk has a seam to wire them
THROUGH is how call sites get written twice. The loop is a read/answer/exit-on-
EOF stand-in whose SHAPE is the part that matters: one reader, EOF ends the
process, and no timeout is ever allowed to stand in for the death fact (§5.4).

ANTI-RECURSION IS TWO CATCHES, and neither is ARCHITECTURE.md:488's. That rule
says the child hard-sets Transport to Monolith; a6 measured that 226 live lines
test `Transport != Monolith` to select the SERVER arm, 148 in MG_Backend, so
obeying it flips the whole backend to frontend glue in the one process with no
frontend. Instead: (a) MOBILEGL_IPC_DIAL=no, structural and separate from role,
and (b) MOBILEGL_TRANSPORT and every MOBILEGL_IPC_* scrubbed from the child's
envp. The child refuses with 64 for (a) and 65 for (b) so the two safeties are
distinguishable - two that cannot be told apart are one.

TWO BUGS WORTH RECORDING, both found by the test rather than by review:

dup2(n, n) IS A NO-OP THAT DOES NOT CLEAR CLOSE-ON-EXEC. FdPassing sets
SOCK_CLOEXEC on the aux pair, so the child depends on dup2 to clear it - but in
a gtest process a fresh socketpair lands on exactly fds 3..8, so a source fd
often IS its own target. The no-op left CLOEXEC set and the following close()
then shut the descriptor we had just "installed". The child came up with no
socket and the parent saw TRANSPORT_CLOSED on its first send. Now spelled out
rather than written cleverly.

THE CHILD'S DIAGNOSTICS WERE INVISIBLE. WireLogError reaches the file sink
only - Defines.h builds the logger with the console sink off - so a child that
refused to start said so into a file the parent does not know the path of.
ARCHITECTURE.md §15.2 warns about exactly this on Android. Both refusal paths
now also write stderr directly, and both carry a distinct exit code the parent
can name without reading anything.

TESTS: six cases, 6/6. Each exists because something would otherwise pass
silently - the reply carries the child's own getpid() so a test that talked to
itself cannot pass (ID-124's lesson at the smallest scale); the process tree is
COUNTED before, during and after, not promised; the child is proven not to exit
while merely idle before it is proven to exit on EOF; an unresolvable image is a
named refusal that spawns nothing (S1); a surviving client knob is caught by
name (S3); and a descriptor crosses execve by SCM_RIGHTS, which is the mechanism
the four segments will ride on and is now exercised before it is needed.

Also records the asio decision in the contract: declined for P6 because spawn
needs five platform mechanisms and asio covers one - its own socketpair returns
operation_not_supported on Windows, it has no descriptor passing, segment
delivery is POSIX-only by design, and there is no fork. Revisit at P6.5, where
asio::generic::stream_protocol carries a raw family/type/protocol triple and
therefore gives AF_VSOCK from one implementation.

Gates: unit suite 2346, up 6, same two pre-existing environmental failures. G1
pull 0 added / 0 removed, .text size 10822147 unchanged, and zero spawn, server
or SocketTransport symbols in the pull build.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:04:31 -04:00
swung0x48andClaude Opus 5 a351836154 [MG_Remote] (P6/so): SocketTransport, green over a real socketpair before any second process
The first P6 code that runs. ITransport over a connected AF_UNIX SOCK_STREAM
socket, with SCM_RIGHTS descriptor passing on a dedicated SOCK_DGRAM aux pair.
No shared memory: this is the CONTROL plane, and the hot path bypasses
ITransport entirely by its own header's account. What the socket carries is the
handshake, surface ops, resync, aux requests and fatals - and, once sm exists,
the four segment descriptors that let the peer map the data plane. It moves the
keys, not the bytes.

CONTRACT-P6 §8 and the spawn plan both require this green over a plain
socketpair with two threads BEFORE a child is ever forked, for the reason
SessionRings.h gives about the attach half: a transport first exercised on the
day the process appears is a transport whose bugs all arrive at once, on the
hardest day to debug them. That requirement is now met.

It reinvents nothing. Framing.h already had AppendFrame and a real byte-stream
reassembler with exactly the BUFFER_TOO_SMALL keep-the-message semantics
ITransport specifies - written for this and never before driven by a socket.
FdPassing.h already had SCM_RIGHTS over a dedicated datagram pair. What is new
is ~250 lines joining them, plus the platform refusal: Windows has no
SCM_RIGHTS and ShmSegment::Adopt is POSIX-only, so CreatePair refuses BY NAME
at construction rather than handing back a transport that fails every later
call.

SOCK_STREAM rather than SOCK_SEQPACKET, deliberately: Doorbell.h:390-398
already chose a stream socket so a closed peer surfaces as POLLIN|POLLHUP with
recv()==0 rather than as a hang, and the control plane may not disagree with
the bell about what death looks like. Framing.h is what makes a stream safe -
the message boundary is in the payload, not in the socket.

TESTS: the same nine ITransport-contract cases InProcessTransportTest runs,
copied rather than shared. Folding both suites into one parameterised fixture
would rename the sixteen existing cases and G14 says names only grow; and the
two suites do not share a handle anyway, since InProcessTransport's tests reach
into condvar doorbells this class does not have. Nine names added, zero
removed. The seven Doorbell* cases are deliberately absent: they exercise
CondVarDoorbell, not ITransport.

Plus three a stream has and a message queue cannot: a 256 KiB payload that
provably crosses in several reads; a garbage stream that must latch failed and
must NOT resync onto a boundary it invented; and adopting an already-connected
fd with no aux channel, which answers UNSUPPORTED to ShareFd rather than
pretending - rule G, a transport declares what it supports.

Red-once, both run: drop the message on BUFFER_TOO_SMALL and six cases go red;
make the framing latch recoverable and AGarbageStreamIsLatchedFailed fails by
name.

Gates: 12/12 in 677 ms. Unit suite 2340 tests, up 12, with the same two
pre-existing environmental failures. G1 pull 0 added / 0 removed, .text size
10822147 unchanged, and zero SocketTransport symbols in the pull build.

One note for the VM track this eventually serves: swapping AF_UNIX for
AF_VSOCK is one line here and nothing at all in Framing. It is the shared-memory
half that does not cross a kernel.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 09:47:32 -04:00
swung0x48andClaude Opus 5 f4cbaa8945 [MG_Remote] (P6/lk): regroup RingControl by writer, and make the asserts that pin it falsifiable
The shared control page both roles map had a mixed-writer cache line:
{appliedSeq, submittedSeq, retiredSeq, completedFrameSerial, presentAckSerial}
sat together, but submittedSeq is producer-written (Ring.h's "THE FIVE
WATERMARKS") while the other four are consumer-written. That is why no
single-writer progress block could be aliased over it, and it is what this
package fixes: submittedSeq moves up beside cmdHead, the other thing the
producer writes, and the four that remain become a named LinkProgress member -
the struct c6 declared in ILink.h - so a data plane with no shared page can own
the same four values and every wait predicate in SessionRings.h keeps ONE
implementation at source level.

The two event flags deliberately stay in the doorbell group. Promoting them
would put the client's per-drain exchange(0) on eventRingFull (EventRing.h:200)
onto the line the client's own spin predicate reads 1e5-1e6 times a frame.

73 call sites rewritten, 15 in the library and 58 in tests. The rewrite is
receiver-scoped rather than field-scoped, because SplitRuntimePeek.h:77 has its
own struct with a field of the same name and SplitRuntimePeek.cpp:146 has both
on one line - a field-scoped rename would have silently broken the peek struct
that MagmaRunAheadScenario reads nine times.

THE ASSERTS ARE THE PART THAT NEEDED A SECOND PASS. The first revision shipped
four aggregate asserts and an adversarial review broke them by counterexample:
swapping retiredSeq and completedFrameSerial inside LinkProgress compiled
clean, passed all four, and passed the runtime layout test too - because
appliedSeq stays at offset 0. Three wire-visible offsets on a shared page were
pinned by nothing. Nothing else in the tree covers it either: the ABI
fingerprint takes no input from this page, and sizeof(RingControl) is 4096
whatever the members do, because alignas(4096) makes it so.

So the block is now per-field as CONTRACT-P6 §8.3 actually asked, plus a
standard-layout precondition, a tail bound that alignas cannot satisfy for us,
and the LinkEventFlags mirror. Each was run red: the field swap reds the
per-field asserts by name, a fifth member inside LinkProgress reds sizeof.

One of them cannot go red, and Ring.h now says so rather than implying
otherwise. A SMALL member inserted between Progress and serverEpoch lands at
offset 288, inside Progress's own line, and serverEpoch's alignas(64) absorbs
up to 32 bytes of it - so both line asserts still pass. The review's proposed
fix does not catch it either; I tried it. A gate nobody can falsify is worse
than no gate, so the limit is written down beside the asserts.

Also: RingTest.ControlPageLayoutIsTheSharedContract said nothing about the one
field this package moved, and now asserts the producer/consumer separation and
the event flags' exclusion itself rather than borrowing the claim from Ring.h.
Ring.h grew 30 lines, so the Ring.h:NN citations this package and c6 authored
are re-anchored to named blocks instead of line numbers. ARCHITECTURE.md §11.2
is updated for the new layout, and a factual error introduced in the previous
revision of that paragraph - submittedSeq annotated as releasing staging, which
retiredSeq does - is corrected.

Gates: pull 0 added / 0 removed, .text size 10822147 unchanged; split 0/0,
.text size 11681395 unchanged; unit suite 2326/2328 with the same two
pre-existing environmental failures as the baseline. The five edits behind
MGITEST_SPLIT_RUNTIME_PEEK were proven compiled by a red-once, not assumed.

Note on the .text claim: that is a SIZE, not the bytes - field offsets moved,
so immediates moved with them. And this page's layout IS observable across
binaries; what is unobservable is behaviour within one binary. The contract
already books the layout change deliberately, before spawn exists to care.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 09:23:48 -04:00
swung0x48andClaude Opus 5 a54ae47ab9 [MG_Remote] (P6/lk): the pre-flight itemisation, and a correction to c6's regroup design
CONTRACT-P6 §8.5 requires lk to publish its blast radius before it starts,
because an earlier draft's ratchet baseline was wrong by a factor of three and
a ratchet installed on the wrong number is red on its first CI run for reasons
that have nothing to do with a leak. The itemisation is mechanical, per file,
with the grep spelling stated: 250 seam-identifier references outside
Transport/ across 23 files (127 production, 123 test), and 44 member-access
sites that the regroup itself must rewrite, across 9 files - 17 of them in
MG_IntegrationTest, which is why lk builds with the integration tests ON.
The earlier build did not, and a missed edit there would have been green.

THE CORRECTION. Measuring that radius turned up a mistake in c6, landed two
commits ago. §8.3 and ILink.h both said lk should promote eventRingFull and
eventDropped into the watermark group and called the result single-writer.
eventRingFull has TWO writers: the server latches it with store(1) when
SEG_EVENT fills (EventRing.h:140) and the CLIENT clears it with an exchange(0)
on EVERY DRAIN (:200). Promoting it would put a per-drain read-modify-write by
the client on the same cache line as appliedSeq - which the server
release-stores every 64 records and the client's spin predicate reads 1e5-1e6
times a frame. That is new false sharing on the hottest line in the system,
and it would land in exactly the numbers this package's gate has to hold
constant. It is also the same class of error the earlier draft made with
submittedSeq, one field over.

So LinkProgress is now the four consumer-written watermarks and nothing else -
genuinely single-writer - and the two flags stay in the doorbell/generation
group, where mixed writers already live beside consumerParked/producerParked,
crossing the seam through a separate EventFlags() accessor on its own line.
The contract records the correction and its reasoning rather than quietly
restating the rule.

ALSO CORRECTED, from running the baseline suite: a6's link-experiment report
said the silently-empty build stamp had "no log and no gate to say so". That
is false. SessionHandshakeTest.cpp:140 asserts BuildStamp[0] != '\0' and :180
asserts that perturbing it changes the fingerprint, and BOTH GO RED in this
configuration right now - the worktree's .git holds a Windows path WSL's git
cannot resolve, so GIT_COMMIT_HASH_SHORT is "". The finding is therefore
stronger, not weaker: the gate that catches it already exists and is already
red. What is silent is the BUILD, and hs owes a named configure-time failure
rather than a new gate.

Baseline for lk, recorded: 3878 tests, two failures, both environmental and
understood - the fingerprint one above, and PipeCatalogue.FrontendNeverTakes-
AnApplierAddress, which walks up from cwd looking for MobileGL/MG_Impl and so
fails for any out-of-source build directory.

No behaviour change. The headers are still included by nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 08:54:48 -04:00
swung0x48andClaude Opus 5 0bbe41c291 [MG_Remote] (P6/c6): the normative contract, and the data-plane seam declared but not wired
c6 is P6's contract package. It lands CONTRACT-P6.md plus two headers and
changes nothing: no caller moves, no byte moves on any wire.

THE CONTRACT supersedes P6-CONTRACT-DRAFT.md, which was written before its own
audit and is wrong in four places - the ABI row, "the latch is implemented
unchanged", "cp is transport only", and "a transport swap and nothing else".
a6 measured all four. It carries 21 rulings, of which the load-bearing one is
D1: the spawned child keeps Transport == Spawn and anti-recursion becomes a
separate Dial axis. ARCHITECTURE.md:488's literal instruction is amended,
because 226 live lines test `Transport != Monolith` to select the SERVER arm
and forcing Monolith flips 148 MG_Backend lines to frontend glue in the one
process that has no frontend.

That ruling can be stated normatively without changing behaviour because of
something a6 found and the contract exploits: TransportMode::Spawn is
UNREACHABLE at this head. ConfigLoader.cpp:344 is the only writer for the
string "spawn" and it writes Monolith. So every rule conditioned on
Transport == Spawn constrains a state no process can enter - and the same fact
is why ConfigLoader's named refusal cannot currently falsify itself, which is
sm's to fix and §9.5's arm-proof gate to catch.

THE SEAM. ITransport says in its own header that the hot path bypasses it;
below it there was no interface of any kind, because Ring.h, ReplySlot.h and
EventRing.h each take a raw void* plus a capacity. ILink.h is that missing
thing. It is setup-time, not hot-path: no method is called per record or inside
a spin predicate, because Doorbell::Wait's predicate runs 1e5-1e6 times a frame
reading watermarks straight off the page, and because the only lane that could
measure a virtual there has four times the dispersion of the effect - a gate
that can only print "within noise" is ID-124 one level down.

StreamLink.h is declared and implemented by nobody, and that is its job: ILink's
adequacy is a claim only a compile can settle. Writing it forced three methods
the brief did not name - ResolveSpan, FlushProgress, and the reply pair - so it
has already earned its keep. Delete one ILink method it declares and the build
goes red.

Deliberately NOT here, each for a reason the contract records: Watermark::Reached
is not redefined (SessionRings.h owns it); Ring.cpp's reserve/pop bodies are not
relocated into a header that would then need the logger; RingControl is not
regrouped, because that rename is 109 production sites with five behind a
non-Android #if, so it is lk's with a published itemisation; and the schema rows
are specified but left to hs, because deprecating SurfaceReply.defaultFb while
appending `result` changes CreateSurfaceReply's arity and the existing
six-argument call would silently bind its defaultFb 0 to result.

INERTNESS IS STRUCTURAL, not measured. Zero object dependency files reference
either header, zero build rules do, and nothing in the tree includes them.
Verified anyway on both flavours: pull and split each have 0 symbols added,
0 removed, and .text byte-identical (10822147 / 11681395). check_doc_citations
resolves all 61 citations.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 08:35:50 -04:00
swung0x48andClaude Opus 5 785fed0b00 [Docs] (Disaggregated): P6 a6 close-out, and the end-state review it was re-scoped from
a6 is the read-only audit P6-SPAWN-PLAN puts first. Seven static items, each
produced by one auditor and re-resolved line by line by one adversarial
verifier; 198 rows, 65 of them contested, and only the surviving ones carry
into the report. Item 5 - can the server link without MG_Impl - is the one
experiment, and it is answered.

The headline is that P6's transport half is smaller than the plan assumed
(fc and fs really did land) and its process/role half is much larger. Four
statements in P6-SPAWN-PLAN / P6-CONTRACT-DRAFT are false at this head:

  - `spawn` is not an observable state at all. ConfigLoader.cpp:339-346
    recognises it and then writes Transport = Monolith, so "the child was
    forced to monolith" and "the parent fell back" are the same value and
    that named refusal cannot falsify itself. Meanwhile 226 live lines test
    `Transport != Monolith` to select the SERVER arm, 148 of them in
    MG_Backend - so ARCHITECTURE.md:488's rule, implemented literally, flips
    the whole backend to frontend glue in the one process with no frontend.
  - `cp` is not transport-only: the InitCapabilities REQUEST has no wire form,
    and the codec refuses to encode the kind a live client still calls.
  - the device-lost latch is not implemented; it was booked as carriage.
  - the server cannot link without MG_Impl: 184 symbols, 177 of them real
    function calls, owed 101 to P7 / 14 to P3b-P4b / 60 shared / 6 to P6.
    There is also no module target to link, so the question could not have
    been answered by editing a link line.

Four more blockers the earlier review missed: the apply thread aborts in
ConsumerDoorbell before popping its first record (contract 3.9's ruling, which
lk should retire rather than amend); neither side of the control plane is
wired to a socket; the control-reply wait has no deadline, so a frozen peer
wedges the GL thread inside eglMakeCurrent; and SurfaceReply cannot carry a
MobileGLResult, so a client cannot tell a dead server from a legitimate
refusal.

The abort census makes dl's funnel a redesign rather than a rename: 92 sites,
30 distinct family words against a 7-value wire enum, and three unbounded
peer-driven allocations with no try/catch anywhere under MG_Remote.

P6-ENDSTATE-REVIEW.md is the re-examination of P6 against the gfxstream-shaped
end state that produced a6's three added items. a6 overturned four of its own
claims - the MG_State eight's shape, the abort count, m_windowHandle's
injection points and a predicate name collision - and those are corrected in
place rather than left to be rediscovered.

Docs only. No code, no gate, no behaviour.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 07:49:37 -04:00
136 changed files with 14346 additions and 1106 deletions
+38
View File
@@ -469,6 +469,23 @@ jobs:
--env "MOBILEGL_TRANSPORT=inproc;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1"
--require-inproc
)
elif [ "${MOBILEGL_CI_TRANSPORT}" = "spawn" ]; then
# THE SAME CLIENT KNOBS AS inproc, so the two acceptance lanes differ in exactly one
# thing: which PROCESS the server role runs in. They are scrubbed out of the CHILD's
# environment by the launcher and read by the client, which is where they belong.
#
# MOBILEGL_IPC_SERVER_PATH IS DELIBERATELY ABSENT. nativeLibraryDir carries an
# install-time hash, so nothing off the device can spell it; TraceReplayActivity
# resolves it from getApplicationInfo() when the env asks for spawn, and an explicit
# value would override that. --use-pbuffer is NOT optional here: until P12 a spawned
# server cannot be handed a window at all, because an ANativeWindow* is a pointer
# into the CLIENT's process and SetWindowHandle is refused on the way across with
# Fatal{UnmigratedSurface, "AndroidNativeWindow@P12"} (Rule H).
extra_retrace_args+=(
--env "MOBILEGL_TRANSPORT=spawn;MOBILEGL_IPC_ROLE_SPLIT_STATE=1;MOBILEGL_IPC_STRICT_ERRORS=1;MOBILEGL_IPC_RUN_AHEAD=1"
--use-pbuffer
--require-spawn
)
else
extra_retrace_args+=(--env "MOBILEGL_TRANSPORT=monolith")
fi
@@ -633,6 +650,13 @@ jobs:
pattern: MobileGL-android-retrace-result-inproc-acceptance-inproc-*
path: retrace-artifacts/inproc-acceptance
- name: Download Android spawn acceptance results
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
uses: actions/download-artifact@v8
with:
pattern: MobileGL-android-retrace-result-spawn-acceptance-spawn-*
path: retrace-artifacts/spawn-acceptance
- name: Render monolith control summary
run: |
node tools/trace_replay/render_retrace_summary.mjs \
@@ -652,6 +676,11 @@ jobs:
--group-label "Android Emulator / inproc acceptance" \
--html mobilegl-android-inproc-acceptance.html
- name: Render spawn acceptance summary
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
run: |
node tools/trace_replay/render_retrace_summary.mjs --input retrace-artifacts/spawn-acceptance --output-dir android-retrace-summary/spawn-acceptance --title "MobileGL Android spawn acceptance" --group-label "Android Emulator / spawn acceptance" --html mobilegl-android-spawn-acceptance.html
- name: Upload Android monolith control summary
uses: actions/upload-artifact@v7
with:
@@ -669,6 +698,15 @@ jobs:
archive: false
if-no-files-found: error
- name: Upload Android spawn acceptance summary
if: env.MOBILEGL_CI_DISAGGREGATED == 'ON'
uses: actions/upload-artifact@v7
with:
name: MobileGL-android-spawn-acceptance-summary-${{ github.sha }}
path: android-retrace-summary/spawn-acceptance/mobilegl-android-spawn-acceptance.html
archive: false
if-no-files-found: error
remove-artifact-clutter:
name: remove artifact clutter
runs-on: ubuntu-latest
+88 -20
View File
@@ -1076,6 +1076,13 @@ jobs:
# ProtocolSmoke and FdPassing - are registered only under MOBILEGL_BUILD_DISAGGREGATED
# (MG_Test/CMakeLists.txt), and before this job existed NO cmake invocation anywhere in this
# workflow passed that option. They had never been compiled by CI, let alone run.
# Exit gate 9.2. BEFORE the lanes run, because it costs a `ctest -N` and answers the one
# question a green lane cannot: did the spawn arm cover the same cases the split arm did?
# A spawn lane registered with fewer cases goes green while proving less, and nothing about
# a smaller green lane looks wrong.
- name: integration-spawn covers integration-split (9.2)
run: python3 scripts/ci/spawn_lane_parity.py build-split
- name: Unit tests on the split runtime
working-directory: build-split
env:
@@ -1099,6 +1106,11 @@ jobs:
sudo sysctl -w kernel.core_pattern='/tmp/core.%e.%p'
ctest --output-on-failure -L integration-split --no-tests=error -j 4 --output-junit "${RUNNER_TEMP}/split-baseline.xml"
python3 ../scripts/ci/junit_tally.py "${RUNNER_TEMP}/split-baseline.xml" --require-split-ran
# Exit gate 9.3: the spawn arm green at the same count. It runs the same cases through a
# SECOND PROCESS, so a failure here that the line above did not see is a transport fact
# and not a phase one - which is the whole reason both lanes exist.
ctest --output-on-failure -L integration-spawn --no-tests=error -j 4 --output-junit "${RUNNER_TEMP}/spawn-baseline.xml"
python3 ../scripts/ci/junit_tally.py "${RUNNER_TEMP}/spawn-baseline.xml" --require-spawn-ran
# Both full transport runs are hard gates. The per-case comparison below
# remains diagnostic because explicit mechanism controls retain their own mode.
@@ -1157,9 +1169,12 @@ jobs:
- name: The split lane really resolved the transport
working-directory: build-split
run: |
log=MobileGL/MG_IntegrationTest/persistent-map-arm-split-DirectGLES.log
# P6: the sink writes one file per ROLE from the base MOBILEGL_LOG_FILE_PATH; the
# transport-resolution line is ConfigLoader's, on the CLIENT thread, so it is in the
# .client half. The base name itself names no file now.
log=MobileGL/MG_IntegrationTest/persistent-map-arm-split-DirectGLES.client.log
if [ ! -f "${log}" ]; then
echo "::error::${log} does not exist: the DirectGLES.Split.PersistentMapArm. entry never ran, so nothing in this job establishes that MOBILEGL_TRANSPORT ever resolved to inproc in a live process"
echo "::error::${log} does not exist: the DirectGLES.Split.PersistentMapArm. entry never ran (or the per-role split renamed it), so nothing in this job establishes that MOBILEGL_TRANSPORT ever resolved to inproc in a live process"
exit 1
fi
# THE DISTINCTIVE PART OF THE INFO LINE, not the bare KEY=VALUE (review finding M-5):
@@ -1984,6 +1999,14 @@ jobs:
- name: Checkout repo
uses: actions/checkout@v6
# `dl` / exit gate S7. CHEAP AND EARLY, on a job that only reads the tree: it needs no
# build, so a death that names no family is reported in seconds rather than after the
# matrix. What it refuses is a std::abort() under MG_Remote/ with no Fatal{Family} marker,
# and a family word that appeared without being recorded - the vocabulary drifts on
# purpose or not at all (CONTRACT-P6 5.2's D2 ruling).
- name: Fatal census (S7)
run: python3 scripts/ci/fatal_census.py
- name: Load trace cases
id: trace-cases
run: |
@@ -1995,17 +2018,19 @@ jobs:
# The subset the verify build retraces ("verify": true in trace_cases.json). It is a
# SUBSET of the matrix above, so retrace-verify needs no fixtures of its own.
echo "verify-matrix=$(python3 tools/trace_replay/trace_cases.py --ci --format github-verify-matrix)" >> "$GITHUB_OUTPUT"
# P5's split subset ("split": true, DirectGLES only). Also a SUBSET of the matrix above,
# so retrace-split needs no fixtures of its own either. It is one case today - OpenRA,
# which is what the phase gate names - and trace_cases.py refuses a `split` case that is
# not in CI or does not run DirectGLES, so the subset cannot silently become empty.
# The split subset: {backend, case, transport} over inproc AND spawn, both backends, for
# every CI case that has not said `"split": false`. Still a SUBSET of the matrix above,
# so retrace-split needs no fixtures of its own. P5 shipped it as one case (OpenRA, which
# the phase gate names); P6 widened it to the whole CI matrix, because every bug the
# spawn work found was a question about the SERVER's process rather than about one trace.
# trace_cases.py refuses a `split` case that is not in CI, so the subset stays a subset.
SPLIT_MATRIX=$(python3 tools/trace_replay/trace_cases.py --ci --format github-split-matrix)
# AND IT MUST NOT BE EMPTY. An empty `include` is not an error to GitHub - it skips the
# whole retrace-split job with no red anywhere - so the one way this subset can vanish
# silently is guarded here. trace_cases.py now also rejects an unknown manifest key, which
# was the hole: `"splitt": true` loaded clean and emptied the subset (review N-4).
if [ "$(printf '%s' "${SPLIT_MATRIX}" | python3 -c 'import json,sys; print(len(json.load(sys.stdin)["include"]))')" -lt 1 ]; then
echo "::error::the split retrace subset is EMPTY. No case in trace_cases.json carries \"split\": true, so retrace-split would be skipped with no red. Exit gate E2 names OpenRA."
echo "::error::the split retrace subset is EMPTY. `split` is an OPT-OUT as of P6 - a CI case is in this subset unless it carries \"split\": false - so an empty subset means either every case opted out or the CI matrix itself is empty. Either way retrace-split would be skipped with no red, and exit gate E2 names OpenRA."
exit 1
fi
echo "split-matrix=${SPLIT_MATRIX}" >> "$GITHUB_OUTPUT"
@@ -2415,10 +2440,15 @@ jobs:
build-retrace/tools/trace_replay/${{ matrix.case }}/${{ matrix.backend }}/output/**
if-no-files-found: warn
# P5's retrace arm: retrace-verify with MOBILEGL_PIPE_VERIFY=1 swapped for
# MOBILEGL_TRANSPORT=inproc and the comparator's symbol swapped for an MG_Remote one. Exit gate
# E2 is one row - OpenRA at SSIM >= 0.99 - and trace_cases.json's `split: true` is where that
# subset lives.
# The retrace arm of the split shape: retrace-verify with MOBILEGL_PIPE_VERIFY=1 swapped for
# MOBILEGL_TRANSPORT and the comparator's symbol swapped for an MG_Remote one. Exit gate E2 is
# one row - OpenRA at SSIM >= 0.99 - but the lane is no longer one row: as of P6 it is
# {backend, case, transport} over the whole CI matrix, both backends, inproc AND spawn.
#
# inproc IS THE CONTROL AND SPAWN IS THE CLAIM. Same library, same codec, same applier, same
# picture; the only difference is which PROCESS the server role runs in. Running only spawn
# would leave "did the transport break it?" and "did the phase break it?" answerable only
# together, which is the question every failure in this phase turned out to hinge on.
#
# IT RUNS THE UNCHANGED CTEST NAMES with the transport exported in the JOB environment, rather
# than the SPLIT-suffixed variant entries. build-retrace configures without
@@ -2434,7 +2464,7 @@ jobs:
# SSIM is neither of them: the nm check below (this library carries MG_Remote) and the
# transport-resolution line in the library's own log (this PROCESS resolved inproc).
retrace-split:
name: retrace split (${{ matrix.backend }}, ${{ matrix.case }})
name: retrace split (${{ matrix.backend }} / ${{ matrix.transport }}, ${{ matrix.case }})
runs-on: ubuntu-latest
timeout-minutes: 240
needs:
@@ -2522,7 +2552,24 @@ jobs:
fi
echo "the library at build-linux/libMobileGL.so is the split build"
- name: Retrace and validate under MOBILEGL_TRANSPORT=inproc
# THE SPAWN ARM NEEDS A SECOND BINARY and the inproc arm needs none, which is the whole
# difference between the two at this level: inproc's server role is a thread in the replay
# process, spawn's is a PROCESS the client launches from this image. It is packaged by
# build-linux-split's `find -name '*.so'` sweep - libMobileGLServer.so is an executable that
# wears a .so name so an APK will install it somewhere exec-able - and a missing one must be
# a NAMED failure here rather than a LaunchServer refusal 78 jobs deep.
- name: Place the server image (spawn arm only)
if: ${{ matrix.transport == 'spawn' }}
run: |
if [ ! -f build-split/libMobileGLServer.so ]; then
echo "::error::the split runtime carries no libMobileGLServer.so, so transport=spawn has no server to launch. ConfigLoader would resolve Spawn, LaunchServer would refuse BY NAME, and this job would red on a message about an unresolvable image rather than about a packaging gap."
exit 1
fi
cp build-split/libMobileGLServer.so build-linux/libMobileGLServer.so
chmod +x build-linux/libMobileGLServer.so
echo "server image: $(readlink -f build-linux/libMobileGLServer.so)"
- name: Retrace and validate under MOBILEGL_TRANSPORT=${{ matrix.transport }}
working-directory: build-retrace/tools/trace_replay
# run_trace_case.cmake turns MOBILEGL_TRANSPORT into assertions of its own - the library
# must have RESOLVED the transport in this process, and its log must carry no Fatal{ - so a
@@ -2532,7 +2579,11 @@ jobs:
run: |
ulimit -c unlimited
sudo sysctl -w kernel.core_pattern='/tmp/core.%e.%p'
export MOBILEGL_TRANSPORT=inproc
export MOBILEGL_TRANSPORT='${{ matrix.transport }}'
# Absolute, because the replay's working directory is not this one and LaunchServer
# resolves the image relative to nothing. Harmless on the inproc arm, which reads it
# only to decide it does not need it.
export MOBILEGL_IPC_SERVER_PATH="${GITHUB_WORKSPACE}/build-linux/libMobileGLServer.so"
ctest -V --no-tests=error --timeout 10800 \
-R '^MobileGLTraceReplay\.${{ matrix.case }}\.${{ matrix.backend }}$'
@@ -2572,6 +2623,10 @@ jobs:
CONTROL_TMPDIR: ${{ runner.temp }}
PULL_LIBRARY: ${{ github.workspace }}/pull-runtime/build-monolith-control/libMobileGL.so
FROZEN_LIBRARY: ${{ github.workspace }}/build-linux/libMobileGL.so
# The control has to run the arm it is a control FOR. Hard-coded inproc, it would go on
# proving something about the other arm while spawn ran unguarded.
SPLIT_TRANSPORT: ${{ matrix.transport }}
MOBILEGL_IPC_SERVER_PATH: ${{ github.workspace }}/build-linux/libMobileGLServer.so
run: >-
bash "${GITHUB_WORKSPACE}/scripts/ci/retrace_pull_library_control.sh"
'${{ matrix.case }}' '${{ matrix.backend }}'
@@ -2597,8 +2652,12 @@ jobs:
working-directory: build-retrace/tools/trace_replay
env:
CONTROL_TMPDIR: ${{ runner.temp }}
LIBRARY_LOG: ${{ matrix.case }}/${{ matrix.backend }}/output/mobilegl.log
LIBRARY_LOG: ${{ matrix.case }}/${{ matrix.backend }}/output/mobilegl.client.log
FROZEN_LIBRARY: ${{ github.workspace }}/build-linux/libMobileGL.so
# The control has to run the arm it is a control FOR. Hard-coded inproc, it would go on
# proving something about the other arm while spawn ran unguarded.
SPLIT_TRANSPORT: ${{ matrix.transport }}
MOBILEGL_IPC_SERVER_PATH: ${{ github.workspace }}/build-linux/libMobileGLServer.so
run: >-
bash "${GITHUB_WORKSPACE}/scripts/ci/retrace_drop_draw_control.sh"
'${{ matrix.case }}' '${{ matrix.backend }}'
@@ -2611,20 +2670,29 @@ jobs:
if: always()
working-directory: build-retrace/tools/trace_replay
run: |
log="${{ matrix.case }}/${{ matrix.backend }}/output/mobilegl.log"
# BOTH ROLES, because under spawn every applier refusal is raised in the SERVER's
# process and a census reading only the client's file reports a confident zero for the
# half it cannot see.
log="${{ matrix.case }}/${{ matrix.backend }}/output/mobilegl.client.log"
server_log="${{ matrix.case }}/${{ matrix.backend }}/output/mobilegl.server.log"
if [ ! -f "${log}" ]; then
echo "no ${log} - the replay wrote no library log"
exit 0
fi
echo "Fatal{ lines: $(grep -c 'Fatal{' "${log}" || true)"
grep -o 'Fatal{[A-Za-z]*, "[^"]*"' "${log}" | sort | uniq -c | sort -rn | head -20 || true
census_files="${log}"
if [ -f "${server_log}" ]; then census_files="${census_files} ${server_log}"; fi
echo "census over: ${census_files}"
echo "Fatal{ lines: $(cat ${census_files} | grep -c 'Fatal{' || true)"
cat ${census_files} | grep -o 'Fatal{[A-Za-z]*, "[^"]*"' | sort | uniq -c | sort -rn | head -20 || true
# The transport line is the CLIENT's: ConfigLoader resolves it there, and under spawn
# the server states its own separately.
grep -m1 "MOBILEGL_TRANSPORT=" "${log}" || echo "no transport line in ${log}"
- name: Upload core dumps
if: failure()
uses: actions/upload-artifact@v7
with:
name: retrace-split-core-dumps-${{ matrix.backend }}-${{ matrix.case }}
name: retrace-split-core-dumps-${{ matrix.transport }}-${{ matrix.backend }}-${{ matrix.case }}
path: /tmp/core.*
if-no-files-found: ignore
@@ -2632,7 +2700,7 @@ jobs:
if: always()
uses: actions/upload-artifact@v7
with:
name: retrace-split-result-${{ matrix.backend }}-${{ matrix.case }}
name: retrace-split-result-${{ matrix.transport }}-${{ matrix.backend }}-${{ matrix.case }}
path: |
build-retrace/tools/trace_replay/${{ matrix.case }}/actual-images/**
build-retrace/tools/trace_replay/${{ matrix.case }}/${{ matrix.backend }}/output/**
+127 -6
View File
@@ -185,15 +185,61 @@ if (MSVC)
endif()
# Generate MGGitHash.h
#
# RESULT_VARIABLE, WHICH THIS CALL DID NOT HAVE (CONTRACT-P6 4.2). Without it a failed
# `git rev-parse` yields "" and nothing says so. Verified live: building this worktree from WSL
# produces an EMPTY hash, because the worktree's `.git` is a file holding a WINDOWS path that
# WSL's git cannot resolve - so two builds from different commits got IDENTICAL ABI
# fingerprints and the stamp silently stopped doing its documented job.
execute_process(
COMMAND git rev-parse HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_HASH_FULL
OUTPUT_STRIP_TRAILING_WHITESPACE
RESULT_VARIABLE MOBILEGL_GIT_STAMP_RESULT
ERROR_QUIET
)
string(SUBSTRING "${GIT_COMMIT_HASH_FULL}" 0 7 GIT_COMMIT_HASH_SHORT)
# --- the BUILD STAMP, and why it is a second pair rather than a fix to the first -------------
#
# GIT_COMMIT_HASH_SHORT MAY NOT MOVE. It is baked into glGetString(GL_VERSION)
# (MG_Impl/GLImpl/Getter/GL_Getter.cpp), so redefining it changes an APPLICATION-VISIBLE GL
# string and the pull build's .rodata - a behaviour leak and a G1 break at once. The handshake
# gets its own pair instead, consumed only by the ABI fingerprint, which no pull build compiles.
#
# PRESENT IS A FIRST-CLASS INPUT, not the emptiness of VALUE. "this build has no stamp" and
# "this build's stamp is the empty string" are different claims, and a fingerprint that could
# not tell them apart is how two unrelated builds agreed in the first place.
#
# -DMOBILEGL_BUILD_STAMP=<anything> (or the environment variable) overrides, because a tree git
# cannot read is not always a tree whose commit is unknown - CI has ${GITHUB_SHA} in hand.
set(MOBILEGL_BUILD_STAMP "" CACHE STRING "Explicit ABI-fingerprint build stamp when git cannot be read")
set(MOBILEGL_BUILD_STAMP_VALUE "")
if(NOT "${MOBILEGL_BUILD_STAMP}" STREQUAL "")
set(MOBILEGL_BUILD_STAMP_VALUE "${MOBILEGL_BUILD_STAMP}")
elseif(NOT "$ENV{MOBILEGL_BUILD_STAMP}" STREQUAL "")
set(MOBILEGL_BUILD_STAMP_VALUE "$ENV{MOBILEGL_BUILD_STAMP}")
elseif(MOBILEGL_GIT_STAMP_RESULT EQUAL 0 AND NOT "${GIT_COMMIT_HASH_FULL}" STREQUAL "")
set(MOBILEGL_BUILD_STAMP_VALUE "${GIT_COMMIT_HASH_FULL}")
endif()
if("${MOBILEGL_BUILD_STAMP_VALUE}" STREQUAL "")
set(MOBILEGL_BUILD_STAMP_PRESENT 0)
# A WARNING AND NOT A FATAL: a build with no stamp is still a usable build, it just cannot
# prove that a peer was built from the same tree. Saying so once at configure time is the
# difference between a known limitation and the silent one 4.2 found.
message(WARNING
"MobileGL: no build stamp. `git rev-parse HEAD` failed (result "
"'${MOBILEGL_GIT_STAMP_RESULT}') and MOBILEGL_BUILD_STAMP was not set, so the ABI "
"fingerprint cannot distinguish two builds of the same sizes from different commits - "
"which is exactly what a stale MOBILEGL_IPC_SERVER_PATH looks like. Pass "
"-DMOBILEGL_BUILD_STAMP=<commit> to restore it.")
else()
set(MOBILEGL_BUILD_STAMP_PRESENT 1)
endif()
configure_file(
${CMAKE_SOURCE_DIR}/MobileGL/MG_Util/Miscellany/MGGitHash.h.in
${CMAKE_BINARY_DIR}/generated/MGGitHash.h
@@ -556,6 +602,7 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
MobileGL/MG_Remote/Transport/ShmSegmentWin32.cpp
MobileGL/MG_Remote/Transport/FdPassing.cpp
MobileGL/MG_Remote/Transport/InProcessTransport.cpp
MobileGL/MG_Remote/Transport/SocketTransport.cpp
# Keeps MG_Util/Debug/Log.h - and through it the GL frontend's
# umbrella header - out of the header-only wire code (WireLog.h).
MobileGL/MG_Remote/Transport/WireLog.cpp
@@ -574,6 +621,9 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
# emitter that returns quietly is how a split lane runs monolith and
# goes green (ARCHITECTURE.md 10.3).
MobileGL/MG_Remote/CapsCodec.cpp
# P6 dl: the one place a session dies - Session::Fail's funnel (Fatal-family aware,
# publishes SessionFault, one telemetry point).
MobileGL/MG_Remote/FatalFunnel.cpp
MobileGL/MG_Remote/Wire/PipeWireCodec.cpp
MobileGL/MG_Remote/Client/ClientSession.cpp
MobileGL/MG_Remote/Client/EmitTables.cpp
@@ -595,6 +645,8 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
MobileGL/MG_Remote/Server/ServerSession.cpp
MobileGL/MG_Remote/Server/PipeApplier.cpp
MobileGL/MG_Remote/Server/ServerLoop.cpp
MobileGL/MG_Remote/Server/ServerMain.cpp
MobileGL/MG_Remote/Server/ServerSpawn.cpp
# P5f fc: the value frame that replaced the control mailbox's function-pointer payload,
# and its codec against protocol.fbs's SurfaceOp/SurfaceReply (the spawn arm's seam).
MobileGL/MG_Remote/Server/SurfaceControlFrame.cpp
@@ -923,20 +975,89 @@ endif()
# Off by default and ANDROID-only, so no shipping configuration builds it. The
# trace flavour of the plugin APK turns it on (android-plugin/build.gradle).
# ---------------------------------------------------------------------------
if (ANDROID AND MOBILEGL_BUILD_SERVER_SPIKE)
# ---------------------------------------------------------------------------
# P6 `sm`: the REAL server image. Unlike MOBILEGL_BUILD_SERVER_SPIKE below - the
# P0 spike, which links no MobileGL library and exists only to prove the Android
# delivery chain - this one links the library and runs mobilegl_server_main.
#
# ARCHITECTURE.md:496 called for a ~30-line stub that dlopen's libMobileGL.so and
# dlsym's the entry point, so one shared library serves both roles. On a desktop
# configure we link it directly instead: there is no APK packaging rule to satisfy
# and a direct link is what makes an undefined symbol a BUILD error rather than a
# runtime dlsym failure in a child whose stderr is /dev/null.
#
# Android keeps the lib*.so naming and the nativeLibraryDir output the spike
# proved is the only exec-able location in an APK.
if (MOBILEGL_BUILD_DISAGGREGATED AND NOT WIN32)
add_executable(MobileGLServer
${CMAKE_CURRENT_SOURCE_DIR}/MobileGL/MG_Remote/Server/ServerEntry.cpp)
target_include_directories(MobileGLServer PRIVATE
${MOBILEGL_INCLUDE_DIR})
target_link_libraries(MobileGLServer PRIVATE ${CMAKE_PROJECT_NAME})
set_target_properties(MobileGLServer PROPERTIES
POSITION_INDEPENDENT_CODE ON)
target_compile_options(MobileGLServer PRIVATE -fPIE)
target_link_options(MobileGLServer PRIVATE -pie)
# $ORIGIN, OR THE SERVER CANNOT START AT ALL ON ANDROID.
#
# This executable links libMobileGL.so, and it is EXEC'd rather than dlopen'd - so it gets a
# fresh linker namespace with the default search path, not the app's. An APK's lib/<abi>/ is
# not on that path, and the failure is the bluntest one there is:
#
# F linker: CANNOT LINK EXECUTABLE ".../lib/arm64/libMobileGLServer.so":
# library "libMobileGL.so" not found: needed by main executable
#
# It cost a device run to find because it is invisible on desktop: CMake gives build-tree
# targets an absolute RPATH automatically, so the WSL server resolved its dependency through a
# path that does not exist on a phone. $ORIGIN says "beside me", which is true in the APK, true
# in the build tree, and true wherever somebody copies the pair - and it is what makes a
# deployment that is NOT a build tree work at all, which the end state is.
# THE PROPERTIES, NOT target_link_options. A raw `-Wl,-rpath,$ORIGIN` reaches the generator
# unquoted and the SHELL expands $ORIGIN to nothing - measured on device, where the linker
# said `normalize_path - invalid input: "$"` and then failed to find libMobileGL.so anyway.
# BUILD_RPATH / INSTALL_RPATH are the supported spelling and CMake escapes them correctly.
set_target_properties(MobileGLServer PROPERTIES
BUILD_RPATH "$ORIGIN"
INSTALL_RPATH "$ORIGIN"
BUILD_WITH_INSTALL_RPATH TRUE)
if (ANDROID)
# An APK's only exec-able install location is lib/<abi>/, and the packager
# only puts a file there if it is named lib*.so. P0 spike A proved this
# works from the app's own untrusted_app domain on two devices.
set_target_properties(MobileGLServer PROPERTIES
PREFIX "lib" SUFFIX ".so" OUTPUT_NAME "MobileGLServer")
if (CMAKE_LIBRARY_OUTPUT_DIRECTORY)
set_target_properties(MobileGLServer PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
endif()
else()
# Desktop: the name the dladdr fallback looks for beside libMobileGL.so.
set_target_properties(MobileGLServer PROPERTIES
PREFIX "lib" SUFFIX ".so" OUTPUT_NAME "MobileGLServer"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
endif()
endif()
if (ANDROID AND MOBILEGL_BUILD_SERVER_SPIKE)
# Renamed by P6 sm: the real server took the name it had been holding.
add_executable(MobileGLServerSpike
${CMAKE_CURRENT_SOURCE_DIR}/tools/spikes/server_stub/main.cpp)
# An executable that is named like a shared library still has to be a real
# PIE executable: Android has refused non-PIE executables since API 21, and
# the name alone does not change what the loader demands of the file.
set_target_properties(MobileGLServer PROPERTIES
set_target_properties(MobileGLServerSpike PROPERTIES
PREFIX "lib"
SUFFIX ".so"
OUTPUT_NAME "MobileGLServer"
OUTPUT_NAME "MobileGLServerSpike"
POSITION_INDEPENDENT_CODE ON)
target_compile_options(MobileGLServer PRIVATE -fPIE)
target_link_options(MobileGLServer PRIVATE -pie)
target_compile_options(MobileGLServerSpike PRIVATE -fPIE)
target_link_options(MobileGLServerSpike PRIVATE -pie)
# AGP packages what the external native build drops into the per-ABI output
# directory, and it selects by the .so extension. CMake puts executables in
@@ -944,7 +1065,7 @@ if (ANDROID AND MOBILEGL_BUILD_SERVER_SPIKE)
# CMAKE_LIBRARY_OUTPUT_DIRECTORY, so point this target's runtime output at
# the library directory when the generator gave us one.
if (CMAKE_LIBRARY_OUTPUT_DIRECTORY)
set_target_properties(MobileGLServer PROPERTIES
set_target_properties(MobileGLServerSpike PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
endif()
endif()
+50 -4
View File
@@ -336,10 +336,32 @@ namespace MobileGL::MG_ConfigLoader {
}
// The three P6 forms. Recognised precisely, so the diagnostic can say "not yet"
// rather than "unknown", which are different bugs on the operator's side.
if (lowered == "spawn" || lowered.compare(0, 5, "unix:") == 0 ||
lowered.compare(0, 5, "pipe:") == 0) {
MGLOG_E("Config: MOBILEGL_TRANSPORT='%s' names a transport P6 implements and P5 does "
"not; staying on monolith. This run is NOT a split run.",
// P6 `sm`/`cp`: spawn is IMPLEMENTED. It launches a server process on a
// rendezvous of its own and connects to it - the two processes are
// independent, so this is `Dial = Connect` with a launcher attached
// rather than the fork-coupled shape ARCHITECTURE.md:488 described.
if (lowered == "spawn") {
MG_Config::Transport = MG_Config::TransportMode::Spawn;
// THE SAME SHAPE AS THE inproc LINE ABOVE, AND FOR THE SAME REASON.
// run_trace_case.cmake asserts on a distinctive sentence from this
// function rather than on `MOBILEGL_TRANSPORT=spawn` alone, because
// ConfigLoader logs an `Accepted env variable: KEY=VALUE` line for
// every MOBILEGL_* in EVERY build including the pull one - so the
// bare KEY=VALUE is satisfied by a monolith library that parsed
// nothing (review M-5). A spawn arm with no line of its own could
// only have been asserted with the inproc marker, which spawn never
// emits: the arm would have been red for a missing sentence rather
// than green for a working transport.
MGLOG_I("Config: MOBILEGL_TRANSPORT=spawn - the MGPipe record stream crosses a real "
"ring to an apply thread in ANOTHER PROCESS");
return;
}
if (lowered.compare(0, 5, "unix:") == 0 || lowered.compare(0, 5, "pipe:") == 0) {
// unix: and pipe: remain P6+ - connecting to an endpoint SOMEBODY
// ELSE is listening on needs the server lifecycle to be somebody
// else's too, which is P12's. Named, never a silent degrade.
MGLOG_E("Config: MOBILEGL_TRANSPORT='%s' names a transport P6 does not implement yet; "
"staying on monolith. This run is NOT a split run.",
value.c_str());
MG_Config::Transport = MG_Config::TransportMode::Monolith;
return;
@@ -405,6 +427,30 @@ namespace MobileGL::MG_ConfigLoader {
ipc.RoleSplitState = false;
}
// P6 `dl` (CONTRACT-P6 5.3): MOBILEGL_IPC_RESPAWN IS A NAMED REFUSAL, NOT A NO-OP.
//
// The device-lost latch is deliberately one-way - a session whose server died has
// nothing to recover into, because every handle the client minted names an object in a
// process that no longer exists. Re-pushing the world onto a fresh server is the work
// this knob would turn on, and no stage has written it.
//
// Refused BY NAME rather than parsed and ignored, for the reason Config.h gives about
// the whole IPC family: an environment variable nothing consumes is indistinguishable
// from one that is consumed and does nothing, and an operator who set this one would
// otherwise conclude that recovery had been tried and had not helped.
{
String respawn;
QueryEnvVariable("MOBILEGL_IPC_RESPAWN", respawn, "");
if (!respawn.empty() && respawn != "0") {
MGLOG_E("Config: MOBILEGL_IPC_RESPAWN='%s' names a recovery NO STAGE HAS "
"IMPLEMENTED. The device-lost latch is one-way on purpose: every handle "
"this client minted names an object inside the server process, so a new "
"server would have to be re-pushed the entire world before a single verb "
"could land. This run will latch device-lost and stay there.",
respawn.c_str());
}
}
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
// One line, on the arm where these numbers decide behaviour, because every one of
// them is a number a bug report has to quote.
@@ -199,6 +199,34 @@ namespace MobileGL::MG_Backend::DirectGLES {
#endif
#if !MOBILEGL_PIPE_PUSH || MOBILEGL_PIPE_LEGACY_MEMOS
const void* ctx = MGB_CTX_IDENTITY;
#if MOBILEGL_PIPE_PUSH
// `st` (CONTRACT-P6 3.4): THE NAMED FATAL PipeInputs.h ALREADY ASKED FOR.
//
// This memo compares the identity FIRST and with NO GENERATION, and its cache variable
// starts at nullptr - so an identity that is ALSO nullptr reads as a CACHE HIT and the
// function returns `*g_fbSlotCache[target]`, a pointer nothing ever filled. The crash
// that follows names neither the memo nor the identity.
//
// It is reachable exactly when a process runs this legacy arm with an unset identity,
// which is what a spawn server used to be: MGPipeServerBlockNoteIdentity early-returned
// on the REHEARSAL knob, so the server's block carried nullptr for the life of the
// process. `sm` widened that gate to MGPipeBlocksAreDistinct() and closed the hole; this
// says so out loud if it ever reopens, because a silent wrong answer here is
// indistinguishable from memory corruption three frames later.
//
// Under MOBILEGL_PIPE_PUSH only: in a pull build MGB_CTX_IDENTITY is the live
// GLContext's address, which is non-null on every path that reaches here, so the test
// would be dead code and G1 measures dead code.
if (ctx == nullptr) {
MGLOG_F("MGPipe: Fatal{UnnamedIdentity, \"FbSlotMemo\"} - the framebuffer binding-slot "
"memo was consulted with a NULL context identity. Its cache starts null too, "
"so this would have read as a hit and returned a slot pointer that was never "
"filled. The identity is set by MGPipeServerBlockNoteIdentity, which arms on "
"MGPipeBlocksAreDistinct(); a null here means this process runs the legacy "
"memo arm with a block nobody claimed (CONTRACT-P6 3.4).");
std::abort();
}
#endif
if (ctx != g_fbSlotCacheContext) {
auto& live = *MGB_CTX;
for (SizeT i = 0; i < g_fbSlotCache.size(); ++i) {
+67 -1
View File
@@ -30,6 +30,8 @@
#include <MG_Remote/Client/BackendObject_Remote.h>
#endif
#include "ServerRole.h"
namespace MobileGL::MG_Backend {
void LogBackendInfo() {
if (!pActiveBackendObject) {
@@ -148,7 +150,13 @@ namespace MobileGL::MG_Backend {
// The single hook (ARCHITECTURE.md:29). Returns false when the split could not be
// brought up, and the caller then REFUSES TO CONTINUE rather than falling back to the
// switch below - a fallback here is "the split lane ran monolith and went green".
Bool InitSplitRoles() {
// Steps 1 and 2 of the split bring-up: the server role's private backend
// object and the two CallMask halves. EXTRACTED so the spawn server
// process runs the SAME code the inproc server role runs - a second copy
// is how the two roles end up disagreeing about a capability bit that
// only one of them ever computes. ServerMain calls this and then does
// its own Accept; InitSplitRoles calls it and then starts the client.
Bool InitServerRoleCommon() {
using namespace MobileGL::MG_Remote;
// 1. the SERVER role's private backend object, on the app thread, with no GL and no
@@ -210,6 +218,37 @@ namespace MobileGL::MG_Backend {
capBits |= MG_Pipe::MGPipeRunAheadCapBitsFor(MG_Config::ActiveBackendType, runAheadReady);
session.SetCapabilityBits(capBits);
session.SetBackend(loop.Backend());
return true;
}
// The single hook (ARCHITECTURE.md:29) for the INPROC shape: both roles in
// this process. The spawn shape runs InitServerRoleCommon in the child and
// the client half here.
Bool InitSplitRoles() {
using namespace MobileGL::MG_Remote;
// SPAWN: THE SERVER ROLE IS NOT IN THIS PROCESS. Steps 1 and 2 -
// the backend and the two CallMask halves - happen in the server,
// which ran InitServerRoleForSpawn before it accepted us. Running
// them here as well would build a second BackendObject in the one
// process that must not have one, and would publish a capability
// mask computed from the WRONG backend's function table.
if (MG_Config::Transport == MG_Config::TransportMode::Spawn) {
const MobileGLResult started = Client::ClientSessionInstance().StartSpawned();
if (started != MOBILEGL_OK) {
MGLOG_E("MG_Remote: the spawn session failed to start (rc=%d); MobileGL will "
"NOT fall back to monolith - a lane named split that ran monolith is "
"the one failure this phase is built to make impossible",
static_cast<int>(started));
return false;
}
pActiveBackendObject = MakeUnique<MG_Remote::Client::BackendObject_Remote>();
return true;
}
if (!InitServerRoleCommon()) {
return false;
}
// 3. the handshake, the four segments, and - at its end - the apply thread.
const MobileGLResult started =
@@ -256,6 +295,19 @@ namespace MobileGL::MG_Backend {
}
#endif
#if MOBILEGL_BUILD_DISAGGREGATED
// The spawn server's entry into the SAME bring-up the inproc server role
// runs (ServerRole.h). A thin forwarder on purpose: the body stays in the
// anonymous namespace beside InitSplitRoles so the two cannot drift.
//
// THE WHOLE FUNCTION IS INSIDE THE GUARD, not just its body. A version with
// the guard inside still DEFINES the symbol in a pull build, and G1 caught
// it: 2 symbols added, 1 removed, .text +16 bytes. The pull build's identity
// is byte-for-byte, and "it returns false there" is not the same as "it is
// not there".
Bool InitServerRoleForSpawn() { return InitServerRoleCommon(); }
#endif
void Init() {
MGLOG_D("Initializing MobileGL Backend...");
@@ -276,6 +328,19 @@ namespace MobileGL::MG_Backend {
MGLOG_W("Failed to initialize MobileGL backend libraries for the remote object");
return;
}
// P6: BOTH CHECKS BELOW ARE STATEMENTS ABOUT THE SERVER'S PROCESS, and under
// spawn that is not this one. Their own wording says so - "a mask is a
// statement about THIS BACKEND", "the table the SERVER'S BACKEND registered at
// step 1" - and in a spawn client there is no backend and never was a table, so
// MGPipeGetResourceOps() is null by construction and the first check fires on a
// correct session. It did, on the first spawn retrace ever run.
//
// The checks are NOT weakened: the server runs the step-2 one itself, inside
// InitServerRoleForSpawn, against its own freshly registered table - which is the
// process where the question has an answer. What is lost under spawn is the
// step-5 re-run's ability to catch a table REPLACED between accept and here, and
// that is a question about one address space; it cannot be asked across two.
if (MG_Config::Transport != MG_Config::TransportMode::Spawn) {
// m-6, re-worded per review v2 N-8. The honesty cross-check runs a SECOND time, now
// that step 4's pActiveBackendObject (the client's BackendObject_Remote) exists and
// its Initialize() has run inside InitSpecificBackendLibs. What the re-run CAN catch
@@ -297,6 +362,7 @@ namespace MobileGL::MG_Backend {
static_cast<const void*>(g_resourceOpsAtStep2));
std::abort();
}
}
LogBackendInfo();
return;
}
+54 -5
View File
@@ -171,7 +171,10 @@ namespace MobileGL::MG_Pipe {
// crash exactly where the rehearsal exists to produce a named one. The red is the
// census (Harness/dualblock-expected-fatals.txt), so the marker keeps the strict
// grammar with the knob's own name as the reason.
if (MGPipeRoleSplitActive()) {
// D10: rides MGPipeBlocksAreDistinct() - under spawn the two blocks are distinct
// whatever the rehearsal knob says, and a barrier pull across a real process
// boundary is exactly the thing this Fatal exists to name.
if (MGPipeBlocksAreDistinct()) {
StrictBarrierPullFatal(field, verb, "MOBILEGL_IPC_ROLE_SPLIT_STATE=1");
}
if (!MGPipeApplierCurrentRecordIsBarriered()) {
@@ -286,16 +289,54 @@ namespace MobileGL::MG_Pipe {
// ---- P5f (f1): the dual-block rehearsal's selection functions (PipeInputs.h) -----------
//
// MGPipeRoleSplitActive is deliberately NOT latched: it is two global loads, asked once per
// MGPipeRoleSplitRehearsalActive is deliberately NOT latched: it is two global loads, asked once per
// verb on the fill side and once per verb boundary on the stamp side, and a latch is a
// second thing a test that flips the knob mid-process would have to know about.
Bool MGPipeRoleSplitActive() {
Bool MGPipeRoleSplitRehearsalActive() {
return MG_Config::Ipc.RoleSplitState &&
MG_Config::Transport != MG_Config::TransportMode::Monolith;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// ---- D1c's predicates (CONTRACT-P6 3.2) -------------------------------------------------
namespace {
// Set once by ServerMain, before any GL work. A spawn server is the server for the whole
// life of the process; there is no thread in it that is not.
Bool g_serverProcessRole = false;
// MG_Remote's "is the calling thread inside the applier". Null until a session installs
// it, which is the honest answer for a process that has no applier.
Bool (*g_applyThreadProbe)() = nullptr;
Bool g_sessionLive = false;
} // namespace
void MGPipeSetServerProcessRole(Bool isServerProcess) { g_serverProcessRole = isServerProcess; }
void MGPipeSetApplyThreadProbe(Bool (*probe)()) { g_applyThreadProbe = probe; }
void MGPipeSetSessionLive(Bool live) { g_sessionLive = live; }
Bool MGPipeServerArm() {
// THE PROCESS FACT FIRST, and it short-circuits: in a spawn server every thread is a
// server thread, and asking the probe would be asking MG_Remote a question it answers
// only about the applier.
if (g_serverProcessRole) return true;
return g_applyThreadProbe != nullptr && g_applyThreadProbe();
}
Bool MGPipeSessionLive() { return g_sessionLive; }
Bool MGPipeBlocksAreDistinct() {
// TWO DIFFERENT REASONS, ONE ANSWER. The rehearsal makes two blocks in one process;
// spawn makes them two blocks in two ADDRESS SPACES, where no knob is involved and the
// distinctness is a fact about the machine. The guards that used to ask only the first
// question were therefore disarmed in the one shape where the answer matters most - a
// spawn server's block is never the client's, whatever MOBILEGL_IPC_ROLE_SPLIT_STATE
// says.
return MGPipeRoleSplitRehearsalActive() ||
MG_Config::Transport == MG_Config::TransportMode::Spawn;
}
#endif // MOBILEGL_BUILD_DISAGGREGATED
PipeInputs& MGPipeClientInputs() {
return MGPipeRoleSplitActive() ? gPipeInputsClientBlock : gPipeInputs;
return MGPipeRoleSplitRehearsalActive() ? gPipeInputsClientBlock : gPipeInputs;
}
void MGPipeClientClearVerbBoundary() {
@@ -312,7 +353,15 @@ namespace MobileGL::MG_Pipe {
Bool MGPipeServerContextIsLive() { return g_serverContextLive; }
void MGPipeServerBlockNoteIdentity() {
if (!MGPipeRoleSplitActive()) return;
// D10: THE WIDER PREDICATE, and the narrow one was a latent crash rather than a missing
// optimisation. Gated on the REHEARSAL, this early-returned for the whole life of a
// spawn server - because that knob is off by default and nothing in the spawn shape
// turns it on - so the server's gPipeInputs.ContextIdentity() stayed nullptr forever.
// DirectGLES' fb-slot memo compares that identity FIRST and with no generation, so a
// nullptr against its own nullptr initialiser reads as a CACHE HIT and hands out a slot
// that was never filled. `st` lands the named Fatal at that site; this is the gate that
// stops it being reachable in the first place.
if (!MGPipeBlocksAreDistinct()) return;
// The server cannot name the client's GLContext - under a real transport it is in
// another process - so the identity the server block carries is the server's OWN
// served-context clock: MGPipeApplierContextSerial moves exactly when the served
+53 -2
View File
@@ -860,9 +860,60 @@ namespace MobileGL::MG_Pipe {
// Same leak-at-exit storage as gPipeInputs above, for the same reason.
inline PipeInputs& gPipeInputsClientBlock = *new PipeInputs();
// PipeInputs.cpp. Whether the rehearsal is armed: the knob AND a real transport (and not
// PipeInputs.cpp. Whether the REHEARSAL is armed: the knob AND a real transport (and not
// the verify build, which ConfigLoader forces off). Constant for the life of the process.
Bool MGPipeRoleSplitActive();
//
// D13 RENAMED THIS FROM MGPipeRoleSplitActive, which is what it has always meant. The old
// name read like "the roles are split", and the widening D1c needed would have made a
// narrow name lie - so the rename came FIRST and the wider predicate was introduced beside
// it rather than by quietly changing what this one answers.
Bool MGPipeRoleSplitRehearsalActive();
// ---- D1c: the role predicates (CONTRACT-P6 3.2) ---------------------------------------
//
// ONE QUESTION EACH, and the reason they are separate functions rather than one `split`
// flag is that the tree asks genuinely different things. a6 proposed three; three do not
// cover it.
//
// D14: IN A NON-DISAGGREGATED BUILD THESE GET A DIFFERENT DEFINITION, not a runtime-false
// one. The `#else` arm is `constexpr`, so every consult folds at compile time and the pull
// build gains no symbol, no branch and no byte - which G1 measures rather than assumes.
#if MOBILEGL_BUILD_DISAGGREGATED
// Am I executing as the SERVER right now? A thread-scoped question in the inproc shape,
// where both roles live in one process, and a process-scoped one under spawn.
Bool MGPipeServerArm();
// Is a peer session live? Distinct from "is the transport split": a spawn SERVER has no
// ClientSession at all, so a guard that asked for one was permanently disarmed there.
Bool MGPipeSessionLive();
// Do the two roles use DIFFERENT PipeInputs storage objects?
//
// TRUE FOR TWO DIFFERENT REASONS, which is the whole point of the predicate. Under the
// rehearsal the two blocks are distinct objects in one process; under SPAWN they are
// distinct because they are in different address spaces, and no knob is involved. The
// guards below used to ask the rehearsal question and were therefore silently off in the
// one shape where the answer matters most.
Bool MGPipeBlocksAreDistinct();
// The two facts the predicates above are built from, stated ONCE by the code that knows
// them. Neither is discoverable from MG_Backend: "this process is the server" is something
// only ServerMain can say, and "am I on the apply thread" is MG_Remote's thread-local.
//
// A PROBE RATHER THAN A FLAG for the thread half, because it is a question about the
// CALLING thread and a flag would answer for whichever thread wrote it last.
void MGPipeSetServerProcessRole(Bool isServerProcess);
void MGPipeSetApplyThreadProbe(Bool (*probe)());
void MGPipeSetSessionLive(Bool live);
#else
inline constexpr Bool MGPipeServerArm() { return false; }
inline constexpr Bool MGPipeSessionLive() { return false; }
inline constexpr Bool MGPipeBlocksAreDistinct() { return false; }
// Setters too: a caller guarded only at its own site would still need these to LINK.
inline void MGPipeSetServerProcessRole(Bool) {}
inline void MGPipeSetApplyThreadProbe(Bool (*)()) {}
inline void MGPipeSetSessionLive(Bool) {}
#endif
// PipeInputs.cpp. THE FILL SIDE'S ONE NEW SPELLING: the client block when the rehearsal is
// armed, gPipeInputs otherwise. Everything in MG_Impl/Pipe/PipeFill.cpp that used to spell
// gPipeInputs spells this instead.
+45
View File
@@ -0,0 +1,45 @@
// MobileGL - MobileGL/MG_Backend/ServerRole.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// The server role's bring-up, as one entry point two shapes share.
//
// Steps 1 and 2 of Init.cpp's split bring-up - the server's private
// BackendObject, and the two CallMask halves computed from THAT backend's own
// function table. Under `inproc` InitSplitRoles calls it and then starts the
// client in the same process; under `spawn` the child's ServerMain calls it and
// then accepts a connection instead.
//
// ONE ENTRY POINT, not two, because the capability bits are a statement about
// the server's backend and only the server can compute them. A second copy in
// ServerMain would be a second answer to "does this backend own the XFB
// capture", diverging silently the first time a backend registers a slot.
#pragma once
#include <Includes.h>
// DECLARED ONLY IN A DISAGGREGATED BUILD. G1 requires the pull build's symbol
// set and .text to be byte-identical, and a definition guarded only on the
// inside still emits a symbol - measured, not assumed.
#if MOBILEGL_BUILD_DISAGGREGATED
namespace MobileGL::MG_Backend {
// Creates the server's BackendObject and publishes the consumed-subsystem
// mask and the capability bits onto ServerSessionInstance(). Does NOT create
// an EGL context: that happens later, on the apply thread, when the client's
// first eglMakeCurrent crosses as a blocking control request.
//
// Returns false when the backend could not be created, and the caller must
// then REFUSE TO CONTINUE rather than fall back - a server process that came
// up without a backend would accept a session it can never apply.
Bool InitServerRoleForSpawn();
} // namespace MobileGL::MG_Backend
#endif // MOBILEGL_BUILD_DISAGGREGATED
@@ -18,6 +18,13 @@
#include <MG_State/GLState/Core.h>
#include <MG_State/GLState/ErrorState/ErrorInfo.h>
#include <MG_Util/Converters/GLToStr/GLEnumConverter.h>
// GUARDED AT THE INCLUDE, not just around the call. This file compiles in the PULL build too,
// and G1 requires that build's symbol set and .text to be byte-identical - a header that drags
// in MG_Remote would change it whether or not any code path reaches the session.
#if MOBILEGL_BUILD_DISAGGREGATED
#include <MG_Remote/Client/ClientSession.h>
#endif
#include <MG_Util/Converters/GLToMG/BufferEnumConverter.h>
#include <MG_Util/Converters/GLToMG/RenderStateEnumConverter.h>
#include <MG_Util/Converters/MGToGL/FramebufferEnumConverter.h>
@@ -2853,6 +2860,27 @@ namespace MobileGL::MG_Impl::GLImpl {
}
GLenum GetGraphicsResetStatus() {
#if MOBILEGL_BUILD_DISAGGREGATED
// P6 `dl` (CONTRACT-P6 5.3): THE ONE GL-VISIBLE CONSEQUENCE OF A DEAD SERVER.
//
// Before this, "a dead server leaves the client silently DECLINE-ing every verb forever
// with glGetError clean" - the contract's own words, and the reason the latch is a
// package rather than carriage. An application that asks the robustness question has no
// other way to find out, because a DECLINE is indistinguishable from a verb that
// happened.
//
// GL_UNKNOWN_CONTEXT_RESET, not GUILTY or INNOCENT. Those two assign BLAME - guilty
// means this context's commands caused the reset, innocent means another context's did -
// and neither is knowable here: the server died for a reason that never crossed the
// wire, and it could as easily have been a driver fault as this client's draw. UNKNOWN is
// the spec's answer for exactly that, and it is the one that does not lie.
//
// WHOLLY INSIDE THE GUARD, including the include above. In a pull build this function is
// byte-for-byte what it was, which is what G1 measures.
if (MG_Remote::Client::ClientSession::DeviceLost()) {
return GL_UNKNOWN_CONTEXT_RESET;
}
#endif
// MobileGL does not implement robustness reset notification, so report GL_NO_ERROR
// ("no reset detected"). Returning the generic stub's (GLenum)1 makes dEQP read a lost
// device after every case (gl3cTestPackages.cpp:121) and, under the default
+15 -2
View File
@@ -11,6 +11,7 @@
#if MOBILEGL_BUILD_DISAGGREGATED
#include <Config.h>
#include <MG_Backend/MGPipe/PipeInputs.h> // D1c: MGPipeServerArm()
#include <MG_Pipe/PipeApply.h>
#include <MG_Remote/Server/ServerLoop.h>
#include <MG_Util/Debug/Log.h>
@@ -28,7 +29,13 @@ namespace MobileGL::MG_Pipe {
void MGPipeRefuseAllocatorFromApplyThread(const char* entry) {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
if (!MG_Remote::Server::ServerLoop::OnApplyThread()) return;
// D10: OR'd with the PROCESS-ROLE fact, not replaced by it. OnApplyThread() answers
// about the INPROC applier thread and is the only fact a ServerLoop fixture with no
// client session has; MGPipeServerArm() adds the spawn case, where EVERY thread is a
// server thread. Replacing the first with the second disarmed the refusal in every unit
// test that drives the apply thread directly - measured, 14 RemoteGuards cases went
// green-by-omission before this was put back as a disjunction.
if (!MG_Remote::Server::ServerLoop::OnApplyThread() && !MG_Pipe::MGPipeServerArm()) return;
// P5f (fr): all named allocator exemptions are retired. A barrier can
// stabilize a client allocator but cannot make it server-owned memory.
MGLOG_F("MGPipe: Fatal{RoleViolation, \"MGPipeSlots\"} - the apply thread called "
@@ -47,7 +54,13 @@ namespace MobileGL::MG_Pipe {
// make a frontend SharedPtr exist in a separate server process.
void MGPipeRefuseFrontendKeyedRegistryFromApplyThread(const char* entry) {
if (MG_Config::Transport == MG_Config::TransportMode::Monolith) return;
if (!MG_Remote::Server::ServerLoop::OnApplyThread()) return;
// D10: OR'd with the PROCESS-ROLE fact, not replaced by it. OnApplyThread() answers
// about the INPROC applier thread and is the only fact a ServerLoop fixture with no
// client session has; MGPipeServerArm() adds the spawn case, where EVERY thread is a
// server thread. Replacing the first with the second disarmed the refusal in every unit
// test that drives the apply thread directly - measured, 14 RemoteGuards cases went
// green-by-omission before this was put back as a disjunction.
if (!MG_Remote::Server::ServerLoop::OnApplyThread() && !MG_Pipe::MGPipeServerArm()) return;
MGLOG_F("MGPipe: Fatal{RoleViolation, \"MGPipeSlots\"} - the apply thread reached "
"BackendSlotTable::%s. Frontend-identity registry operations are monolith-only, "
"including barriered records; resolve the twin from the record's handle instead",
+89 -112
View File
@@ -1983,36 +1983,75 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
#
# ClearThenReadPixelsScenario is target A of the reduced path and already existed; Triangle is
# target B and PersistentCoherentMap is target C, both new in P5.
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST MGL_SPLIT_CLEAR_TESTS
TEST_FILTER "ClearThenReadPixelsScenario.*"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST MGL_SPLIT_TRIANGLE_TESTS
TEST_FILTER "TriangleScenario.*"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST MGL_SPLIT_PMAP_TESTS
TEST_FILTER "PersistentCoherentMapScenario.*"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
# ---- P6 `t6`: THE SPAWN ARM, beside the inproc one and never instead of it --------------
#
# EXIT GATES 9.2 AND 9.3: `integration-spawn`'s case-name set must be IDENTICAL to
# `integration-split`'s, and it must be green at the same count.
#
# THAT IDENTITY IS MADE STRUCTURAL RATHER THAN MAINTAINED. Registering the spawn arm as a
# second copy of each block would make the two sets agree today and drift the first time
# somebody adds a scenario to one of them - and a spawn lane covering LESS than the split
# lane goes green while proving less, with nothing to say so. One macro emits both arms from
# one filter, so a case added to either is added to both or to neither.
#
# ONE ENVIRONMENT DIFFERENCE, AND IT IS THE SUBJECT OF THE LANE. MOBILEGL_TRANSPORT=spawn
# makes the test process the CLIENT and has it launch a server from MOBILEGL_IPC_SERVER_PATH
# - the same path the inproc arm already carries, because under inproc the library reads it
# and decides it does not need one.
mgl_itest_join_environment(MGL_ITEST_GLES_SPAWN_ENVIRONMENT
"MOBILEGL_BACKEND_TYPE=DirectGLES" "MOBILEGL_TRANSPORT=spawn"
"MOBILEGL_IPC_SERVER_PATH=${MGL_ITEST_SPLIT_SERVER_PATH}" "MGITEST_SPLIT_LANE=1"
${MGL_ITEST_CAPABILITY_ENV} ${MGL_ITEST_COMMON_ENV})
# scenarioFilter, a PREFIX TAIL (empty for most; "F1." and "Ct." for the two per-slot loops,
# which name their sub-lane in the test name), then zero or more EXTRA LABEL STEMS. A stem is
# suffixed with the arm's own name (`integration-clientarrays` becomes `-split` on one arm and
# `-spawn` on the other), so a lane-scoped label cannot accidentally name both lanes at once.
# A UNIQUE LIST VARIABLE PER CALL, and the names collected for SplitLogPaths to walk.
#
# gtest_discover_tests' TEST_LIST is not a configure-time value: the generated include file
# sets it when CTEST runs. So one shared variable would hold only the LAST block's entries -
# measured, and it is why the first version of this macro silently unhooked every private log
# path but one. The counter gives each call its own name; the names are what get walked.
set(MGL_SPLIT_ARM_TESTS "")
set(MGL_SPLIT_ARM_TEST_LISTS "")
set(MGL_SPLIT_ARM_INDEX 0)
macro(mgl_itest_register_split_arms scenarioFilter prefixTail)
foreach(mglItestArm IN ITEMS Split Spawn)
string(TOLOWER "${mglItestArm}" mglItestArmLower)
string(TOUPPER "${mglItestArm}" mglItestArmUpper)
set(mglItestArmLabels "integration-gpu\\;integration-${mglItestArmLower}")
foreach(mglItestExtra IN ITEMS ${ARGN})
set(mglItestArmLabels "${mglItestArmLabels}\\;${mglItestExtra}-${mglItestArmLower}")
endforeach()
# ONE ACCUMULATED LIST FOR BOTH ARMS, and it is not bookkeeping: SplitLogPaths gives
# every entry a PRIVATE MOBILEGL_LOG_FILE_PATH, and SplitLogPaths.PrivateAndDistinct
# reds if one is missing or shared. The per-block TEST_LIST variables this macro
# replaced were what fed it - dropping them silently unhooked the whole mechanism,
# which that gate caught. Accumulating here means a block added later is covered
# without anyone remembering to add its variable to the list.
#
# IT MATTERS MORE ON THE SPAWN ARM: there TWO PROCESSES append to the path, so two
# entries sharing one file is not merely ambiguous, it interleaves two sessions.
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.${mglItestArm}.${prefixTail}"
TEST_LIST "MGL_SPLIT_ARM_TESTS_${MGL_SPLIT_ARM_INDEX}"
TEST_FILTER "${scenarioFilter}"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "${mglItestArmLabels}"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_${mglItestArmUpper}_ENVIRONMENT}"
)
list(APPEND MGL_SPLIT_ARM_TEST_LISTS "MGL_SPLIT_ARM_TESTS_${MGL_SPLIT_ARM_INDEX}")
math(EXPR MGL_SPLIT_ARM_INDEX "${MGL_SPLIT_ARM_INDEX} + 1")
endforeach()
endmacro()
mgl_itest_register_split_arms("ClearThenReadPixelsScenario.*" "")
mgl_itest_register_split_arms("TriangleScenario.*" "")
mgl_itest_register_split_arms("PersistentCoherentMapScenario.*" "")
# ---- P5e fix1: THE PUSH-MONOLITH ARM, INSIDE THE GATED SET (ID-107) ----------------------
#
@@ -2077,16 +2116,7 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
set(MGL_SPLIT_D1_FILTER_DrawParametersScenario "DrawParametersScenario.*")
set(MGL_SPLIT_D1_FILTER_PrimitiveRestartScenario "PrimitiveRestartScenario.*")
foreach(mglItestD1Scenario IN LISTS MGL_SPLIT_D1_SCENARIOS)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST "MGL_SPLIT_D1_${mglItestD1Scenario}_TESTS"
TEST_FILTER "${MGL_SPLIT_D1_FILTER_${mglItestD1Scenario}}"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
mgl_itest_register_split_arms("${MGL_SPLIT_D1_FILTER_${mglItestD1Scenario}}" "")
endforeach()
# ---- P5e mv: THE MULTI-DRAW TIERS, INSIDE THE GATED SET (ID-109's rule, one level down) --
@@ -2199,16 +2229,7 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
set(MGL_SPLIT_I1_FILTER_AtomicCounterScenario "AtomicCounterScenario.*")
set(MGL_SPLIT_I1_FILTER_ProgramPipelineScenario "ProgramPipelineScenario.*StorageBlock*")
foreach(mglItestI1Scenario IN LISTS MGL_SPLIT_I1_SCENARIOS)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST "MGL_SPLIT_I1_${mglItestI1Scenario}_TESTS"
TEST_FILTER "${MGL_SPLIT_I1_FILTER_${mglItestI1Scenario}}"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
mgl_itest_register_split_arms("${MGL_SPLIT_I1_FILTER_${mglItestI1Scenario}}" "")
endforeach()
# ---- P5b t2: the transform-feedback spans, the XFB object bind, the patch parameter -------
@@ -2237,53 +2258,17 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
# Every DirectVulkan XFB capture entry in the inproc census fails on exactly that (t2-v1.md
# §"the 51"), and it retires with P7 (Magma's resource family) / P9 (the readback carrier) -
# not here. A DirectVulkan arm of this lane would be red for a reason t2 cannot fix.
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST MGL_SPLIT_T2_TESS_TESTS
TEST_FILTER "TessellationXfbCaptureScenario.*"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST MGL_SPLIT_T2_XFB_TESTS
TEST_FILTER "XfbCaptureBufferReuseScenario.*"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
mgl_itest_register_split_arms("TessellationXfbCaptureScenario.*" "")
mgl_itest_register_split_arms("XfbCaptureBufferReuseScenario.*" "")
# ---- P5e package vi (MG_Remote/CONTRACT-P5E.md §5.1, ID-82 / ruling 2) --------------------
#
# Client-memory vertices and indices now cross as owned ordinary buffers.
# Keep the original names and private logs; all six scenarios join the full
# GPU and split acceptance labels as well as their focused regression label.
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST MGL_SPLIT_VI_CLIENT_ARRAY_TESTS
TEST_FILTER "ClientVertexArrayScenario.*"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split\;integration-clientarrays-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
mgl_itest_register_split_arms("ClientVertexArrayScenario.*" "" integration-clientarrays)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split."
TEST_LIST MGL_SPLIT_SYNC_TESTS
TEST_FILTER "SyncWireScenario.*"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}"
)
mgl_itest_register_split_arms("SyncWireScenario.*" "")
# The split half of the counting pair. MGITEST_PERSISTENT_MAP_ARM=emulated is R-6: under split
# the adopt tier is pinned at T2, the resource owner declines every acquisition and the client
@@ -2400,10 +2385,12 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_STRICT_ENVIRONMENT}"
)
# Apply per-entry paths after GoogleTest discovery has populated the TEST_LISTs.
configure_file(Harness/SplitLogPaths.cmake.in SplitLogPaths.cmake @ONLY)
set_property(DIRECTORY APPEND PROPERTY TEST_INCLUDE_FILES
"${CMAKE_CURRENT_BINARY_DIR}/SplitLogPaths.cmake")
# The configure_file that used to sit here MOVED TO THE END OF THIS FILE (P6 `t6`).
#
# It substitutes @MGL_SPLIT_ARM_TEST_LISTS@, which the registration macro appends to - so
# running it here captured only the calls made ABOVE this line and silently dropped the F1
# and Ct blocks below it. SplitLogPaths.PrivateAndDistinct is what caught that, naming
# F1WireScenario.ClearBufferfiPixels; the generated file now sees every call.
# Python is mandatory for this split integration gate (also used by the CI controls).
# Do not silently omit the ownership check when the interpreter is unavailable.
find_package(Python3 REQUIRED COMPONENTS Interpreter)
@@ -2418,15 +2405,7 @@ endif()
if (MOBILEGL_BUILD_DISAGGREGATED)
target_sources(MobileGLIntegrationTest PRIVATE Scenarios/F1WireScenario.cpp)
foreach(f1Slot ClearBufferfi ClearBufferfv ClearBufferiv ClearBufferuiv ClearNamedFramebufferfi ClearNamedFramebufferfv ClearNamedFramebufferiv ClearNamedFramebufferuiv CopyTexImage2D CopyTexSubImage2D GenerateMipmap GenerateMipmapPackedFloat GenerateMipmapDepth)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split.F1."
TEST_FILTER "F1WireScenario.${f1Slot}Pixels"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}\;MOBILEGL_LOG_FILE_PATH=${CMAKE_CURRENT_BINARY_DIR}/p5b-f1-${f1Slot}.log"
)
mgl_itest_register_split_arms("F1WireScenario.${f1Slot}Pixels" "F1.")
endforeach()
# P5f fm: the framebuffer/copy/mipmap verbs now consume server records on Magma too.
mgl_itest_join_environment(MGL_ITEST_MAGMA_WIRE_ENVIRONMENT
@@ -2579,15 +2558,7 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
TextureDeathCrossesAndTheRecycledSlotAnswersTheNewObject
FramebufferDeathCrossesAndTheRecycledSlotAnswersTheNewObject
TheDirectApplierResetCallOnTheGLThreadIsRoleViolation)
gtest_discover_tests(MobileGLIntegrationTest
TEST_PREFIX "DirectGLES.Split.Ct."
TEST_FILTER "CtWireScenario.${ctCase}"
DISCOVERY_TIMEOUT 30
PROPERTIES
LABELS "integration-gpu\;integration-split"
TIMEOUT ${MGL_ITEST_TIMEOUT}
ENVIRONMENT "${MGL_ITEST_GLES_SPLIT_ENVIRONMENT}\;MOBILEGL_LOG_FILE_PATH=${CMAKE_CURRENT_BINARY_DIR}/p5c-ct-${ctCase}.log"
)
mgl_itest_register_split_arms("CtWireScenario.${ctCase}" "Ct.")
endforeach()
endif()
@@ -2754,6 +2725,12 @@ if (MOBILEGL_BUILD_DISAGGREGATED)
endif()
if (MOBILEGL_BUILD_DISAGGREGATED)
# LAST, so every mgl_itest_register_split_arms call above has already contributed its list
# name. Apply per-entry paths after GoogleTest discovery has populated the TEST_LISTs.
configure_file(Harness/SplitLogPaths.cmake.in SplitLogPaths.cmake @ONLY)
set_property(DIRECTORY APPEND PROPERTY TEST_INCLUDE_FILES
"${CMAKE_CURRENT_BINARY_DIR}/SplitLogPaths.cmake")
add_test(NAME SplitLogPaths.ResultAccountingControls
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Harness/test_split_log_paths.py)
set_tests_properties(SplitLogPaths.ResultAccountingControls PROPERTIES LABELS "unit")
@@ -32,7 +32,7 @@ namespace MGITest {
if (out == nullptr) return false;
namespace MGP = MobileGL::MG_Pipe;
out->peekAvailable = true;
out->roleSplitActive = MGP::MGPipeRoleSplitActive();
out->roleSplitActive = MGP::MGPipeRoleSplitRehearsalActive();
MGP::PipeInputs& client = MGP::MGPipeClientInputs();
out->blocksDistinct = &client != &MGP::gPipeInputs;
out->clientSerial = client.FilledState().CurrentVerbSerial;
@@ -29,7 +29,7 @@ namespace MGITest {
// False wherever the peek cannot look (see the header above). Everything else is
// meaningful only when this is true.
bool peekAvailable = false;
// MGPipeRoleSplitActive(): the knob AND a real transport. The control's red half turns
// MGPipeRoleSplitRehearsalActive(): the knob AND a real transport. The control's red half turns
// on this answer alone.
bool roleSplitActive = false;
// &MGPipeClientInputs() != &gPipeInputs - the fill side and the read side are two
@@ -29,6 +29,7 @@
#pragma once
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
@@ -37,10 +38,51 @@
namespace MGITest::PipeStatsWindow {
// The lane's private log path, or empty when the lane configured none.
inline std::string LibraryLogPath() {
const char* path = std::getenv("MOBILEGL_LOG_FILE_PATH");
return (path != nullptr && *path != '\0') ? std::string(path) : std::string();
// P6: MOBILEGL_LOG_FILE_PATH IS A BASE NAME, NOT A FILE. The library writes one log per
// ROLE - `<stem>.client<ext>` and `<stem>.server<ext>` - because under inproc both roles are
// threads of one process and a single file made every per-side assertion a search.
//
// THE RULE IS COPIED HERE AND IT HAS TO BE, which is worth stating because the obvious fix is
// to call the library's own MG_Util::Debug::RoleLogPath and delete this. That does not link:
// this module links the SHIPPING libMobileGL.so, built -fvisibility=hidden, and the role-path
// helpers are `t` (local) in it - only MG_Test, which links the static archive, may call them.
//
// SO THE COPY IS FLAVOUR-AWARE INSTEAD. That is the part the first copy got wrong: it derived
// `.client` in BOTH flavours, while the pull build has one role and writes
// MOBILEGL_LOG_FILE_PATH unchanged. In the verify lane it therefore opened a file that never
// existed and every reader reported "the library never logged" - a product failure that had
// not happened. Keep this `#if` and Log.cpp's RoleLogPath in step.
inline std::string RoleLogPath(const char* roleSuffix) {
const char* base = std::getenv("MOBILEGL_LOG_FILE_PATH");
if (base == nullptr || *base == '\0') return {};
#if MOBILEGL_BUILD_DISAGGREGATED
std::string path(base);
const std::string::size_type slash = path.find_last_of("/\\");
const std::string::size_type dot = path.find_last_of('.');
if (dot == std::string::npos || (slash != std::string::npos && dot < slash)) {
return path + "." + roleSuffix;
}
return path.substr(0, dot) + "." + roleSuffix + path.substr(dot);
#else
(void)roleSuffix;
return std::string(base);
#endif
}
// The lane's private CLIENT log path, or empty when the lane configured none. In the pull
// build this IS the whole log.
inline std::string LibraryLogPath() { return RoleLogPath("client"); }
// The server role's half, or EMPTY when this build has no separate server half. Empty rather
// than "the same path again": every caller below concatenates the two, and a pull build that
// named one file twice would show each line twice - which reads as a doubled counter or a
// repeated diagnostic rather than as a path mistake.
inline std::string ServerLibraryLogPath() {
#if MOBILEGL_BUILD_DISAGGREGATED
return RoleLogPath("server");
#else
return {};
#endif
}
inline std::string ReadWholeFile(const std::string& path) {
@@ -50,6 +92,51 @@ namespace MGITest::PipeStatsWindow {
return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}
inline std::string ReadFileSince(const std::string& path, std::uintmax_t offset) {
if (path.empty()) return {};
std::ifstream file(path, std::ios::binary);
if (!file.good()) return {};
file.seekg(static_cast<std::streamoff>(offset));
return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}
// A "the log is this long right now" snapshot, ONE OFFSET PER ROLE.
//
// The scenarios that assert on arming take a mark before the workload and read what was
// appended after it, so that only bytes this case caused can satisfy - or refute - the claim.
// The roles are separate files, so this cannot be one scalar: a single offset applied to the
// concatenation would slide by however much the OTHER role happened to write, and the read
// would start mid-line in the wrong file.
struct LogMark {
std::uintmax_t client = 0;
std::uintmax_t server = 0;
};
inline std::uintmax_t FileSizeOrZero(const std::string& path) {
if (path.empty()) return 0;
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file.good()) return 0;
const std::streamoff size = file.tellg();
return size < 0 ? 0 : static_cast<std::uintmax_t>(size);
}
inline LogMark MarkLaneLog() {
return LogMark{FileSizeOrZero(LibraryLogPath()), FileSizeOrZero(ServerLibraryLogPath())};
}
// BOTH ROLES, and for the arming diagnostics the SERVER's is the one that matters. Those lines
// are emitted by the BACKEND - "demoted to an ordinary varying", the reroute and emulation
// banners - and under inproc the backend runs on the apply thread, which is the server role.
// Reading only the client's half finds nothing and reports "the emulation is not armed",
// which is the most expensive possible way to be wrong: it accuses the product of a defect
// that the reader itself invented.
inline std::string ReadLaneLogSince(const LogMark& mark) {
return ReadFileSince(LibraryLogPath(), mark.client)
+ ReadFileSince(ServerLibraryLogPath(), mark.server);
}
inline std::string ReadLaneLog() { return ReadLaneLogSince(LogMark{}); }
// The last summary line in the log, verbatim. `found` is false when the library never emitted
// one, which is a different failure from "the counter read zero" and has to be reported as
// one: it means the stats channel never reached the process, not that the workload did
@@ -70,7 +157,15 @@ namespace MGITest::PipeStatsWindow {
return window;
}
inline Window LastFromLaneLog() { return Last(ReadWholeFile(LibraryLogPath())); }
// BOTH ROLES, and the server's is where the numbers are. The `draws` / `vbs` counters
// increment in the backend's PrepareForDraw, which runs on the APPLY THREAD - the server
// role - so under inproc split the summary line lands in the server's log. Reading only the
// client's would find the "counters ON" banner (client-side) but no window, which reads as
// "the stats channel never reached the process". Concatenated, Last() takes whichever role
// emitted the final summary.
inline Window LastFromLaneLog() {
return Last(ReadWholeFile(LibraryLogPath()) + ReadWholeFile(ServerLibraryLogPath()));
}
// One counter out of that line, by its short name ("mpr", "draws", "csom"), or -1 when the
// line does not carry it. The search includes the SEPARATOR before the name and the `=` after
@@ -8,10 +8,19 @@ file(MAKE_DIRECTORY "@CMAKE_CURRENT_BINARY_DIR@/split-logs")
# the caps bit, and a shared log file is a marker nobody can attribute.
# P5e pa's strict lane joins it for the same reason as vi's: its four entries exist to CARRY a
# Fatal marker (the two program rows), and a shared log file is a marker nobody can attribute.
foreach(entry IN LISTS MGL_SPLIT_CLEAR_TESTS MGL_SPLIT_TRIANGLE_TESTS MGL_SPLIT_PMAP_TESTS
MGL_SPLIT_T2_TESS_TESTS MGL_SPLIT_T2_XFB_TESTS MGL_SPLIT_SYNC_TESTS
MGL_SPLIT_VI_CLIENT_ARRAY_TESTS
MGL_SPLIT_PA_STRICT_DRAW_TESTS MGL_SPLIT_PA_STRICT_DISPATCH_TESTS)
# P6 `t6`: ONE LIST FOR EVERY ENTRY THE SHARED REGISTRATION MACRO EMITS, on BOTH arms. The
# per-block TEST_LIST variables this replaces were a list somebody had to remember to extend;
# a block added without its variable got no private log and nothing said so until
# PrivateAndDistinct happened to notice. The macro accumulates instead.
# The macro's per-call lists, walked by NAME: gtest_discover_tests populates each of them when
# ctest runs, which is also when this file is included.
foreach(listName IN ITEMS @MGL_SPLIT_ARM_TEST_LISTS@)
foreach(entry IN LISTS ${listName})
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
endforeach()
endforeach()
foreach(entry IN LISTS MGL_SPLIT_PA_STRICT_DRAW_TESTS MGL_SPLIT_PA_STRICT_DISPATCH_TESTS)
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
endforeach()
@@ -21,13 +30,7 @@ foreach(scenario @MGL_SPLIT_SMALL_RING_SCENARIOS@)
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
endforeach()
endforeach()
# P5b d1's split entries: the same private, distinct log per entry.
foreach(scenario @MGL_SPLIT_D1_SCENARIOS@)
foreach(entry IN LISTS MGL_SPLIT_D1_${scenario}_TESTS)
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
endforeach()
endforeach()
# d1's entries are covered by MGL_SPLIT_ARM_TESTS above (P6 `t6`).
# P5e mv's five tier-pinned lanes, the same rule for the same reason - and here it also repairs
# the addendum §4 blind spot for them: these entries carry a third name segment, so the strict
@@ -43,7 +46,9 @@ endforeach()
# P5b package i1's four scenarios, the same shape as the small-ring loop above: every
# DirectGLES.Split. entry owns exactly one absolute log path and shares it with nobody, which
# is what SplitLogPaths.PrivateAndDistinct checks over the discovered set.
foreach(scenario @MGL_SPLIT_I1_SCENARIOS@)
# i1's entries are covered by MGL_SPLIT_ARM_TESTS above (P6 `t6`); the loop is kept as a no-op
# shell only so the surrounding prose still reads against a structure.
foreach(scenario "")
foreach(entry IN LISTS MGL_SPLIT_I1_${scenario}_TESTS)
set_tests_properties("${entry}" PROPERTIES ENVIRONMENT
"MOBILEGL_LOG_FILE_PATH=@CMAKE_CURRENT_BINARY_DIR@/split-logs/${entry}.log")
@@ -96,10 +96,10 @@ namespace MGITest {
if (!control) return false;
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
do {
if (control->appliedSeq.load(std::memory_order_acquire) >= seq) return true;
if (control->Progress.appliedSeq.load(std::memory_order_acquire) >= seq) return true;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
} while (std::chrono::steady_clock::now() < until);
return control->appliedSeq.load(std::memory_order_acquire) >= seq;
return control->Progress.appliedSeq.load(std::memory_order_acquire) >= seq;
#else
(void)seq; (void)timeoutMs;
return false;
@@ -143,9 +143,9 @@ namespace MGITest {
state.presentCredit = MobileGL::MG_Config::Ipc.PresentCredit;
state.presentCreditWaits = session->PresentCreditWaits();
if (const auto* control = session->Control()) {
state.appliedSeq = control->appliedSeq.load(std::memory_order_acquire);
state.retiredSeq = control->retiredSeq.load(std::memory_order_acquire);
state.presentAckSerial = control->presentAckSerial.load(std::memory_order_acquire);
state.appliedSeq = control->Progress.appliedSeq.load(std::memory_order_acquire);
state.retiredSeq = control->Progress.retiredSeq.load(std::memory_order_acquire);
state.presentAckSerial = control->Progress.presentAckSerial.load(std::memory_order_acquire);
}
// The producer's ledger. Every one of these is a plain member read on the encoder
@@ -9,6 +9,38 @@ import sys
import xml.etree.ElementTree as ET
# P6: THE SINK WRITES ONE FILE PER ROLE, so MOBILEGL_LOG_FILE_PATH is a BASE NAME and no file
# of that literal name exists. The derivation matches MG_Util/Debug/Log.cpp's RoleLogPath: the
# role goes before the extension. A census that read the base would find nothing and report a
# confident zero for every marker the run actually raised - which under split is most of them,
# because the applier's refusals are on the server side.
def role_paths(base):
text = str(base)
slash = max(text.rfind("/"), text.rfind("\\"))
dot = text.rfind(".")
out = []
for role in ("client", "server"):
if dot == -1 or dot < slash:
out.append(text + "." + role)
else:
out.append(text[:dot] + "." + role + text[dot:])
return out
def read_role_logs(base):
"""Concatenated text of every role file that exists for this base, or '' if none do."""
chunks = []
for path in role_paths(base):
p = Path(path)
if p.is_file():
chunks.append(p.read_text(errors="replace"))
return "".join(chunks)
def any_role_file(base):
return any(Path(p).is_file() for p in role_paths(base))
def paths(document):
owners = {}
split = {}
@@ -89,10 +121,10 @@ def classify_markers(logs):
scanned = []
for name in sorted(logs):
path = logs[name]
if not Path(path).is_file():
if not any_role_file(path):
continue
scanned.append(name)
text = Path(path).read_text(errors="replace")
text = read_role_logs(path)
for tag, field, verb, why in MARKER_RE.findall(text):
pair = f"{field}@{verb}"
if tag == "Fatal":
@@ -204,12 +236,12 @@ def expect_fatal(document, junit_path, expected_path):
if failed:
problems.append(f"{name} is RED and declares no private log")
continue # metadata/monolith-arm entries have no marker channel
if not Path(path).is_file():
problems.append(f"{name}: declared private log {path} does not exist")
if not any_role_file(path):
problems.append(f"{name}: declared private log {path} has no role file (.client/.server)")
continue
scanned += 1
entry_fatal = set()
for tag, field, verb, why in MARKER_RE.findall(Path(path).read_text(errors="replace")):
for tag, field, verb, why in MARKER_RE.findall(read_role_logs(path)):
pair = f"{field}@{verb}"
if tag == "Fatal":
entry_fatal.add(pair)
@@ -380,7 +412,7 @@ def main():
missing = []
label = sys.argv[5] if len(sys.argv) > 5 else ""
for name, path in selected.items():
if Path(path).is_file() and re.search(sys.argv[4], Path(path).read_text(errors="replace")):
if any_role_file(path) and re.search(sys.argv[4], read_role_logs(path)):
print(f"private-log evidence: {name}: {path}")
else:
missing.append(f"{name} ({path})")
@@ -31,12 +31,15 @@ class ResultAccountingTest(unittest.TestCase):
self.temp.cleanup()
def discovery(self, names):
# P6: the ENV path is a BASE NAME and the library writes <base>.client.log /
# <base>.server.log. The fixture writes the CLIENT role file - what a real run leaves on
# disk - while the XML carries the base, exactly as the lane does.
tests = []
for i, name in enumerate(names):
log = self.root / (str(i) + ".log")
log.write_text("")
base = self.root / (str(i) + ".log")
(self.root / (str(i) + ".client.log")).write_text("")
tests.append({"name": name, "properties": [{"name": "ENVIRONMENT", "value": [
"MOBILEGL_LOG_FILE_PATH=" + str(log)]}]})
"MOBILEGL_LOG_FILE_PATH=" + str(base)]}]})
return {"tests": tests}
def results(self, rows):
@@ -97,7 +100,7 @@ class ResultAccountingTest(unittest.TestCase):
def test_admitted_or_fatal_on_passed_case_is_not_hidden(self):
for marker in ['Admitted{UnmigratedPipeInput, "GetProgramObject@Clear"}',
'Fatal{UnmigratedPipeInput, "GetProgramObject@Clear"}']:
(self.root / "0.log").write_text(marker)
(self.root / "0.client.log").write_text(marker)
with self.assertRaises(ValueError):
self.census()
@@ -71,6 +71,7 @@
#include <string>
#include <vector>
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
@@ -124,8 +125,9 @@ void main() { oColor = vec4(0.0, 1.0, 0.0, 1.0); }
}
std::string LibraryLogPath() {
const char* path = std::getenv("MOBILEGL_LOG_FILE_PATH");
return (path != nullptr && *path != '\0') ? std::string(path) : std::string();
// P6: the path is a BASE NAME and the library writes one log per role; PipeStatsWindow
// derives the suffix, so the rule lives in one place.
return MGITest::PipeStatsWindow::LibraryLogPath();
}
std::string ReadWholeFile(const std::string& path) {
@@ -25,10 +25,12 @@
// half of that control is TheDirectApplierResetCallOnTheGLThreadIsRoleViolation below, and
// the guard's two non-Fatal arms are pinned in PipeWireCodecTest's CtWireFatals suite.
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/ScenarioFixture.h"
#include "../Harness/SplitRuntimePeek.h"
#include <MG_Pipe/PipeApply.h>
#include <Config.h> // `t6`: the spawn arm cannot observe the server process's counters
#include <MG_Remote/Server/ServerSession.h>
#if !defined(_WIN32)
@@ -53,6 +55,26 @@ namespace {
return MobileGL::MG_Remote::Server::ServerSessionInstance().Applier().Verbs();
}
// P6 `t6`: THE COUNTERS BELOW LIVE IN THE SERVER'S PROCESS, and under spawn that is not
// this one.
//
// ServerVerbs() reads PipeApplier's in-process tallies. Under inproc the applier is a thread
// here and the numbers are this process's own; under spawn it is a thread in a DIFFERENT
// process and this process's copy stays 0 forever - so these cases would fail asserting a
// fact about somebody else's memory, which is a harness limit and not a product defect.
//
// SKIPPED BY NAME RATHER THAN EXCLUDED FROM THE LANE. Exit gate 9.2 asks that
// integration-spawn's case-name SET equal integration-split's, and a case dropped from the
// registration would make the two sets differ silently - the exact drift the shared
// registration macro exists to prevent. A skip keeps the name, states the reason, and is
// counted as a skip rather than as coverage.
//
// WHAT WOULD RETIRE IT: cross-process telemetry, which is also what `t6`'s S8 needs for
// SessionFaultCount() over a whole run. Until that exists this is the honest answer.
bool ServerCountersAreObservableHere() {
return MobileGL::MG_Config::Transport != MobileGL::MG_Config::TransportMode::Spawn;
}
class CtWireScenario : public ScenarioTest {
protected:
void SetUp() override {
@@ -94,6 +116,12 @@ namespace {
TEST_F(CtWireScenario, ApplierResetCrossesAtThePrimedEdgeInSerialOrder) {
if (!Ready()) return;
if (!ServerCountersAreObservableHere()) {
GTEST_SKIP() << "transport=spawn: the applier's counters are in the SERVER's process "
"and this one's copy is 0 by construction. The record still crosses - "
"the retrace lane is what proves that - but this case asserts on a "
"tally only an in-process applier can publish.";
}
// The first verb of the process primes the tracker; the edge is the producer. The
// clear also gives the case its pixels, so a lane that emitted nothing is red twice
// (here and in the fixture's emit-ordinal rule).
@@ -141,6 +169,11 @@ namespace {
// The object dies unbound so the destructor - and the death record - fire at the
// delete, and the tally is read AFTER the EmitAndWait the delete blocked on.
glBindTexture(GL_TEXTURE_2D, 0);
if (!ServerCountersAreObservableHere()) {
GTEST_SKIP() << "transport=spawn: ObjectDeaths is the SERVER process's tally and this "
"process's copy never moves. The death record itself crosses; what "
"cannot cross today is the counter that would prove it here.";
}
const MobileGL::Uint64 deathsBefore = ServerVerbs().ObjectDeaths();
glDeleteTextures(1, &texture);
// THE FENCE, the framebuffer case's exactly (MOBILEGL_IPC_BATCH_WAITS, default on):
@@ -197,6 +230,11 @@ namespace {
// Die unbound, framebuffer first so the attachment's own death is a separate record.
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
if (!ServerCountersAreObservableHere()) {
GTEST_SKIP() << "transport=spawn: ObjectDeaths is the SERVER process's tally and this "
"process's copy never moves. The death record itself crosses; what "
"cannot cross today is the counter that would prove it here.";
}
const MobileGL::Uint64 deathsBefore = ServerVerbs().ObjectDeaths();
glDeleteFramebuffers(1, &fbo);
// THE FENCE (MOBILEGL_IPC_BATCH_WAITS, default on): object_death is a kCtxObject
@@ -255,7 +293,10 @@ namespace {
// same); the NAME is asserted from the log below, which the child truncated and
// wrote before it died.
EXPECT_EXIT(MobileGL::MG_Pipe::MGPipeApplierReset(), ::testing::KilledBySignal(SIGABRT), ".*");
if (const char* logPath = std::getenv("MOBILEGL_LOG_FILE_PATH"); logPath != nullptr) {
// THE CLIENT'S LOG: MGPipeApplierReset is called here, on the GL thread, so the guard's
// line is written under the client role. P6 splits the lane's log per role and the
// suffix rule lives in PipeStatsWindow.
if (const std::string logPath = MGITest::PipeStatsWindow::LibraryLogPath(); !logPath.empty()) {
std::ifstream in(logPath, std::ios::binary);
std::ostringstream log;
log << in.rdbuf();
@@ -11,7 +11,7 @@
// proves nothing if no case can tell one block from two, so this scenario asserts exactly that,
// from inside the process:
//
// 1. MGPipeRoleSplitActive() - the knob is armed AND the transport is real;
// 1. MGPipeRoleSplitRehearsalActive() - the knob is armed AND the transport is real;
// 2. &MGPipeClientInputs() != &gPipeInputs - two distinct objects;
// 3. a client verb boundary moves the CLIENT block's serial and leaves the SERVER block's
// serial alone - the fill side's writes no longer reach the read side.
@@ -61,7 +61,7 @@ TEST_F(DualBlockScenario, TheTwoRolesHaveDistinctBlocks) {
<< "the dual-block peek is compiled out: this entry is only ever registered in a "
"disaggregated build, so a false here means the registration and the build disagree";
ASSERT_TRUE(before.roleSplitActive)
<< "dual-block control: MGPipeRoleSplitActive() is false - MOBILEGL_IPC_ROLE_SPLIT_STATE "
<< "dual-block control: MGPipeRoleSplitRehearsalActive() is false - MOBILEGL_IPC_ROLE_SPLIT_STATE "
"is not armed in this process (or the transport is monolith), so the two roles share "
"one PipeInputs block and this case is the knob's negative control";
EXPECT_TRUE(before.blocksDistinct)
@@ -57,6 +57,7 @@
#include <iterator>
#include <string>
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
@@ -105,29 +106,28 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
protected:
// The library log this process is writing, or an empty path when none was configured.
static std::filesystem::path LibraryLogPath() {
const char* path = std::getenv("MOBILEGL_LOG_FILE_PATH");
return (path != nullptr && *path != '\0') ? std::filesystem::path(path)
: std::filesystem::path();
// P6: the path is a BASE NAME and the library writes one log per role; PipeStatsWindow
// derives the suffix, so the rule lives in one place.
return std::filesystem::path(MGITest::PipeStatsWindow::LibraryLogPath());
}
static std::uintmax_t LibraryLogSize() {
std::error_code ec;
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return 0;
const std::uintmax_t size = std::filesystem::file_size(path, ec);
return ec ? 0 : size;
// ONE MARK PER ROLE. The library writes a log per role, so "how long is the log
// right now" is two numbers; a single scalar applied to the concatenation would slide
// by whatever the other role wrote in between and start the read mid-line.
static MGITest::PipeStatsWindow::LogMark LibraryLogMark() {
return MGITest::PipeStatsWindow::MarkLaneLog();
}
static std::string LibraryLogSince(std::uintmax_t offset) {
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return {};
std::ifstream file(path, std::ios::binary);
if (!file.good()) return {};
file.seekg(static_cast<std::streamoff>(offset));
return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
// BOTH ROLES. The arming diagnostics this case looks for are emitted by the
// BACKEND, and under inproc the backend runs on the apply thread - the server role -
// so the line lands in the server's log. Reading only the client's found nothing and
// reported the emulation unarmed, which accused the product of a defect the reader
// had invented.
static std::string LibraryLogSince(const MGITest::PipeStatsWindow::LogMark& mark) {
return MGITest::PipeStatsWindow::ReadLaneLogSince(mark);
}
static std::string LibraryLog() { return LibraryLogSince(0); }
static std::string LibraryLog() { return MGITest::PipeStatsWindow::ReadLaneLog(); }
// One frame that crosses several verb boundaries: a clear (kClear), a draw (kDraw) and
// a readback (kReadback). Three of the nine fill classes, so an entry compare that only
@@ -200,7 +200,7 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
"backwards; the VerifyCorrupted. lane owns that half";
}
const std::uintmax_t before = LibraryLogSize();
const MGITest::PipeStatsWindow::LogMark before = LibraryLogMark();
ASSERT_NO_FATAL_FAILURE(DrawOneFrame());
EXPECT_EQ(FirstGLError(), 0u);
@@ -251,7 +251,7 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
}
const std::string knob = std::getenv("MOBILEGL_PIPE_VERIFY_CORRUPT");
const std::uintmax_t before = LibraryLogSize();
const MGITest::PipeStatsWindow::LogMark before = LibraryLogMark();
ASSERT_NO_FATAL_FAILURE(DrawOneFrame());
const std::string appended = LibraryLogSince(before);
@@ -37,6 +37,7 @@
#include <utility>
#include <vector>
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
@@ -305,27 +306,25 @@ void main()
// is appended to by every process in the lane, and only bytes appended after the
// snapshot may satisfy an assertion.
static std::filesystem::path LibraryLogPath() {
const char* path = std::getenv("MOBILEGL_LOG_FILE_PATH");
return (path != nullptr && *path != '\0') ? std::filesystem::path(path)
: std::filesystem::path();
// P6: the path is a BASE NAME and the library writes one log per role; PipeStatsWindow
// derives the suffix, so the rule lives in one place.
return std::filesystem::path(MGITest::PipeStatsWindow::LibraryLogPath());
}
static std::uintmax_t LibraryLogSize() {
std::error_code ec;
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return 0;
const std::uintmax_t size = std::filesystem::file_size(path, ec);
return ec ? 0 : size;
// ONE MARK PER ROLE. The library writes a log per role, so "how long is the log
// right now" is two numbers; a single scalar applied to the concatenation would slide
// by whatever the other role wrote in between and start the read mid-line.
static MGITest::PipeStatsWindow::LogMark LibraryLogMark() {
return MGITest::PipeStatsWindow::MarkLaneLog();
}
static std::string LibraryLogSince(std::uintmax_t offset) {
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return {};
std::ifstream file(path, std::ios::binary);
if (!file.good()) return {};
file.seekg(static_cast<std::streamoff>(offset));
return std::string((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// BOTH ROLES. The arming diagnostics this case looks for are emitted by the
// BACKEND, and under inproc the backend runs on the apply thread - the server role -
// so the line lands in the server's log. Reading only the client's found nothing and
// reported the emulation unarmed, which accused the product of a defect the reader
// had invented.
static std::string LibraryLogSince(const MGITest::PipeStatsWindow::LogMark& mark) {
return MGITest::PipeStatsWindow::ReadLaneLogSince(mark);
}
std::string m_buildLog;
@@ -493,7 +492,7 @@ void main()
// Taken BEFORE the program is built, so the line this looks for can only be one
// this process wrote.
const std::uintmax_t before = LibraryLogSize();
const MGITest::PipeStatsWindow::LogMark before = LibraryLogMark();
const GLuint program = BuildCaptureProgram({{GL_VERTEX_SHADER, kPointVertexSource},
{GL_GEOMETRY_SHADER, kPointGeometrySource},
@@ -54,6 +54,7 @@
#include <string>
#include <vector>
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
@@ -109,9 +110,9 @@ void main() { o_color = vec4(0.25, 0.5, 0.75, 1.0); }
}
std::filesystem::path LibraryLogPath() {
const char* path = std::getenv("MOBILEGL_LOG_FILE_PATH");
return (path != nullptr && *path != '\0') ? std::filesystem::path(path)
: std::filesystem::path();
// P6: the path is a BASE NAME and the library writes one log per role; PipeStatsWindow
// derives the suffix, so the rule lives in one place.
return std::filesystem::path(MGITest::PipeStatsWindow::LibraryLogPath());
}
// Where the child is told to write ITS log. Empty when the lane configured no log path at
@@ -44,6 +44,7 @@
#include <utility>
#include <vector>
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
@@ -250,27 +251,25 @@ void main() {
const std::string& BuildLog() const { return m_buildLog; }
static std::filesystem::path LibraryLogPath() {
const char* path = std::getenv("MOBILEGL_LOG_FILE_PATH");
return (path != nullptr && *path != '\0') ? std::filesystem::path(path)
: std::filesystem::path();
// P6: the path is a BASE NAME and the library writes one log per role; PipeStatsWindow
// derives the suffix, so the rule lives in one place.
return std::filesystem::path(MGITest::PipeStatsWindow::LibraryLogPath());
}
static std::uintmax_t LibraryLogSize() {
std::error_code ec;
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return 0;
const std::uintmax_t size = std::filesystem::file_size(path, ec);
return ec ? 0 : size;
// ONE MARK PER ROLE. The library writes a log per role, so "how long is the log
// right now" is two numbers; a single scalar applied to the concatenation would slide
// by whatever the other role wrote in between and start the read mid-line.
static MGITest::PipeStatsWindow::LogMark LibraryLogMark() {
return MGITest::PipeStatsWindow::MarkLaneLog();
}
static std::string LibraryLogSince(std::uintmax_t offset) {
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return {};
std::ifstream file(path, std::ios::binary);
if (!file.good()) return {};
file.seekg(static_cast<std::streamoff>(offset));
return std::string((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// BOTH ROLES. The arming diagnostics this case looks for are emitted by the
// BACKEND, and under inproc the backend runs on the apply thread - the server role -
// so the line lands in the server's log. Reading only the client's found nothing and
// reported the emulation unarmed, which accused the product of a defect the reader
// had invented.
static std::string LibraryLogSince(const MGITest::PipeStatsWindow::LogMark& mark) {
return MGITest::PipeStatsWindow::ReadLaneLogSince(mark);
}
GLuint m_vao = 0;
@@ -535,7 +534,7 @@ void main() {
// Taken BEFORE the draw, so the line this looks for can only be one this
// process wrote for this span. The latch fires on the FIRST rerouted
// draw, which is inside the query below.
const std::uintmax_t before = LibraryLogSize();
const MGITest::PipeStatsWindow::LogMark before = LibraryLogMark();
const GLuint generated = QueryGenerated([]() { glDrawArrays(GL_TRIANGLES, 0, 3); });
EXPECT_EQ(DrainGLErrors(), 0u);
EXPECT_EQ(generated, 1u) << "the pinned-on lane did not even count correctly";
@@ -49,6 +49,7 @@
#include <string>
#include <vector>
#include "../Harness/PipeStatsWindow.h"
#include "../Harness/HeadlessGL.h"
#include "../Harness/ScenarioFixture.h"
@@ -354,31 +355,29 @@ void main()
// configured. MOBILEGL_LOG_FILE_PATH is read at log-init, before anything this
// fixture can reach, so the ctest entry sets it and this only reads it back.
static std::filesystem::path LibraryLogPath() {
const char* path = std::getenv("MOBILEGL_LOG_FILE_PATH");
return (path != nullptr && *path != '\0') ? std::filesystem::path(path)
: std::filesystem::path();
// P6: the path is a BASE NAME and the library writes one log per role; PipeStatsWindow
// derives the suffix, so the rule lives in one place.
return std::filesystem::path(MGITest::PipeStatsWindow::LibraryLogPath());
}
// How many bytes the library log already holds. Everything this fixture asserts on
// is searched from here forward, because the file is APPENDED to by every process
// in the lane and a line left behind by an earlier one would otherwise satisfy the
// assertion without this process having done anything at all.
static std::uintmax_t LibraryLogSize() {
std::error_code ec;
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return 0;
const std::uintmax_t size = std::filesystem::file_size(path, ec);
return ec ? 0 : size;
// ONE MARK PER ROLE. The library writes a log per role, so "how long is the log
// right now" is two numbers; a single scalar applied to the concatenation would slide
// by whatever the other role wrote in between and start the read mid-line.
static MGITest::PipeStatsWindow::LogMark LibraryLogMark() {
return MGITest::PipeStatsWindow::MarkLaneLog();
}
static std::string LibraryLogSince(std::uintmax_t offset) {
const std::filesystem::path path = LibraryLogPath();
if (path.empty()) return {};
std::ifstream file(path, std::ios::binary);
if (!file.good()) return {};
file.seekg(static_cast<std::streamoff>(offset));
return std::string((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// BOTH ROLES. The arming diagnostics this case looks for are emitted by the
// BACKEND, and under inproc the backend runs on the apply thread - the server role -
// so the line lands in the server's log. Reading only the client's found nothing and
// reported the emulation unarmed, which accused the product of a defect the reader
// had invented.
static std::string LibraryLogSince(const MGITest::PipeStatsWindow::LogMark& mark) {
return MGITest::PipeStatsWindow::ReadLaneLogSince(mark);
}
static GLenum FirstGLError() {
@@ -499,7 +498,7 @@ void main()
// Taken BEFORE the program is built, so the line this looks for can only be one
// this process wrote. The latch means it is emitted at the FIRST stage of the
// FIRST affected program, which is inside the build below.
const std::uintmax_t before = LibraryLogSize();
const MGITest::PipeStatsWindow::LogMark before = LibraryLogMark();
const GLuint program = BuildPipeline(kDistinctTessEvalSource, kDistinctGeometrySource);
if (program == 0) {
+11 -2
View File
@@ -1350,9 +1350,18 @@ namespace MobileGL::MG_Pipe {
// documented bring-up exception), and a ServerLoop fixture with no client at all has
// none either - there this call is the only reset that exists. Monolith keeps the
// direct call, byte for byte (G1); in a pull build none of this is compiled at all.
// D10: THE MIDDLE CONJUNCT WAS ClientSession::Active() != nullptr ALONE, WHICH IS
// PERMANENTLY NULL IN A SERVER PROCESS - so this guard could not arm at all under
// spawn, in the shape where calling the reset off the apply thread is most likely and
// least recoverable. MGPipeSessionLive() is the same question asked in a way both roles
// can answer, and MGPipeServerArm() is the process-scoped half of "am I the server".
//
// BOTH ARE ADDED AS DISJUNCTS, not substituted. The originals are the only facts a
// fixture without a full session has, and swapping them out silently disarms every such
// test - measured.
if (MG_Config::Transport != MG_Config::TransportMode::Monolith &&
MG_Remote::Client::ClientSession::Active() != nullptr &&
!MG_Remote::Server::ServerLoop::OnApplyThread()) {
(MG_Remote::Client::ClientSession::Active() != nullptr || MG_Pipe::MGPipeSessionLive()) &&
!MG_Remote::Server::ServerLoop::OnApplyThread() && !MG_Pipe::MGPipeServerArm()) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"g_applier\"} - MGPipeApplierReset() called "
"off the apply thread with an active transport; under split the reset "
"crosses as the applier_reset record (CONTRACT-P5C.md §5.1)");
+746
View File
@@ -0,0 +1,746 @@
# CONTRACT-P6 — the backend runs in a second process
Authority: this file, beside `CONTRACT-P5.md` (table 0, byte carriers, field ownership, R-1…R-17),
`CONTRACT-P5B.md` (the class-C slots), `CONTRACT-P5C.md` (rule E, the two named exemptions, SEG_EVENT,
the guards), `CONTRACT-P5E.md` (rule F, the barriered predicate, the wait rule) and
`CONTRACT-MAGMA-RUNAHEAD.md`. Where it disagrees with any of them this file is newer and wins; §10
lists every such place. Base: `feat/disaggregated @ 785fed0b`. Every `file:line` was read at that
commit; paths are under `MobileGL/` unless they start with `docs/`.
**How to change it.** Package `c6`'s file, edited by the integrator first. A P6 package
(`lk` / `hs` / `so` / `sm` / `cp` / `dl` / `st` / `t6`) that needs a row changed goes through the
integrator; the packages compile against the rows below from day one.
**What this file is written from.** [`a6-audit-v1.md`](../../docs/Disaggregated/notes/p6/a6-audit-v1.md)
(198 rows, seven items, each adversarially re-resolved) and
[`a6-link-experiment.md`](../../docs/Disaggregated/notes/p6/a6-link-experiment.md) (the 184 symbols).
It supersedes [`P6-CONTRACT-DRAFT.md`](../../docs/Disaggregated/P6-CONTRACT-DRAFT.md), which was
written before its own audit and is **wrong in four places** (§10.1). The re-scoping against the
eventual client-in-a-VM end state is
[`P6-ENDSTATE-REVIEW.md`](../../docs/Disaggregated/P6-ENDSTATE-REVIEW.md); this file takes from it
only what P6 must not preclude, and §11 says what P6 explicitly does not take on.
---
## §0 What c6 is, and the rule above every row
`c6` lands **this file and two headers**. It changes no behaviour, adds no caller, and moves no
byte on any wire. Every rule below that describes an action names the package that implements it.
A rule with no package named is a statement about the tree as it already is.
**Rule G — a role may not name a process-local handle.** Rule E forbade naming the other role's
*memory*; rule G extends it to *identity*. A value whose meaning comes from the owning process's
kernel or loader state — `EGLDisplay`, `EGLSurface`, `EGLContext`, `ANativeWindow*`, any `void*`
window handle, an fd number, a pid, a mapped address — either crosses as a **token** defined in §2,
or does not cross. Descriptors cross only by a mechanism the transport **declares it supports**, and
where the transport declares none they do not cross at all and the bytes are transferred instead;
a transport may not invent a third answer.
> The draft hard-coded `SCM_RIGHTS` inside rule G. That is one transport's implementation of one
> clause, not the rule, and writing it into the rule is what would make the rule wrong the first
> time a transport has no descriptor passing at all.
**Rule H — a value whose meaning comes from the peer's window system never crosses. Permanently.**
Not "until P12". P12 gives the *server* its own display; it does not give the client's window a way
across. §6 is rule H's whole enforcement.
**Rule G's teeth** are §9's arm-proof gate: a spawn lane that silently ran monolith satisfies every
other gate in this file.
---
## §1 The one fact that makes c6 possible: `Spawn` is unreachable today
`ConfigLoader.cpp:339-346` is the only writer of `MG_Config::Transport` for the string `spawn`, and
it writes **`TransportMode::Monolith`** at `:344`, with a log line saying P5 does not implement it.
Two consequences, and the second is why this file can exist without changing behaviour:
1. **`ConfigLoader`'s named refusal cannot falsify itself.** It lands on the same value a server's
resting state would have, so "the child was forced to monolith" and "the parent fell back" are
one state. `sm` fixes this; until then, no lane can prove it ran spawn (§9.5).
2. **Every rule in this file conditioned on `Transport == Spawn` is vacuous in c6's own tree.** It
constrains a state no process can enter. That is how D1 (§3.1) is stated normatively while
changing nothing, and `c6`'s gate pins the vacuity so the `ConfigLoader` change cannot land early.
---
## §2 Table 0 additions
| row | encoding | invalid | consumer | package |
|---|---|---|---|---|
| `DisplayToken` / `SurfaceToken` / `ContextToken` | `Uint64`, minted by the client, dense from 1, never reused in a session. Server keeps token → native handle; it never sees the client's EGL values. `protocol.fbs`'s `display` / `surface` / `context` are already `ulong` and are these. **The client already mints them** (`MG_State/EGLState/Core.h`'s `EncodeHandle`), contrary to `Server/SurfaceControlFrame.h:26-29`, which says inproc bit-casts the handle — that comment is corrected by `cp`. | `0` on any op but `ReleaseCurrent` → `Fatal{ProtocolCorruption}` | the server's surface map | `cp` |
| `SurfaceOpKind::InitCapabilities = 11` | **Appended.** The draft claimed `ServerInitCapabilities` needs no wire form because "`CapsSnapshot` answers it". The *answer* is a `CapsSnapshot`; the **request** has a live client caller (`Client/BackendObject_Remote.cpp:126`) and the codec **refuses to encode it** (`Protocol/SurfaceOpCodec.cpp:119-122`, `InprocOnlyOpOnTheWire`). A spawn client cannot ask. | unknown tag → `Fatal{ProtocolCorruption}`, never ignored | the server's control pump | `cp` |
| `SurfaceReply.result: int` | **Appended, id 5.** Carries the `MobileGLResult` that `ServerApplyWireSurfaceOp` already computes and drops. Without it a client cannot tell a server that died mid-op from a legitimate refusal, and therefore cannot choose between arming the device-lost latch and returning `EGL_FALSE`. | — | the client's control demultiplexer | `hs` |
| `SurfaceReply.defaultFb` | **`(deprecated)`.** The encoder passes a literal `0` offset (`SurfaceOpCodec.cpp:184`) and the decoder never reads it; `kEventSurfaceChanged` is the landed carrier (P5f `fc`). The slot is **burned, never deleted** — a deleted field frees its vtable slot for the next append. | — | nobody, by construction | `hs` |
> **asio was considered for the byte stream and declined (2026-09-21).** It is already vendored
> and on the include path, so the question is a fair one. But spawn needs five platform
> mechanisms and asio covers one: its own `socketpair` returns `operation_not_supported` on
> Windows (`3rdparty/asio/include/asio/detail/impl/socket_ops.ipp:683`), it has no descriptor
> passing at all, segment delivery is POSIX-only by design, and there is no `fork`. So adopting
> it would not make Windows work; it would only put asio headers inside `Transport/`, which
> `ITransport.h` keeps dependency-light on purpose. **Revisit at P6.5**, where
> `asio::generic::stream_protocol` carries a raw (family, type, protocol) triple and therefore
> gives AF_VSOCK from the same implementation (2026-09-22: the end state's link is TCP, not
> AF_VSOCK - §10.3 - and the argument is the same for `asio::ip::tcp`) - and where `ITransport` lets an `AsioTransport`
> land beside `SocketTransport` without touching a caller.
| `LinkTerms{dataPlane, wireForm, maxReplyBytes, cmdWindowBytes, stageWindowBytes}` | Appended to `Hello`/`Welcome`. `dataPlane` has exactly **one** legal value in P6, `SharedSegments`; `wireForm` exactly one, `StructImage`. Anything else is refused **by name**. The four sizes are **stated by the SERVER**. | any other value → `Refuse{ProtocolMismatch}` | the handshake | `hs` → **not landed** (verified 2026-09-22: `protocol.fbs` has no `LinkTerms`); re-homed to P6.5 `nd`, §10.3 |
| `Refuse{code, detail, peer values}` | Appended `CtrlMsg` union tag. A handshake disagreement is an **answer**, not an abort (§5.1). | — | both sides | `hs` → **not landed** (no `Refuse` in `union CtrlMsg`); re-homed to P6.5 `wf`, §10.3 |
| `wireFingerprint` / `buildFingerprint` | The single `abiFingerprint` splits. §4. | mismatch → `Refuse`, never `Fatal` | the handshake | `hs` → **partially landed** (explicit build stamp, `abiMajor`/`abiMinor` checked, real pids; the split itself and the `PipeFields.def` layout digest are not); re-homed to P6.5 `wf`, §10.3 |
| `FatalCode` | **Unchanged**, 7 values (`protocol.fbs:248-256`). `table Fatal` appends `family: string`. §5.2. | — | — | `dl` |
All schema edits are **append-only**. A FlatBuffers table field's id is its vtable slot and an enum
value **is** the wire value; retired fields become `(deprecated)`, never disappear. `CapsSnapshot`'s
four deprecated fields are the worked precedent and their reasoning is in `protocol.fbs` itself.
> **`hs` implementation note, from c6's review.** `flatc` drops deprecated fields from the generated
> `Create*` helper. Deprecating `defaultFb` while appending `result` therefore changes
> `CreateSurfaceReply`'s arity, and the existing 6-argument call at `SurfaceOpCodec.cpp:183-184`
> would **silently bind its `/*defaultFb=*/0` to `result`**. `hs` converts that call site to
> `SurfaceReplyBuilder` with explicit `add_*` in the same commit, so a positional mistake is
> impossible rather than merely unlikely.
---
## §3 Role, Dial, and the six predicates
### 3.1 D1 — what `Transport` reads as in the server process
**`TransportMode::Spawn`. The child does not force `Monolith`.**
`ARCHITECTURE.md:488`'s literal instruction ("`mobilegl_server_main` hard-sets `MG_Config::Transport`
to `Monolith` before reaching `Init()`") is **amended by this file**. a6 measured why: 226 live lines
test `Transport != Monolith` to select the **server** arm, 148 of them in `MG_Backend`. Forcing
`Monolith` flips all of them to frontend glue in the one process with no frontend. The sharpest
instance is `PipeInputs::IsLive()` (`MG_Impl/Pipe/PipeFill.cpp:2135`): forced monolith, it reads
`MG_State::pGLContext`, which is null there, so **58 `MGB_CTX_LIVE` guards all answer "not live"**.
Anti-recursion moves to a **separate, non-inherited axis**: `MG_Config::Dial == DialMode::No` in the
child. The envp scrub stays as the second, independent catch, and S3 (§9) still falsifies it —
and the diagnostic must **name which of the two fired**, or the double safety is untestable as two
things. Package: `sm`.
### 3.2 D1c — there are six predicates, not three
a6 proposed three. Three do not cover the tree.
| predicate | asks | pull-build shape |
|---|---|---|
| `MGPipeSplitActive()` | do records cross a role boundary at all | `#else` returns `false` |
| `MGPipeServerArm()` | am I executing as the server **right now** | `#else` returns `false` |
| `MGPipeShouldDial()` | should this process connect out | `#else` returns `false` |
| `MGPipeSessionLive()` | is a peer session live | role-defined; `#else` `false` |
| `MGPipeBlocksAreDistinct()` | do the two roles share one storage object | `#else` `false` |
| `MGPipeBackendIsLocal()` | is the backend in **this** process | `#else` `true` |
`ContextEpoch::Server` and `ActiveXfbState`'s role index are **`MGPipeSplitActive()`** sites, not
`MGPipeServerArm()` sites: they are partition keys, and the `ServerArm` disjunct would make a
partition key thread-dependent.
**D14 — all six must fold away in the pull build**, and the required shape is `SlotCaps.h`'s: the
non-disaggregated build gets a **different definition** under `#else`, not a runtime-false predicate.
`MGPipeSplitActive()` must additionally remain exactly one load of a process global and must never
be latched into a `static Bool`. G1 is 0/0/0/0 and `.text` unchanged; anything else is a c6 defect.
Package: `sm`.
### 3.3 D13 — rename before introducing
`MGPipeRoleSplitActive()` (`MG_Backend/MGPipe/PipeInputs.cpp:292`) means
`Ipc.RoleSplitState && Transport != Monolith` — the **rehearsal knob**, default off. It is renamed
to **`MGPipeRoleSplitRehearsalActive()`**, which is what it has always meant, and
`MGPipeBlocksAreDistinct()` is introduced beside it as the wider predicate. a6's shape — rename, then
widen the same function — is **overturned**: a widened function under a narrow name is a name that lies.
Blast radius, measured at this head: **12 sites**, of which `DualBlockScenario.cpp`'s assertion
*message* embeds the old name and must be updated with it. Package: `sm`.
### 3.4 D10 — the four guards that cannot arm in a server-only process
| guard | today | becomes | package |
|---|---|---|---|
| `MGPipeApplierReset` layer 2 (`MG_Pipe/PipeApply.cpp:1353-1355`) | needs `ClientSession::Active() != nullptr`, permanently null in a server process | middle conjunct → `MGPipeSessionLive()`; third → `!MGPipeServerArm()` | `sm` |
| `MGPipeServerBlockNoteIdentity` (`PipeInputs.cpp:314`) | early-returns unless the rehearsal knob is on | gate → `MGPipeBlocksAreDistinct()` | `sm` |
| `CountBarrierPull`'s unconditional Fatal arm (`PipeInputs.cpp:174`) | knob-gated | rides `MGPipeBlocksAreDistinct()` | `sm` |
| the two `RefuseFromApplyThread` helpers (`MG_Impl/Pipe/SlotAllocator.cpp:29-57`) | `ServerLoop::OnApplyThread()` | OR'd with a process-role fact set once by `ServerMain` | `sm` |
**The one that crashes rather than merely failing to arm.** With `MGPipeServerBlockNoteIdentity`
early-returning, a spawn server's `gPipeInputs.ContextIdentity()` stays `nullptr` for the life of the
process, and `DirectGLES.cpp:199-213`'s fb-slot memo does a **raw pointer compare with no generation**
against it — so `nullptr == nullptr` reads as a **cache hit** and the first call uses an
uninitialised slot. `PipeInputs.h:878-884`'s own comment says a named Fatal was intended there.
`sm` lands the gate change; `st` lands the named Fatal.
---
## §4 The handshake (`hs`)
### 4.1 One equality test answers three different questions today
`AbiFingerprintInputs` (`Transport/SessionRings.h:544-566`) mixes wire properties, struct-layout
properties and pure build identity into one `Uint64`. It splits:
**`wireFingerprint` — always compared.** Inputs, in order:
an ordered **catalogue digest** over `PipeCalls.def`'s `(opcode, payload struct name, call-flag row,
WaitClass)`; a **payload layout digest** derived from `PipeFields.def` (per member: name, `offsetof`,
`sizeof`); the record-header layout; both blob-codec version stamps; the format-capability table's
two extents; `kOpCount`; `MOBILEGL_ABI_VERSION`; endianness; pointer width; **and**
`sizeof(MGPCaps)` and `sizeof(DynamicBackendParameters)`.
Those last two **stay compared** because they are wire facts, not build facts: `MGPWireRec_GetCaps`
is composed from `sizeof(MGPCaps)` (`MG_Pipe/generated/PipeWire.inc`). `sizeof(GLFunctionsTable)` is
**deleted** from the mix: it never crosses the wire, so adding one backend slot today invalidates
every peer for no wire reason.
> **Why the layout digest is not optional.** `SessionRings.h:561-565`'s own comment says the git
> stamp is in the mix because *two builds of the same sizes can still disagree about a FIELD ORDER,
> which no sizeof can see*. A catalogue digest over `(opcode, struct name, flags, WaitClass)` sees
> neither a member reorder inside a payload struct nor a width change. So the widely-proposed "drop
> the git stamp, add a catalogue hash" is **wrong as usually stated** — it removes a guard and does
> not replace it. The layout digest is the replacement, and `gen_pipe.py` already CI-enforces that
> `PipeFields.def` names every member, so it is a generator addition and not a toolchain.
**`buildFingerprint` — compared only while `Dial == Fork`.** Under fork the child *is* the same
binary, so comparing it catches a stale `MOBILEGL_IPC_SERVER_PATH` pointing at an old
`libMobileGLServer.so` — a real P6 failure mode. **P6's policy is therefore strictly stronger than
today's, not looser**; the end state is a policy flip, not a redesign.
### 4.2 The missing build stamp
a6 found `CMakeLists.txt:188-195` takes the git hash with **no `RESULT_VARIABLE` and no fallback**, so
a failed `git rev-parse` silently yields `""`. Verified live: building this worktree from WSL
produces `GIT_COMMIT_HASH_SHORT ""`, because the worktree's `.git` file holds a Windows path WSL's
git cannot resolve. Two builds from different commits then get **identical** fingerprints and the
stamp silently stops doing its documented job.
**The fix may not touch `GIT_COMMIT_HASH_SHORT`.** That macro is baked into
`glGetString(GL_VERSION)` (`MG_Impl/GLImpl/Getter/GL_Getter.cpp:614`), so redefining it changes an
**application-visible GL string** and the pull build's `.rodata` — a behaviour leak and a G1 break
at once. Instead `MGGitHash.h.in` gains a **second** pair, `MOBILEGL_BUILD_STAMP_VALUE` and
`MOBILEGL_BUILD_STAMP_PRESENT`, consumed only by the fingerprint, and the CMake step gains a
`RESULT_VARIABLE`. A build with no stamp sets `PRESENT` to 0, and a `Dial == Fork` handshake whose
peer reports `PRESENT == 0` is a **named refusal**: under fork the two peers are supposed to be the
same binary, and without a stamp that premise cannot be checked at all. Package: `hs`.
### 4.3 Two verified asymmetries `hs` also fixes
- The client checks only `abiFingerprint` and **never `abiMajor`/`abiMinor`** (`ClientSession.cpp:566-568`).
- `Hello::pid` is hard-coded `0` and `Welcome::serverPid` echoes the client's, so it is always 0
(`ClientSession.cpp:519-521`, `ServerSession.cpp:532-534`). §9.5's arm-proof gate wants the child
pid; `serverPid` is its natural carrier and must start carrying it.
### 4.4 Segment geometry (D-size)
`MOBILEGL_IPC_RING_MB` / `STAGE_MB` are read from the **client** process's env with ceilings of
1024 / 4096 MiB (`ConfigLoader.cpp:363-364`), while the **server** creates the segments. Under spawn
that is a guest environment variable sizing an allocation inside the renderer process. The four sizes
become **server-stated** `LinkTerms` fields; the client's values become a *request* the server may
clamp, and the clamped values are reported in `Welcome`.
`ShmSegment::Adopt`'s `fstat` "do not trust the peer's declared size" check
(`Transport/ShmSegmentPosix.cpp:127-133`) is today the **only** bound, and it has no analogue on a
link with no fd. The compile-time ceiling that refuses an oversized announcement by name is
**P6.5's** to define; P6 does not pretend to have answered it.
---
## §5 Death, refusal, and what P5e changed
### 5.1 The handshake never aborts
A version or terms disagreement is a `Refuse{code, detail, peer values}` control message plus
`MOBILEGL_ERR_PROTOCOL_MISMATCH` on **both** sides: the server sends `Refuse` and exits 0, the client
reaps the child and refuses **by name**, never falling back to monolith. Both `FatalAbiMismatch` call
sites go (`ServerSession.cpp:471-483`, `ClientSession.cpp:565-568`). The worked shape is eight lines
away in the same function: `ServerSession.cpp:456-466` already returns
`MOBILEGL_ERR_PROTOCOL_MISMATCH` for a malformed frame, with the correct `msg_as_Hello() != nullptr`
guard. Package: `hs`.
### 5.2 `Fatal{}` keeps aborting in P6, and gains one funnel
a6 censused **92 abort sites** under `MG_Remote/` carrying **30 distinct family words**, against a
**7-value** wire `FatalCode`. So `Session::Fail(FatalCode, detail)` as usually proposed **cannot carry
today's vocabulary in its first argument**.
**D2 ruling.** The first argument is an internal `MGFatalFamily`, generated from a new
`MG_Remote/FatalFamilies.def` — one row per family word, each row carrying its `FatalCode`
projection. The **wire** keeps `FatalCode` unchanged; `table Fatal` appends `family: string`. The
projection is a **total table**, not a switch with a `default:` arm — this build has **no `-Werror`
anywhere** (verified: `CMakeLists.txt`, every `*.cmake`, both workflows), so a gate premised on
`-Wswitch` failing the build is fiction.
`Session::Fail` stays `[[noreturn]]` in P6 and still ends in `abort()`. Log lines, CI greps and every
red-once are byte-identical. What the funnel buys, and what makes it worth `dl`'s two days:
- **one** place that publishes a `SessionFault{family, detail, seq, op}` frame to the peer **before**
dying, so the guest's log names which record killed the session instead of reading a bare EOF;
- one telemetry point;
- a CI census gate refusing any **new** bare abort outside the funnel.
> **LANDED, in three steps.** (1) `FatalFamilies.def` + `FatalFamily.h` generate `MGFatalFamily`,
> its total projection `FatalCodeForFamily` and `FatalFamilyName`; 32 rows, tested. (2) `SessionFail`
> (`FatalFunnel.{h,cpp}`) is the funnel: the ~90 scattered `MGLOG_F("...Fatal{...}"); abort();` pairs
> under `MG_Remote/` become one call each, the message string passed **verbatim** so every line and
> grep is byte-identical, the family enum riding alongside for the coarse code. `SessionFaultCount()`
> is the telemetry point. The census now also requires every `SessionFail`/`WireLogFatal` call's
> string to carry a `Fatal{` word, and its baseline drops from 93 bare aborts to 4 (both funnels).
> (3) `table Fatal` gains `family: string`; `SessionFail` publishes the frame on whichever session
> control plane is active before aborting, and the client's control-reply loop recognizes it, names
> the family and latches device-lost. **seq/op are NOT threaded** through the 90 sites — the message
> already names the op — so the frame carries `code`, `family` and `message`, not a field always 0.
> A `kill -9` bypasses `abort()` and is caught by `dl`'s hangup witness instead; the self-detected
> fatal is the one that publishes.
**The policy flip is not P6's.** Making `Fail` return needs a real return path invented at every site
whose callers rely on `[[noreturn]]`, and a6 counted how many do. That is `Ph`'s (§11).
Two sites carry **no `Fatal{` marker at all** (`Client/PersistentMapTracker.cpp:1052-1058`,
`Transport/WireLog.cpp:41-50`), so "the log stays verbatim" is not true of them and the family grep
cannot see them. `dl` gives each a family tag.
### 5.3 The device-lost latch does not exist, and P6 writes it
`P6-CONTRACT-DRAFT §5.1` says the latch "is implemented unchanged". It is not implemented at all:
`FatalCode::DeviceLost`/`ServerCrashed` have zero producers and zero consumers,
`glGetGraphicsResetStatus` returns `GL_NO_ERROR` unconditionally
(`MG_Impl/GLImpl/Getter/GL_Getter.cpp:2855-2861`), and `MOBILEGL_IPC_RESPAWN` / `IDLE_EXIT_S` are
parsed **nowhere** (only a comment at `Config.h:466`). Today a dead server leaves the client
silently `DECLINE`-ing every verb forever with `glGetError` clean.
**It is a package (`dl`), not carriage.** The latch is session-scoped and set from
`Doorbell::PeerHungUp()` — D5c amends "`Dead()`" here, and §5.4's block says why — **never from a
timeout**. `MOBILEGL_IPC_RESPAWN=1` is a named refusal until some stage implements the re-push.
**LANDED.** `ClientSession::DeviceLost()` / `LatchDeviceLost()`, armed at the verb barrier, at the
forced run-ahead wait and at the control-reply wait, and read by `GetGraphicsResetStatus`, which
now answers **`GL_UNKNOWN_CONTEXT_RESET`**. Not `GUILTY` or `INNOCENT`: those assign blame, and the
server died for a reason that never crossed the wire — it could as easily have been a driver fault
as this client's draw. The consult and its include sit wholly inside `MOBILEGL_BUILD_DISAGGREGATED`;
G1 re-measured after it, **0 symbol diff and `.text` unchanged at `0xa52203`**. That measurement
also caught an unrelated 16-byte drift the guards did not: P6's O_APPEND log-sink fix was compiled
into the pull build too, and is now guarded for the same reason.
### 5.4 Slow, dead, and frozen are three states
- A published, never-applied record is **discarded at the latch, not waited on**.
- **Slow and dead are distinguished without a timeout threshold.** A server one frame behind is
P5e's intended steady state; a server that is gone is `Fatal{ServerCrashed}`. `SocketDoorbell`
already latches `m_dead` on EOF — take the fact from there.
- **A frozen peer produces no hangup**, and a6 found the tree has no defence: the control-reply wait
`m_controlDone.wait(lock, pred)` (`Server/ServerLoop.cpp:724`) has **no deadline**, while the ring
side has `kBarrierTimeoutMs`. A SIGSTOP'd or freezer'd server wedges the GL thread inside
`eglMakeCurrent` with no diagnostic.
**D5 ruling — two waits, two answers.** (a) The server's *in-process* mailbox wait gains a bound and
its expiry is `Fatal{ControlReplyTimeout, "<op>@<seq>"}`. (b) The client's *cross-process* reply wait
is bounded by `MOBILEGL_IPC_CONTROL_TIMEOUT_MS` (default 5000) and its expiry is **not** fatal: the
client consults the doorbell's death latch — dead latches device-lost, alive-but-silent is a named
diagnostic. Packages: `cp` (a), `dl` (b).
> **D5c — the client's self-bell CANNOT witness the server's death, and `sm` is why.** Measured, not
> predicted: `minecraft-1.21.4-fabric-iris-iterationrp-in-world` kills the *server* process outright
> on this machine (llvmpipe: `LLVM ERROR: Cannot select: intrinsic %llvm.x86.vcvtps2ph.256`, SIGABRT
> at call 159429), and the client did **not** take the `SessionWait::ShutDown` path that already
> exists and is already correct. It sat out the full 120 s and reported
> `Fatal{BarrierTimeout, "ResourceRespecify"}` — the wrong diagnosis, at 120 s a case, for a server
> that had been gone since the first second. Under monolith the same trace fails in 3 s.
>
> The cause is structural and is the price of the two-fd bell: the client parks on `clientBell[0]`
> (slot 5) and rings *itself* through `clientBell[1]` (slot 6), so it holds **both ends** of that
> socketpair. EOF arrives only when every writer closes, and the client is one of them — so that
> descriptor can never hang up, no matter what happens to the peer. A bell that can wake itself is
> a bell that cannot hear a death.
>
> **`dl` therefore needs a witness descriptor whose far end only the SERVER holds**, polled beside
> the park fd and never read from, whose `POLLHUP`/EOF latches `Dead()`. The control socket is
> already exactly that and needs no new descriptor. The fix does not belong to `sm`: holding both
> ends is required for self-notification and is not the defect — assuming one descriptor could
> answer both questions is.
>
> **LANDED.** `SocketDoorbell::SetDeathWitness(fd)`; the client hands it
> `SocketTransport::StreamFd()`. The witness enters the poll set with `events = POLLRDHUP` **and
> nothing else**, which is what lets it watch a socket it must never read: `POLLHUP`/`POLLERR`/
> `POLLNVAL` arrive in `revents` unrequested, so the hangup is seen while `POLLIN` never is — a
> control reply queued on that descriptor can neither wake the bell nor be consumed from under
> `SocketTransport`'s reassembler. Measured: `kill -9` on the server is noticed in **0.01 s**
> against a 120 000 ms barrier, and with the witness removed the same test takes the full 2 s
> retry budget and fails naming this paragraph.
>
> **`Dead()` AND `PeerHungUp()` ARE TWO FACTS, and only the second may arm the latch.** `Park`
> sets `m_dead` for `POLLERR`, `POLLNVAL` and unrecognised `revents` as well — each a fault in
> *this* process's descriptor — and `CondVarDoorbell::Kill()` sets it on every orderly `Stop()`.
> A latch taken from `Dead()` would report a lost GPU for a local fd bug and a context reset for
> every clean exit. `ADeadBellIsNotAlwaysAHungUpPeer` is the red-once for the distinction;
> `AnOrderlyStopIsNotADeviceLoss` is **not** — it stays green under the collapse, because under
> spawn the self bell is a `SocketDoorbell` and `Stop()` never kills one. That was found by
> running the falsification rather than by reading the code.
---
## §6 The control plane (`cp`)
### 6.1 What `fc` landed, and what is left
P5f package `fc` framed the twelve `Server*` forwarders as value-only `SurfaceControlFrame`s and
landed the wire codec. The draft concluded `cp` is "transport only". **Three things are not
transport**, and a6 found all three:
1. The `InitCapabilities` **request** has no wire form (§2).
2. `SurfaceReply` cannot carry a `MobileGLResult` (§2).
3. **Neither side of the control plane is wired to a socket.** The apply thread's `ready` predicate
has exactly three terms — stop, `ControlIsPending()`, `cmdHead != LocalTail()` — and a socket is
not among them (`ServerLoop.cpp:398-402`), so a `SurfaceOp` arriving on the wire is read by
**nobody**. The client's pump consumes only `CapsSnapshot` and drops everything else with a WARN
(`ClientSession.cpp:1425-1432`).
### 6.2 D4 — who reads the control socket
A dedicated **`mgl-srv-io` thread**: `ReceiveFrame` → `DecodeWireSurfaceOp` → post into the
**existing** one-slot mailbox as an ordinary non-apply-thread poster. `ServerLoop.cpp:673-727` is not
changed. The io thread is additionally the server's **only** sender on the control transport:
`PublishCapsSnapshot` enqueues and the io thread drains one outbound FIFO — which is what fixes the
ordering hazard that `CapsSnapshot` is pushed from **inside the dispatch, on the apply thread,
mid-op** (`ServerLoop.cpp:959-969`).
Rejected: adding a fourth term to the apply thread's `ready` predicate. That puts frame decode on the
thread holding the native context and makes every control arrival a wake of the applier.
### 6.3 D7 — `seq`
The **client** mints, always, dense from 1, never reused in a session. `seq == 0` arriving on the
wire is `Fatal{ProtocolCorruption, "SurfaceOp.seq"}` at the **decoder**, not at
`RunSurfaceControlFrame`, whose local mint (`ServerLoop.cpp:659-662`) stays and becomes reachable only
for a local, non-wire post. Correlation lives in the client's control demultiplexer;
`DecodeWireSurfaceReply` keeps its void signature and stops being the place correlation was expected.
### 6.4 `ForgetCurrentTuple`
The N-3 rule holds identically on the frame path: the forgetting calls are inside the dispatch
(`ApplySurfaceControlFrame`) and `ServerLoopTest`'s C7/N-3 controls drive them through framed posts
unchanged. No change.
---
## §7 Windows — rule H's enforcement (`cp`)
### 7.1 The blacklist is open, and the end state's first guest walks through it
`WindowBackendForWireWindowKind` (`Protocol/SurfaceOpCodec.cpp:104-113`) **accepts**
`WindowKind::X11 → WindowBackend::X11` and `Win32Hwnd → Win32`. `DecodeWireSurfaceOp` (`:141-179`)
refuses only `AndroidNativeWindow` and `MetalLayer`. An accepted kind's `nativeToken` is copied
through and `UnpackWindowHandle` (`Server/ServerLoop.cpp:875-882`) casts it to `void*`
**unconditionally**, whence it reaches `eglCreateWindowSurface` in the server process.
`DetectWindowBackend()` is a compile-time `#if` chain (`MG_Impl/EGLImpl/EGLImpl.cpp:59-70`), so a
guest cannot avoid announcing its own window system.
### 7.2 D8 — whitelist, and in P6 the accept set for a window op is empty
- `X11` → `Fatal{UnmigratedSurface, "X11@P12"}`; `Win32Hwnd` → `"Win32Hwnd@P12"`.
- `None` on a **window** op → `Fatal{ProtocolCorruption, "SurfaceOp.windowKind"}`. Today it is
accepted, maps to `WindowBackend::Unknown`, and the raw token is copied through anyway.
- Separately and independently: `nativeToken != 0` on **any** op →
`Fatal{ProtocolCorruption, "SurfaceOp.nativeToken"}`.
- `Pbuffer` / `Surfaceless` are surface **shapes**, not window backends, and remain the only things
P6 lands.
**Do not append `WindowKind::ServerOwned` in P6.** The schema is append-only, so an enumerator
appended now and re-meant later is a wire value burned; P6 has no consumer for it. P12 appends it.
### 7.3 The client emits unconditionally, and P6 must decide what that costs
`Client/BackendObject_Remote.cpp:214-216` posts `SetWindowHandle` with no split-arm check, so on a
real Android app the **first `eglCreateWindowSurface` aborts the server process** and the client sees
only a dead peer. `cp` mirrors the refusal on the **client** side, so the diagnostic names the cause
in the process that caused it. This is P6's, not P12's, because P6's device lanes run on a phone.
### 7.4 `m_windowHandle` has four stores, not one
a6's precise shape, correcting the corpus (and `P6-ENDSTATE-REVIEW §2.5`): four stores
(`MG_Backend/BackendObject.cpp:475`, `:365`, `:206`, `:207`), five reads, and `:283` is a **call**,
not a store. `.Width`/`.Height` have **no readers**. The smallest latch point for a server-owned
window is `RegisterEGLWindowSurface` (`:232-238`), and the non-obvious fourth edit is the
`sameHandle` dedup key (`BackendObject_DirectGLES.cpp:962-967`), which under server ownership never
matches and would rebuild the native context on every `eglCreateWindowSurface`. Recorded here for
P12; P6 changes none of it.
---
## §8 The data plane (`lk` implements, `c6` declares)
### 8.1 Why a seam at all
`ITransport.h:16-20` says in its own header that the hot path bypasses it: it is the **control**
plane, and that scope is already correct for a socket. Below it there is **no interface of any kind** —
`Ring.h`, `ReplySlot.h` and `EventRing.h` take raw `void* base + capacity`. So "swap the transport"
has nothing to swap.
`c6` declares `Transport/ILink.h` and `Transport/StreamLink.h`. `lk` implements `ShmLink` by moving
today's `SessionSegments` / `Ring` / `ReplySlotPool` / `EventRing` behind the interface, line for
line, with **zero behaviour change**.
### 8.2 The seam is a setup-time interface, not a hot-path one
`ILink` hands out POD handles **once at attach** and then stays out of the way. No `ILink` virtual is
called per record, per publish, or inside any spin predicate. Three grounds, and the second is
decisive:
1. Two virtuals per record at the 4000 records/frame that `SEG_CMD` is sized against is ~8000
indirect calls/frame — about 0.5% of the measured 15.72 ms client frame. Affordable, but the only
lane that could measure it has ±4% run-to-run dispersion, **eight times the effect**, so the gate
`P6-ENDSTATE-REVIEW` demands could only ever print "within noise" — a green that proves nothing.
2. **The spin predicate forbids it outright.** `Doorbell::Wait` is a non-virtual template whose spin
loop calls `ready()` up to `SpinItersPerUs() * spinUs` times; at 916 waits/frame with 99.8%
resolved inside the spin, the predicate runs 10⁵–10⁶ times per frame and reads the watermarks
straight off the page. That is the 31.58%-of-the-GL-thread path. A virtual there is not a rounding
question.
3. The encode path already depends on four inline accessors around its single `Reserve`, and
virtualising `Reserve` alone would force either four more virtuals or moving R-10's wrap counters
behind the seam — and those are deliberately encoder-owned.
**The gate is therefore an `objdump` call-count of the encode path, not a wall clock**: after `lk` the
path must have no more out-of-line calls than today. That is falsifiable; "within noise" is not.
### 8.3 `RingControl`'s regroup is `lk`'s, and it is a wire break the day a second build exists
The watermark cache line is `{appliedSeq, submittedSeq, retiredSeq, completedFrameSerial,
presentAckSerial}`; `eventRingFull`/`eventDropped` sit in a **separate** `alignas(64)` group with
`serverEpoch`/`ringGeneration`/the two park flags. And `submittedSeq` is **producer-written**
(`Ring.h`'s "THE FIVE WATERMARKS" block) while the other four are consumer-written — so the group has **mixed writers**, and any
"single-writer progress block aliased over the watermark line" is unsound.
`lk` therefore **regroups**: `submittedSeq` moves to the producer's own line, beside `cmdHead`,
which is the other thing the producer writes; what is left — the four consumer-written watermarks —
becomes a named `LinkProgress` member with per-field `offsetof` static_asserts.
> **Correction, found while `lk` was measuring its own blast radius.** An earlier revision of this
> section, and of `ILink.h`, also promoted `eventRingFull`/`eventDropped` into the watermark group
> and called the result single-writer. **Both were wrong.** `eventRingFull` has two writers: the
> server latches it with `store(1)` when `SEG_EVENT` fills (`Transport/EventRing.h:140`) and the
> **client clears it with an `exchange(0)` on every drain** (`:200`). Promoting it would put a
> per-drain RMW by the client on the same cache line as `appliedSeq` — which the server
> release-stores every 64 records and the client's spin predicate reads 10⁵–10⁶ times per frame.
> That is new false sharing on the hottest line in the system, and it would land in exactly the
> numbers this package's gate has to hold constant. The two flags stay in the doorbell/generation
> group, where mixed writers already live beside `consumerParked`/`producerParked`, and cross the
> seam through a separate `EventFlags()` accessor. *Accessor*, not line: they share
> `serverEpoch`'s line, which is where mixed writers already live.
It is free **today** — both peers are the same binary, enforced by the fingerprint — and a wire break
the day a second build exists. It is **`lk`'s and not `c6`'s** because the rename blast radius is
**109 sites in production alone**, not the 39 an earlier draft assumed, and because five of them sit
behind `#if defined(MGITEST_SPLIT_RUNTIME_PEEK) && !defined(__ANDROID__)` — an Android configure
compiles them out, so a missed rename is green on device and red only on a desktop split-peek build.
`lk` publishes the per-file itemisation before it starts.
### 8.4 What `StreamLink` is for
Every method is a named refusal, `Fatal{UnmigratedDataPlane, "StreamLink@P6.5"}`. It exists so the
seam's adequacy is a **compile**, not an argument: if `ILink` cannot name what a byte stream needs,
`StreamLink` cannot be declared against it. Writing it is what revealed that the seam needs
`FlushProgress()`, `ResolveSpan()` and a reply pair — three methods the brief's own list
(progress transmission, send window, flush) did not name.
`c6`'s red-once: delete one `ILink` method `StreamLink` declares and the build goes red.
### 8.5 The purity gate (`lk`)
After `lk`, the identifiers `RingControl`, `RingProducer`, `RingConsumer`, `ReplySlotPool` and
`EventRingConsumer`, and any `m_shm.` expression, appear **only** inside `Transport/ShmLink.*` and
the transport's own tests. Same shape as the existing A/B/C purity gates. The baseline is recomputed
mechanically at `lk`'s head and published per file — the earlier draft's ratchet number was wrong by
a factor of three, and a ratchet installed at the wrong number is red on day one for reasons that
have nothing to do with a leak.
### 8.6 `SEG_STAGE`'s cursors are deliberately dead
`Ring.h`'s "DEAD IN P5, DELIBERATELY" states it and a test pins it: `SEG_STAGE` is **not a ring**; staging is an
encoder-local linear allocator reclaiming on `retiredSeq`, and all three stage cursors stay zero for
the whole of P5. A stream link's send window either revives them **completely** or does not use them;
the header names the middle state as *a guaranteed hang rather than a slow path*. P6.5's, recorded
here so it is not rediscovered.
---
## §9 The gate
Beyond the five-part gate (`docs/Disaggregated/ARCHITECTURE.md` §13.2):
1. **G1** — pull build 0/0/0/0, `.text` unchanged. Every predicate in §3.2 folds away.
2. **G2/G14** — `integration-spawn`'s case-name set identical to `integration-split`'s.
3. `integration-spawn` green at the same count as `integration-split`.
4. **Process tree, mechanical** — exactly one extra child while running, zero after; `HeadlessGL`'s
fork pre-check leaves no orphan.
5. **Arm proof (ID-124)** — every spawn entry records the child pid and `transport=spawn` in its own
private log. A spawn lane that fell back to monolith passes items 1–4. §1 is why this gate is not
optional: today the fallback and the intended state are **the same value**.
6. **Red-once per package (R-16)**, one named pair each.
7. **Device** — Redmi `2f7cbe2e`, reboot-clean, paired A/B in one thermal window.
8. **Performance recorded, not gated**, but three numbers are mandatory: the socket doorbell's cost
against `inproc`'s condvar; `SEG_STAGE` bytes/frame; and records/frame **post-chunking**. The last
two are takeable on the existing inproc lane today and `MEASUREMENTS.md:342` says in as many words
that no post-chunking distribution exists.
> Item 8's wording must be able to **accept a negative regression without looking suspicious**: today
> the client spins ~1600 times/frame on a shared cache line with 99.8% of waits resolved there, and a
> socket link has no such line. Converting that into ~4 blocking reads/frame may be **cheaper**.
Negative controls, each run red once:
| # | knob | what it must falsify | package |
|---|---|---|---|
| S1 | `MOBILEGL_IPC_SERVER_PATH=/nonexistent` | named refusal, not a silent monolith fallback | `sm` |
| S2 | `kill -9` the server mid-frame | the latch; the client never hangs and never keeps submitting. Red-once the **wrong implementation** too: set the latch from a timeout and the paired control "a server one frame behind is the normal state" must go red | `dl` |
| S3 | child envp not scrubbed | `Dial = No` catches it **and the diagnostic names which of the two catches fired** | `sm` |
| S4 | inherited P5f epoch invalidation disabled | a replaced context inherits stale synced state; a still-live XFB lifetime retains its paused span | `st` |
| S5 | `WindowKind::X11` with a plausible XID reaches the server | named Fatal, **and the gate falsifies that the token reached `UnpackWindowHandle`**. Today's S5 tests only `AndroidNativeWindow` and stays green with §7.1's hole open | `cp` |
| S6 | a peer offers `LinkTerms.dataPlane = StreamOnly` | refused by name, **and the server survives to serve the next connection** | `hs` |
| S7 | a bare `abort()` added outside `Session::Fail` | the census gate goes red | `dl` |
| S8 | — | `integration-spawn` asserts `SessionFaultCount() == 0` over a whole run: the **good-path** assertion E1/ID-122 wanted and could not express, and which S5/S6 can falsify | `t6` |
---
## §10 Amendments
### 10.1 To `P6-CONTRACT-DRAFT.md`, which this file supersedes
1. §1's "ABI fingerprint | Unchanged … same-machine, same-binary" → §4.
2. §5.1's "The latch … is implemented unchanged" → **false**; §5.3.
3. §4's "P6's remainder is TRANSPORT ONLY" → **false in three ways**; §6.1.
4. §7's "a transport swap and nothing else" → **no longer true**. This file adds `lk`, `hs` and `dl`
to the package list and says so here rather than smuggling it.
### 10.2 To the earlier contracts
1. `CONTRACT-P5C.md:537-539` — EGL value framing was discharged by P5f `fc`, the unpack/render-state
epoch work by P5f `fs`. P6 carries the existing frames over the socket and verifies the inherited
lifecycle rules in the second process.
2. `CONTRACT-P5C.md:56` — P6's multi-context shape. **Declined**: P6 stays single-context. §11.
3. `Transport/ReplySlot.h`'s "P6 debt" for the 2 MiB reply cap and chunked readback. **Declined**:
P9's. Note `P6-SPAWN-PLAN §8.5` already reassigned it and the header was never updated — two
documents in the tree disagreed; this file settles it.
4. `Ring.h`'s "BATCHING MAY ONLY MAKE A WATERMARK LATE" — `appliedSeq` is excluded from lazy publication **by name**. P6 does not change
the behaviour; it records that any future stream link **amends** this rule rather than inferring
around it. Several designs have argued the late-never-early invariant licenses lazy `appliedSeq`;
it explicitly carves `appliedSeq` out.
5. `ARCHITECTURE.md:488` — the child-forces-monolith rule. **Amended**; §3.1.
6. `ARCHITECTURE.md:9` and `MG_Backend/MGPipe/PipeInputs.h:281`, `:744`, `:957`, and
`P5F-WIRE-COMPLETENESS §1.4` — "the server does not link `MG_Impl`". **False at this head.** §12.
### 10.3 Amendments of 2026-09-22 — the end state re-ruled
1. **The end state is TCP across machines, OSes and architectures**, not an AVF pVM over
`AF_VSOCK`. `docs/Disaggregated/P6-ENDSTATE-REVIEW.md` carries the retraction at its head; its
§3 gains form **D**. Same-machine `spawn` (AF_UNIX + shared segments) stays as the local form.
2. **The transport stack has two independent axes.** The control plane (`ITransport`: `fork`
inherited fds / `unix:<path>` / `tcp://host:port`) and the data plane (`ILink`: `ShmLink` /
`StreamLink`) are chosen separately, negotiated in the handshake, and may be mixed — on one
machine, control over TCP with data over shared segments is a legal pair. Callers above
`Transport/` see `ITransport` + `ILink` and nothing else; branching on the link kind above that
line is a purity-gate failure (the `lk` grep gate, widened). Design: `ARCHITECTURE.md` §11.9.
3. **§8.2's "`ITransport` is not extended" is amended in one respect**: descriptor passing leaves
the control plane and becomes the shared-segment data plane's *delivery*. `ShmLink` brings its
own AF_UNIX aux rendezvous, named in `Welcome`, and `SCM_RIGHTS` travels on that and nowhere
else. Rule G is unchanged: a transport that declares no descriptor passing (TCP) passes none,
and the data plane that needs it must bring its own channel or not be selected. `auto`
selection is decided by a **successful delivery**, never by inspecting addresses, and a
fall-back to `Stream` is named in the log and the stats line.
4. **§2's three `hs` rows** (`LinkTerms`, `Refuse`, the fingerprint split) did not land in `hs`;
`protocol.fbs` carries neither `LinkTerms` nor a `Refuse` member of `CtrlMsg`. They are P6.5's
(`nd`, `wf`), and S6 in §9 moves with them. `CURRENT_STAGE_PROGRESS.md`'s earlier claim that
S6 had been run red is withdrawn.
5. **Fixed-width wire form is no longer negotiable-later.** Two different binaries from two
compilers are the end state, so the `PipeFields.def`-derived layout digest, the fixed-width
rewrite of `DynamicBackendParameters` / `MGPCaps` / the `RenderStateParameters` blob, and the
`buildFingerprint`-only-under-`Dial == Fork` policy are P6.5 `wf`, taken off P7.
6. **`Ph` gains pairing/authentication**: a `Hello` without a pairing token is refused on any
non-loopback listener. `Ph` precedes P12's non-loopback listen.
7. **"The 511 class-C entries" in §11** is the P5-joint census
(`docs/Disaggregated/notes/p6/census-classC.md`). At this head the `MGR_UNMIGRATED_*` lists are
empty; `SetSwapInterval` (P10) and `DeleteTransformFeedback` (P9) are the two that remain.
---
## §11 Not P6
Real window arrival and the `android:process=":mgl"` Service (P12); multi-context (P12); chunked
readback and the reply-slot pool (P9); `DynamicBackendParameters`' fixed-width rewrite (P7);
`MOBILEGL_IPC_POLL_ESCALATE` (P10); remaining monolith-only frontend-object / twin-registry glue
(P3b/P4b) and the named P7 functionality debts; Windows `pipe:` / `unix:`; the 511 class-C entries.
**The two-axis transport stack — control × data, TCP-capable, cross-build — is P6.5** and is the
IPC track's next stage (§10.3). P9 builds its reply semantics on P6.5's message replies rather than
on a slot pool, and P11's T0/T1 are refused by name on a stream data plane.
**Untrusted-guest hardening is `Ph`**, and it must land before any shipping server app accepts a
connection from a guest it did not produce — including the `Fatal`-policy flip (§5.2), the
handle-slot budget, and the caps in §12.
E1's re-specification (ID-122) is **not** discharged by P6 and does not become P6's because P6 starts.
---
## §12 Recorded debt
### 12.1 The server image links `MG_Impl` in P6 (D12)
**P6's server image is the whole `libMobileGL.so`** — which is what `ARCHITECTURE.md:496`'s "one
shared library, two roles" always meant. The assertions that the server does not link `MG_Impl` are
false and become debt with named owners.
Measured: **184 symbols**, 177 of them real function calls, that the server set needs and only
`MG_Impl` / `MG_State` / `MG_Remote/Client` define. Owners: **P7 101**, **P3b/P4b 14**, both backends
**60**, **P6's own 6**. There is additionally **no module target to link** — `SOURCE_FILES` is one
flat list feeding both library targets — so establishing module boundaries is itself named work,
owed to P13. Method and full symbol list:
[`a6-link-experiment.md`](../../docs/Disaggregated/notes/p6/a6-link-experiment.md).
**P6's own six** are not P7's and are `sm`/`lk`'s to clear: `Server/PipeApplier.cpp` calls
`Client::ClientSession::NoteApplyThreadEnteredApplier()` / `NoteApplyThreadLeftApplier()`;
`Wire/PipeWireCodec.cpp` needs `MG_State::GLState::DecodeProgramArchive` and
`Client::AdoptTierIsEmulate()`; `MG_Pipe/PipeApply.cpp` needs `Client::ClientSession::Active()` and
`AdoptTierIsEmulate()`.
**Gate**: a ratchet recomputes the 184 in CI and asserts it only ever falls.
### 12.2 D11 — five unbounded peer-driven allocations, capped, with no `try`/`catch`
Every peer-declared count is bounded **before** it reaches an allocator and the bound is a named
refusal. `MG_Remote` gets no `try`/`catch`: a cap that is checked is better than an exception that is
caught, and the funnel (§5.2) is where the diagnostic lives.
| site | today | package |
|---|---|---|
| `MG_Pipe/PipeApply.cpp:1563-1569` | resizes to a peer-supplied `Cso.Slot + 1` with **no slot limit**; every sibling create-family goes through `RecordAt`'s bounded path. `Slot = 0xFFFFFFFE` asks for ~1.7 TB | `dl` |
| `Server/PipeApplier.cpp:416-441` | readback scratch resized from `Box.W * Box.H * bpp` **before** any size gate. 65535² RGBA8 asks for ~17 GB | `dl` |
| `MG_State/.../ProgramArtifactsCodec.cpp:166-175`, `:216-223` | count bounded by remaining **bytes**, then multiplied by `sizeof(element)` | `dl` |
| `Server/StagedTextureStore.h` | resize not bounded against the level's declared extent | `Ph` |
| `SEG_EVENT` overflow | a guest that merely stops draining kills the host renderer in 60 s | `Ph` |
### 12.3 One guest per server process (D9)
For the whole of P6, one server process serves exactly one client session, and it is a **structural
fact, not a preference**: `g_Display`/`g_Context`/`g_Surface`/`g_Config` are per-process file-statics
and `InitDisplayAndContext` opens with an unconditional `DestroyEGLContext()` whose last act is
`eglTerminate` — a **process-wide** EGL teardown. `ServerSession::Accept`'s same-object arm
(`ServerSession.cpp:425`) returns `MOBILEGL_ERR_INVALID_ARGUMENT` **with no log line at all**; `sm`
gives it one. Under `Dial == Fork` a second guest is unreachable by construction, so the invariant
becomes falsifiable only under `Dial == Connect`, which P6 does not land.
### 12.4 Settled by ruling rather than by experiment
- **Who runs the applier in the server process**: `ServerMain` **must** drive it through
`ServerLoop::Start()`, so `g_applyThreadKey` is published and the dozen `OnApplyThread()` guards
keep meaning what they mean. Owner `sm`; red-once drives the applier without `Start()`.
- **The server's exit primitive**: `_exit`, after an explicit log flush. It decides whether
`g_processTeardown` is set and therefore whether seven twin destructors take their early-out.
Owner `sm`.
- **The handshake asserts the resolved subsystem mask**; a mismatch is `Refuse`, not `Fatal`. The
envp scrub list does **not** include `MOBILEGL_PIPE_*`, so the two processes can resolve different
masks from their own environments. Owner `hs`.
- **P6 maps no segment read-only.** `ShmSegment.h:62-63`'s stated design — the peer gets
`SEG_CMD`/`SEG_STAGE` read-only on the server side — **cannot be implemented as written**, and the
comment is corrected rather than left to mislead. Owner `lk`.
- **`DualBlockScenario`'s `serverIdentity != nullptr`** is an in-process fact, and G2/G14 requires
the spawn lane to keep the case name. Its assertions are **re-homed**, not weakened: `DualBlockPeek`
becomes a control-plane query answered by the server process. The declared fallback — assert
`MGPipeBlocksAreDistinct()` on the client side and carry the identity half by §3.4's server-side
Fatal — must be **declared here** if taken, not discovered in review. Owner `t6`.
+7 -1
View File
@@ -485,7 +485,13 @@ namespace MobileGL::MG_Remote {
// which is the one break the rest of the mix is blind to.
inputs.AbiVersion =
static_cast<Uint32>(MOBILEGL_ABI_VERSION(MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR));
inputs.BuildStamp = GIT_COMMIT_HASH_SHORT;
// MOBILEGL_BUILD_STAMP_VALUE, NOT GIT_COMMIT_HASH_SHORT (CONTRACT-P6 4.2). The old
// macro is application-visible through glGetString(GL_VERSION) and may not move, and it
// came from an execute_process with no RESULT_VARIABLE - so a tree git could not read
// produced "" and every such build agreed with every other. The new pair separates the
// VALUE from whether the build could name a commit at all.
inputs.BuildStamp = MOBILEGL_BUILD_STAMP_VALUE;
inputs.BuildStampPresent = MOBILEGL_BUILD_STAMP_PRESENT;
return inputs;
}
+572 -50
View File
@@ -10,11 +10,14 @@
// reply read that sits inside it are package c1's (EmitAndWait below is still c0's stub).
#include "ClientSession.h"
#include <MG_Remote/FatalFunnel.h>
#include "../CapsCodec.h"
#include "../Protocol/generated/protocol_generated.h"
#include "../Server/ServerLoop.h"
#include "../Server/ServerSession.h"
#include "../Protocol/SurfaceOpCodec.h"
#include "../Transport/FdPassing.h"
#include "../Transport/InProcessTransport.h"
#include "WireTables.h"
@@ -34,15 +37,34 @@
#include <utility>
#include <vector>
// CONTRACT-P6 4.3: the handshake now carries real process ids.
#if defined(_WIN32)
#include <process.h>
#else
#include <unistd.h>
#endif
namespace MobileGL::MG_Remote::Client {
namespace {
// CONTRACT-P6 4.3. Hello::pid was hard-coded 0 and Welcome::serverPid ECHOED it, so both
// were always 0 and neither named anything. Under spawn the pair is the cheapest arm
// proof there is: two different values mean two processes, and a same-process session
// cannot produce them.
std::uint32_t SelfProcessId() {
#if defined(_WIN32)
return static_cast<std::uint32_t>(::_getpid());
#else
return static_cast<std::uint32_t>(::getpid());
#endif
}
} // namespace
#define MGP5_C0_STUB(what) \
do { \
MGLOG_F("MGPipe: Fatal{UnimplementedClientSession, \"%s\"} - P5 packages s1/c1 have not " \
SessionFail(MGFatalFamily::UnimplementedClientSession, \
"MGPipe: Fatal{UnimplementedClientSession, \"%s\"} - P5 packages s1/c1 have not " \
"landed this yet; c0 shipped the signature only", \
what); \
std::abort(); \
} while (0)
what)
namespace {
@@ -51,6 +73,13 @@ namespace MobileGL::MG_Remote::Client {
// The same bounded handshake deadline the server uses. Bounded, not kWaitForever: a
// bring-up that never answers has to be a red lane rather than a wedged CI job.
constexpr Uint32 kHandshakeTimeoutMs = 5000;
// cp (CONTRACT-P6 D5b): bounded, and its expiry is NOT fatal. A peer that
// is gone is a different fact from a peer that is slow, and only the
// doorbell death latch may say which.
constexpr Uint32 kRemoteControlTimeoutMs = 5000;
// The server has to create a backend before it binds, and a cold
// software rasteriser is not fast. Bounded, and a NAMED refusal at the end.
constexpr Uint32 kSpawnConnectTimeoutMs = 20000;
// Teardown's drain. Also bounded, and for the same reason - table 3's order is
// "publish and wait for the server to drain and acknowledge", and a wait with no
// deadline there turns a lost record into a hung process exit.
@@ -80,15 +109,37 @@ namespace MobileGL::MG_Remote::Client {
return ::MobileGL::Wire::GetCtrlEnvelope(bytes.data());
}
// CONTRACT-P6 4.3: THE DECLARED PROTOCOL VERSION, WHICH THIS SIDE NEVER READ.
//
// Hello has carried abiMajor/abiMinor since P5 and the SERVER checks them, but the
// client only ever compared the fingerprint - so the asymmetry was silent in the one
// direction that matters for spawn, where the peer is a SEPARATE IMAGE the operator
// chose with MOBILEGL_IPC_SERVER_PATH.
//
// The fingerprint mixes AbiVersion and would catch a mismatch anyway, but it catches it
// as "struct shapes" - which sends the reader looking for a layout change that is not
// there. Checking the version FIRST turns the same failure into the sentence that
// explains it. Both handshake sites call this; there are two, and only one of them used
// to be reachable, which is how the gap survived review.
[[noreturn]] void FatalProtocolVersionMismatch(unsigned theirMajor, unsigned theirMinor,
const char* theirStamp) {
SessionFail(MGFatalFamily::AbiMismatch, "MGPipe: Fatal{AbiMismatch, \"protocol version\"} ours=%u.%u theirs=%u.%u "
"ourBuild=%s theirBuild=%s - the peer speaks a different MGPipe protocol. "
"Under spawn this is most often a stale MOBILEGL_IPC_SERVER_PATH pointing at "
"a libMobileGLServer.so built from another tree.",
static_cast<unsigned>(MOBILEGL_PROTOCOL_ABI_MAJOR),
static_cast<unsigned>(MOBILEGL_PROTOCOL_ABI_MINOR), theirMajor, theirMinor,
GIT_COMMIT_HASH_SHORT, theirStamp == nullptr ? "?" : theirStamp);
}
[[noreturn]] void FatalAbiMismatch(const char* what, Uint64 ours, Uint64 theirs,
const char* theirStamp) {
MGLOG_F("MGPipe: Fatal{AbiMismatch, \"%s\"} ours=%llu theirs=%llu ourBuild=%s "
SessionFail(MGFatalFamily::AbiMismatch, "MGPipe: Fatal{AbiMismatch, \"%s\"} ours=%llu theirs=%llu ourBuild=%s "
"theirBuild=%s - never a downgrade: the caps block's size is ABI-dependent "
"and every field past the first difference would be read at the wrong offset",
what, static_cast<unsigned long long>(ours),
static_cast<unsigned long long>(theirs), GIT_COMMIT_HASH_SHORT,
theirStamp == nullptr ? "?" : theirStamp);
std::abort();
}
// Guarded the same way ServerSession's helpers are: MG_Config::Ipc only exists
@@ -178,7 +229,7 @@ namespace MobileGL::MG_Remote::Client {
if (wait == Transport::SessionWait::Reached) {
Transport::RingControl* control = producer.Control();
if (control == nullptr ||
Transport::Watermark::Reached(control->appliedSeq, seq)) {
Transport::Watermark::Reached(control->Progress.appliedSeq, seq)) {
return wait;
}
DrainEventRing(events);
@@ -272,9 +323,8 @@ namespace MobileGL::MG_Remote::Client {
Bool corrupt = false;
while (events.Pop(view, &corrupt)) {
if (corrupt) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"event-ring\"} - the reverse "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"event-ring\"} - the reverse "
"channel's record stream is corrupt");
std::abort();
}
switch (view.kind) {
case Transport::kEventBufferWriteback: {
@@ -283,11 +333,10 @@ namespace MobileGL::MG_Remote::Client {
static_cast<const Transport::EventBufferWritebackHead*>(view.payload);
const void* bytes = static_cast<const Uint8*>(view.payload) + sizeof(*head);
if (view.payloadSize - sizeof(*head) < head->Size) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"buffer-writeback\"} - the "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"buffer-writeback\"} - the "
"head declares %llu inline bytes and the record carries %llu",
static_cast<unsigned long long>(head->Size),
static_cast<unsigned long long>(view.payloadSize - sizeof(*head)));
std::abort();
}
// The blobref names SEG_EVENT and the IN-SEGMENT offset of those inline
// bytes - never a host address (R-2's rule B), which is the whole reason
@@ -309,11 +358,10 @@ namespace MobileGL::MG_Remote::Client {
static_cast<const Transport::EventGpuWrittenHead*>(view.payload);
const Uint64 tail = view.payloadSize - sizeof(*head);
if (tail / sizeof(Transport::EventRange) < head->RangeCount) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"gpu-written\"} - RangeCount "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"gpu-written\"} - RangeCount "
"%u does not fit the record's %llu tail bytes",
static_cast<unsigned>(head->RangeCount),
static_cast<unsigned long long>(tail));
std::abort();
}
// EventRange and MGPRange are the same two Uint64s (EventRing.h:61-66
// asserts it), so the tail is handed over as-is rather than copied into
@@ -354,12 +402,11 @@ namespace MobileGL::MG_Remote::Client {
// least one byte and that byte terminates the string.
if (head->MessageBytes == 0 || tail < head->MessageBytes ||
message[head->MessageBytes - 1] != '\0') {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"kEventGlError\"} - "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"kEventGlError\"} - "
"MessageBytes %u against a %llu-byte tail, or the terminating "
"NUL is missing",
static_cast<unsigned>(head->MessageBytes),
static_cast<unsigned long long>(tail));
std::abort();
}
// The error queue is CLIENT state, written here on the GL thread. The
// observation point is the next drain after the post - P9 owns the
@@ -457,6 +504,27 @@ namespace MobileGL::MG_Remote::Client {
// monolith answer. Every call that PRESUMES a session aborts instead.
ClientSession* ClientSession::Active() { return g_active; }
Bool ClientSession::DeviceLost() {
const ClientSession* session = Active();
return session != nullptr && session->m_deviceLost.load(std::memory_order_acquire);
}
void ClientSession::LatchDeviceLost(const char* why) {
// exchange, so the log line is written EXACTLY once however many waits notice the same
// hangup at the same moment - and there will be several: the barrier, the control wait
// and the event pump can all be in flight when the server goes.
if (m_deviceLost.exchange(true, std::memory_order_acq_rel)) {
return;
}
MGLOG_E("MGPipe: DEVICE LOST - %s. The server process is gone; every verb from here is "
"DECLINED and glGetGraphicsResetStatus reports GL_UNKNOWN_CONTEXT_RESET. This is "
"latched from the peer's HANGUP and not from any deadline (CONTRACT-P6 5.4): a "
"server one frame behind is P5e's intended steady state and must never read as a "
"dead one. There is no recovery - MOBILEGL_IPC_RESPAWN is the stage that would "
"add one and it is refused by name until then.",
why == nullptr ? "the peer hung up" : why);
}
ClientSession& ClientSessionInstance() {
// Leak at exit, deliberately and per ID-8, exactly as ServerSessionInstance does.
static ClientSession* instance = new ClientSession{};
@@ -518,7 +586,7 @@ namespace MobileGL::MG_Remote::Client {
auto stamp = builder.CreateString(GIT_COMMIT_HASH_SHORT);
auto hello = ::MobileGL::Wire::CreateHello(
builder, MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR, stamp,
/*backendType=*/0u, /*pid=*/0u, /*configBlob=*/0, fingerprint);
/*backendType=*/0u, /*pid=*/SelfProcessId(), /*configBlob=*/0, fingerprint);
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
builder, ::MobileGL::Wire::CtrlMsg::Hello, hello.Union());
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
@@ -563,6 +631,16 @@ namespace MobileGL::MG_Remote::Client {
const char* theirStamp = welcome->buildFingerprint() == nullptr
? nullptr
: welcome->buildFingerprint()->c_str();
// 4.3: the pid the SERVER stated, taken before any check can abort, so a Fatal line
// can name it too.
m_peerServerPid = static_cast<std::uint32_t>(welcome->serverPid());
// The VERSION before the fingerprint: both would fire, and only one names the cause.
if (welcome->abiMajor() != MOBILEGL_PROTOCOL_ABI_MAJOR ||
welcome->abiMinor() != MOBILEGL_PROTOCOL_ABI_MINOR) {
FatalProtocolVersionMismatch(static_cast<unsigned>(welcome->abiMajor()),
static_cast<unsigned>(welcome->abiMinor()),
theirStamp);
}
if (welcome->abiFingerprint() != fingerprint) {
FatalAbiMismatch("struct shapes", fingerprint, welcome->abiFingerprint(),
theirStamp);
@@ -603,6 +681,406 @@ namespace MobileGL::MG_Remote::Client {
return attached;
}
return FinishStartup(&m_clientTransport->PeerDoorbell(),
&m_clientTransport->SelfDoorbell(),
/*startApplyThreadHere=*/true);
}
MobileGLResult ClientSession::StartSpawned() {
if (m_started) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
// A rendezvous nobody else can collide with. Independent processes need
// a NAME; making it per-process-per-instant is what stops two runs on
// one machine - which `ctest -j` produces by construction - finding each
// other's server.
// AN ABSTRACT NAME ('@'), not a path under /tmp. An Android app has no
// writable /tmp and the first device run proved it the blunt way: the
// server launched, bind() had nowhere to put the node, and the client
// refused by name 20 s later. The abstract namespace needs no directory,
// no mode bits and no cleanup after a crash, and its reach - the network
// namespace - is exactly one app's processes.
const std::string endpoint = std::string("@mgl-") +
std::to_string(static_cast<long long>(::getpid())) + "-" +
std::to_string(reinterpret_cast<std::uintptr_t>(this));
const MobileGLResult launched =
Server::LaunchServer(std::string(MG_Config::Ipc.ServerPath.c_str()), endpoint,
&m_spawned);
if (launched != MOBILEGL_OK) {
return launched;
}
std::unique_ptr<Transport::SocketTransport> socket;
// The bounded connect retry is what tolerates the server still binding -
// and it is the CLIENT's, not the launcher's. An exhausted budget is a
// NAMED refusal; there is no monolith fallback from here.
const MobileGLResult connected =
Transport::SocketTransport::ConnectTo(endpoint, kSpawnConnectTimeoutMs, socket);
if (connected != MOBILEGL_OK) {
int exitCode = 0;
Server::ReapServer(m_spawned, 2000, &exitCode);
MGLOG_E("MG_Remote client: could not reach the server we launched at \"%s\" "
"(rc=%d, server exit=%d)",
endpoint.c_str(), static_cast<int>(connected), exitCode);
return connected;
}
// THE ONE FACT A MONOLITH OR inproc RUN CANNOT PRODUCE: a pid that is
// not ours. The ConfigLoader marker proves the VALUE resolved; this
// proves the SERVER ROLE LEFT THIS PROCESS, which is the whole claim the
// SPAWN arm of the retrace matrix makes. run_trace_case.cmake requires
// BOTH, so a spawn arm cannot go green on a transport that resolved and
// then quietly ran the server role locally.
const MobileGLResult started = StartOverSocket(std::move(socket));
if (started == MOBILEGL_OK) {
MGLOG_I("MG_Remote client: spawn ARMED - the server role runs in pid %d, reached at "
"\"%s\"",
m_spawned.pid, endpoint.c_str());
}
return started;
}
MobileGLResult ClientSession::StartOverSocket(
std::unique_ptr<Transport::SocketTransport> transport) {
if (m_started) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
if (transport == nullptr) {
MGLOG_E("MG_Remote client: StartOverSocket needs a connected transport");
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
m_socketTransport = Move(transport);
m_transport = m_socketTransport.get();
// ---- Hello. The same bytes as inproc; the fingerprint is still compared
// for equality, because under Dial == Fork the child IS the same binary and
// comparing it catches a stale MOBILEGL_IPC_SERVER_PATH (CONTRACT-P6 4.1).
const Uint64 fingerprint = CapsAbiFingerprint();
{
::flatbuffers::FlatBufferBuilder builder(512);
auto stamp = builder.CreateString(GIT_COMMIT_HASH_SHORT);
auto hello = ::MobileGL::Wire::CreateHello(
builder, MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR, stamp,
/*backendType=*/0u, /*pid=*/SelfProcessId(), /*configBlob=*/0, fingerprint);
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
builder, ::MobileGL::Wire::CtrlMsg::Hello, hello.Union());
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
const MobileGLResult sent = m_transport->SendFrame(
MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()});
if (sent != MOBILEGL_OK) {
Stop();
return sent;
}
}
// ---- Welcome, and the four announced sizes. THERE IS NO LOCAL SERVER TO
// ASK: the inproc path cross-checks Welcome against ServerSessionInstance()'s
// own mapping, which a6 showed is vacuous against a real peer. Here the wire
// values are the only values, which is what that check has to become on
// every lane (CONTRACT-P6 4.4).
Uint64 announced[4] = {0, 0, 0, 0};
const Uint32 replySlotCount = Transport::kDefaultReplySlotCount;
{
std::vector<Uint8> frame;
const MobileGLResult received =
ReceiveEnvelope(*m_transport, frame, kHandshakeTimeoutMs);
if (received != MOBILEGL_OK) {
MGLOG_E("MG_Remote client: no Welcome from the spawned server within %u ms (rc=%d)",
kHandshakeTimeoutMs, static_cast<int>(received));
Stop();
return received;
}
const ::MobileGL::Wire::CtrlEnvelope* envelope = ParseEnvelope(frame);
if (envelope == nullptr || envelope->msg_type() != ::MobileGL::Wire::CtrlMsg::Welcome ||
envelope->msg_as_Welcome() == nullptr) {
MGLOG_E("MG_Remote client: the spawned server first frame is not a verifiable "
"Welcome");
Stop();
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
const ::MobileGL::Wire::Welcome* welcome = envelope->msg_as_Welcome();
const char* theirStamp = welcome->buildFingerprint() == nullptr
? nullptr
: welcome->buildFingerprint()->c_str();
// 4.3: the pid the SERVER stated, taken before any check can abort, so a Fatal line
// can name it too.
m_peerServerPid = static_cast<std::uint32_t>(welcome->serverPid());
// The VERSION before the fingerprint: both would fire, and only one names the cause.
if (welcome->abiMajor() != MOBILEGL_PROTOCOL_ABI_MAJOR ||
welcome->abiMinor() != MOBILEGL_PROTOCOL_ABI_MINOR) {
FatalProtocolVersionMismatch(static_cast<unsigned>(welcome->abiMajor()),
static_cast<unsigned>(welcome->abiMinor()),
theirStamp);
}
if (welcome->abiFingerprint() != fingerprint) {
FatalAbiMismatch("struct shapes", fingerprint, welcome->abiFingerprint(),
theirStamp);
}
const ::MobileGL::Wire::SegmentRef* refs[4] = {welcome->cmdRing(), welcome->stageRing(),
welcome->replyPool(),
welcome->eventRing()};
for (int index = 0; index < 4; ++index) {
if (refs[index] == nullptr || refs[index]->sizeBytes() == 0) {
MGLOG_E("MG_Remote client: Welcome SegmentRef %d is missing or zero-sized",
index);
Stop();
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
announced[index] = refs[index]->sizeBytes();
}
}
// ---- the four descriptors. THIS is the step inproc does not have, and the
// reason SCM_RIGHTS is in this design at all: the segments are anonymous -
// ASharedMemory_create has no filesystem name and memfd / shm_open+unlink
// are not openable either - so the descriptor IS the only key.
//
// The slot travels in the sideband rather than being inferred from arrival
// order, so a reordered or dropped offer is a NAMED mismatch instead of two
// segments quietly swapped.
// Seven offers: four segments, then THREE bell descriptors (slots 4..6).
// Three because each side parks on one and rings another; see ServerMain.
int fds[7] = {-1, -1, -1, -1, -1, -1, -1};
{
struct Sideband {
Uint32 slot;
Uint64 bytes;
};
const auto closeAll = [&fds]() {
for (int& open : fds) {
if (open >= 0) {
::close(open);
open = -1;
}
}
};
for (int received = 0; received < 7; ++received) {
Sideband sideband{};
Uint64 sidebandSize = 0;
int fd = -1;
std::vector<Uint8> scratch(Transport::FdPassing::kMaxSidebandBytes);
MobileGLMutableByteSpan span{scratch.data(), scratch.size()};
const MobileGLResult got =
m_transport->ReceiveFd(&fd, span, &sidebandSize, kHandshakeTimeoutMs);
if (got != MOBILEGL_OK || fd < 0) {
MGLOG_E("MG_Remote client: segment descriptor %d did not arrive (rc=%d)",
received, static_cast<int>(got));
closeAll();
Stop();
return got == MOBILEGL_OK ? MOBILEGL_ERR_PROTOCOL_MISMATCH : got;
}
if (sidebandSize != sizeof(Sideband)) {
MGLOG_E("MG_Remote client: segment offer %d carried %llu sideband bytes",
received, static_cast<unsigned long long>(sidebandSize));
::close(fd);
closeAll();
Stop();
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
std::memcpy(&sideband, scratch.data(), sizeof(Sideband));
const bool isSegment = sideband.slot < 4;
if (sideband.slot >= 7 || fds[sideband.slot] >= 0 ||
(isSegment && sideband.bytes != announced[sideband.slot])) {
MGLOG_E("MG_Remote client: segment offer names slot %u with %llu bytes; "
"Welcome announced a different size or the slot is already filled",
sideband.slot, static_cast<unsigned long long>(sideband.bytes));
::close(fd);
closeAll();
Stop();
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
fds[sideband.slot] = fd;
}
// ---- adopt and map. The same Adopt + Map every inproc run has
// exercised since P5; only the origin of the descriptor is new.
const MobileGLResult adopted = m_shm.AdoptFromDescriptors(
fds, announced, replySlotCount, Transport::MemoryRole::Client);
if (adopted != MOBILEGL_OK) {
closeAll();
Stop();
return adopted;
}
// The four segment descriptors now belong to m_shm. The two bells
// belong to the doorbells, which own and close them.
//
// WHICH BELL IS WHICH IS THE SESSION'S KNOWLEDGE, exactly as under
// inproc: slot 4 is the pair end whose WRITE wakes the server, slot 5
// is the one this side POLLS.
// PARK ON ONE END, RING THE OTHER - the same split the server makes,
// and for the same reason: a single-fd bell rings the PEER, so it
// cannot wake its own waiter.
// fds[4] ring the SERVER (ring-only, we never park on it)
// fds[5] our park end
// fds[6] ring OURSELVES
m_socketPeerBell = MakeUnique<Transport::SocketDoorbell>(-1, fds[4], 1, true);
// Built into a TYPED pointer first: the witness is SocketDoorbell's, and the member
// is a Doorbell so that the inproc path can put a CondVarDoorbell in it.
auto selfBell = MakeUnique<Transport::SocketDoorbell>(fds[5], fds[6], 1, true);
// `dl`: THE DEATH WITNESS, and it has to be a descriptor this side does not also
// write to. Our own bell is a socketpair we hold BOTH ends of - slot 5 to park on,
// slot 6 to ring ourselves - so it can never hang up however dead the server is. The
// control socket's far end is held only by the server, so its hangup IS the death.
//
// Passing the fd rather than the transport keeps the ownership honest: the bell polls
// it for hangup alone and never reads it, and SocketTransport goes on owning and
// closing it. CONTRACT-P6 D5c.
selfBell->SetDeathWitness(m_socketTransport->StreamFd());
m_socketSelfBell = Move(selfBell);
}
// `cp`: from here the twelve EGL forwarders cross the socket instead of
// being posted into a mailbox this process does not own. Installed BEFORE
// FinishStartup, because FinishStartup's caps pump can already trigger
// one.
Server::ServerLoopInstance().SetRemoteControlSink(&RemoteControlSinkThunk, this);
// The apply thread IS ALREADY RUNNING, in the other process: ServerMain
// started it before it sent the first descriptor. Starting one here would
// put a second applier on a ring that already has one.
return FinishStartup(m_socketPeerBell.get(), m_socketSelfBell.get(), false);
}
MobileGLResult ClientSession::RemoteControlSinkThunk(void* user,
Server::SurfaceControlFrame& frame) {
return static_cast<ClientSession*>(user)->RunRemoteSurfaceControlFrame(frame);
}
MobileGLResult ClientSession::RunRemoteSurfaceControlFrame(Server::SurfaceControlFrame& frame) {
if (m_transport == nullptr) {
return MOBILEGL_ERR_NOT_INITIALIZED;
}
// THE CLIENT MINTS, always, dense from 1 (CONTRACT-P6 §6.3). The server's
// local mint exists for unnumbered LOCAL posts; a wire request that let
// the server renumber it would get back a reply it cannot correlate.
if (frame.seq == 0) {
frame.seq = ++m_remoteControlSeq;
}
::flatbuffers::FlatBufferBuilder builder(512);
const MG_Remote::SurfaceWireError encoded = MG_Remote::EncodeSurfaceOpFrame(frame, &builder);
if (encoded != MG_Remote::SurfaceWireError::None) {
// A NAMED refusal, not a dropped op. InprocOnlyOpOnTheWire is the
// live one: three of the twelve forwarders ride the frame channel
// without a wire kind (CONTRACT-P6 §2), and a spawn client that
// reaches one has found a gap rather than a transport error.
MGLOG_E("MG_Remote client: surface op kind %d cannot cross the wire (%s)",
static_cast<int>(frame.kind), MG_Remote::SurfaceWireErrorName(encoded));
return MOBILEGL_ERR_UNSUPPORTED;
}
// ONE CONTROL OP AT A TIME. The twelve forwarders are already
// caller-serialised on the server's m_callerMutex under inproc; the same
// discipline has to hold here or two replies race for one correlation.
const std::lock_guard<std::mutex> lock(m_remoteControlMutex);
const MobileGLResult sent = m_transport->SendFrame(
MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()});
if (sent != MOBILEGL_OK) {
return sent;
}
// The reply. A BOUNDED wait whose expiry is NOT fatal (CONTRACT-P6 §5.4
// D5b): a peer that is gone is a different fact from a peer that is slow,
// and only the doorbell's death latch may say which.
for (;;) {
std::vector<Uint8> reply;
const MobileGLResult received =
ReceiveEnvelope(*m_transport, reply, kRemoteControlTimeoutMs);
if (received != MOBILEGL_OK) {
// `dl` (D5b): THE EXPIRY IS NOT FATAL AND IT IS NOT ONE ANSWER. The transport
// already distinguishes the two states this wait can end in, and the contract
// says they must stay distinguished without a threshold:
//
// TRANSPORT_CLOSED - the control socket returned EOF. Only the server held the
// far end, so it is gone. That is the device-loss fact, taken from a
// descriptor.
// TIMEOUT - nothing arrived in the budget, and the socket is still open. The
// peer is ALIVE AND SILENT: wedged, frozen, SIGSTOP'd, or merely slower than
// the budget. 5.4 forbids calling that a death, so it gets a NAME instead.
// The bell is asked anyway, because a hangup noticed by the ring side counts
// here too.
if (received == MOBILEGL_ERR_TRANSPORT_CLOSED) {
LatchDeviceLost("the control stream reached EOF while a reply was owed");
} else if (const Transport::Doorbell* bell = m_producer.SelfDoorbell();
bell != nullptr && bell->PeerHungUp()) {
LatchDeviceLost("a control reply timed out and the peer had hung up");
} else {
MGLOG_E("MG_Remote client: the server is ALIVE BUT SILENT - no SurfaceReply "
"for %s seq %llu within %u ms and the control stream is still open. "
"This is NOT device loss (CONTRACT-P6 5.4): a frozen or merely slow "
"peer produces no hangup, and only a hangup may arm the latch. If "
"this repeats, the server is wedged rather than gone.",
Server::SurfaceControlOpName(frame.kind),
static_cast<unsigned long long>(frame.seq), kRemoteControlTimeoutMs);
}
MGLOG_E("MG_Remote client: no SurfaceReply for seq %llu within %u ms (rc=%d)",
static_cast<unsigned long long>(frame.seq), kRemoteControlTimeoutMs,
static_cast<int>(received));
return received;
}
const ::MobileGL::Wire::CtrlEnvelope* envelope = ParseEnvelope(reply);
if (envelope == nullptr) {
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
if (envelope->msg_type() == ::MobileGL::Wire::CtrlMsg::CapsSnapshot) {
// The server republishes caps from inside its MakeCurrent
// dispatch (a6 row A4-30), so a snapshot can arrive BEFORE the
// reply to the very op that produced it. Adopting it here rather
// than dropping it is what keeps R-12's "a second arrival IS the
// invalidation" true on this path too.
if (const auto* snapshot = envelope->msg_as_CapsSnapshot()) {
AdoptCapsSnapshot(snapshot);
}
continue;
}
if (envelope->msg_type() == ::MobileGL::Wire::CtrlMsg::Fatal) {
// `dl` step three: the server published a SessionFault before it aborted, so this
// is a death that NAMES ITSELF instead of arriving as a bare EOF. Log the family
// and detail, latch device-lost from it, and report the op declined - the same
// answer a hangup gives, now with a cause the guest's log can read.
if (const auto* fatal = envelope->msg_as_Fatal()) {
const char* fam = fatal->family() ? fatal->family()->c_str() : "<none>";
const char* msg = fatal->message() ? fatal->message()->c_str() : "";
MGLOG_E("MG_Remote client: the server published a SessionFault before dying - "
"Fatal family %s: %s", fam, msg);
}
LatchDeviceLost("the server published a SessionFault and then aborted");
frame.ok = false;
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
if (envelope->msg_type() != ::MobileGL::Wire::CtrlMsg::SurfaceReply ||
envelope->msg_as_SurfaceReply() == nullptr) {
MGLOG_E("MG_Remote client: expected a SurfaceReply, got message type %d",
static_cast<int>(envelope->msg_type()));
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
const ::MobileGL::Wire::SurfaceReply* wire = envelope->msg_as_SurfaceReply();
if (wire->seq() != frame.seq) {
MGLOG_E("MG_Remote client: SurfaceReply names seq %llu, we asked for %llu",
static_cast<unsigned long long>(wire->seq()),
static_cast<unsigned long long>(frame.seq));
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
MG_Remote::DecodeWireSurfaceReply(*wire, &frame);
return MOBILEGL_OK;
}
}
// The half of startup that is IDENTICAL for inproc and spawn: the ring
// producer, the reply pool, the event ring, the segment table, the encoder,
// the first CapsSnapshot and the emitter tables. Extracted by `sm` so the
// spawn path cannot drift from the shape P5 spent five packages settling -
// everything here is below the line where "which transport" stopped
// mattering.
//
// `startApplyThreadHere` is the one policy difference, and it is not a
// transport question: under inproc the client is what starts the server
// role, because there is no server-side main to do it. Under spawn there
// IS one, and it started the apply thread before it ever sent Welcome.
MobileGLResult ClientSession::FinishStartup(Transport::Doorbell* peerBell,
Transport::Doorbell* selfBell,
bool startApplyThreadHere) {
Transport::RingControl* control = m_shm.CmdControl();
m_cmd = Transport::RingProducer(control, m_shm.CmdRingBase(), m_shm.CmdRingCapacity(),
Transport::RingCursorSet::Cmd);
@@ -619,8 +1097,7 @@ namespace MobileGL::MG_Remote::Client {
}
// PeerDoorbell() is the bell the SERVER parks on and this side rings; SelfDoorbell() is
// this side's own. Which is which is the session's knowledge, not the transport's.
m_producer.Attach(control, &m_cmd, &m_clientTransport->PeerDoorbell(),
&m_clientTransport->SelfDoorbell(), SpinUsFromConfig());
m_producer.Attach(control, &m_cmd, peerBell, selfBell, SpinUsFromConfig());
m_replies = Transport::ReplySlotPool(m_shm.ReplyBase(), m_shm.ReplyBytes(),
m_shm.ReplySlotCount());
@@ -629,7 +1106,7 @@ namespace MobileGL::MG_Remote::Client {
m_shm.EventSegmentBase());
// P5e (ra, §2.6): the drain's other half. A server parked on a full SEG_EVENT is woken
// by the drain that emptied it, not by the next thing this client happens to publish.
m_events.SetServerDoorbell(&m_clientTransport->PeerDoorbell());
m_events.SetServerDoorbell(peerBell);
if (!m_replies.Valid() || !m_events.Valid()) {
Stop();
return MOBILEGL_ERR_INVALID_ARGUMENT;
@@ -695,16 +1172,34 @@ namespace MobileGL::MG_Remote::Client {
// them down in the mirror order (m_started = false, then g_active = nullptr).
m_started = true;
g_active = this;
// D1c: THE SESSION-LIVE AND APPLY-THREAD FACTS, stated where they become true.
//
// MGPipeApplierReset's layer-2 guard used to ask ClientSession::Active() != nullptr,
// which no SERVER process can ever answer yes to - so the guard was compiled in and
// permanently disarmed there. MGPipeSessionLive() is the same question asked in a way
// both roles can answer, and the probe hands MG_Backend the one thread fact it cannot
// derive: whether the CALLING thread is inside the applier.
MG_Pipe::MGPipeSetSessionLive(true);
// ServerLoop::OnApplyThread, NOT ApplyThreadIsInsideApplier - two different questions,
// and installing the wrong one turned every GL-thread call into a role violation while
// the applier happened to be busy. Measured: the inproc retrace died on
// Fatal{RoleViolation, "MGPipeSlots"} raised from the GL thread. "Am I the apply
// thread" is what the guards ask; "is the apply thread inside the applier" is R-1's
// mutual-exclusion probe and is about a DIFFERENT thread.
MG_Pipe::MGPipeSetApplyThreadProbe(&Server::ServerLoop::OnApplyThread);
LogMemory("handshake");
// ---- 8. and only now the apply thread. It is package v1's ServerLoop: it names the
// thread mgl-srv-apply, applies MOBILEGL_IPC_SERVER_AFFINITY and logs the RESOLVED
// mask. Under `inproc` the client is what starts the server role, which is why this
// call is here rather than in some server-side main.
const MobileGLResult running = Server::ServerLoopInstance().Start(server);
if (running != MOBILEGL_OK) {
Stop();
return running;
if (startApplyThreadHere) {
Server::ServerSession& server = Server::ServerSessionInstance();
const MobileGLResult running = Server::ServerLoopInstance().Start(server);
if (running != MOBILEGL_OK) {
Stop();
return running;
}
}
// ---- 9. AND ONLY NOW THE THIRTY-SEVEN WIRE EMITTERS (R-17). This is the line that
@@ -826,6 +1321,10 @@ namespace MobileGL::MG_Remote::Client {
m_presentsSent = 0;
if (g_active == this) {
g_active = nullptr;
// Mirror order, and the probe goes with it: a dangling function pointer into a
// torn-down session is a worse answer than "there is no applier".
MG_Pipe::MGPipeSetSessionLive(false);
MG_Pipe::MGPipeSetApplyThreadProbe(nullptr);
}
// AND ONLY NOW the monolith adapters go back (codex 4): every ring an emitter would have
// used is freed above, so from here a routed call - an at-exit ~BufferObject delete - runs
@@ -833,6 +1332,25 @@ namespace MobileGL::MG_Remote::Client {
// process that no longer has a session. During the whole span above, the raised flag made
// any routed call abort by name instead.
ReinstallMonolithAfterTeardown();
// P6: the server we launched. Closing the transport is what it sees as
// EOF and EOF is its whole exit condition, so the order is transport
// first, reap second - and the reap is BOUNDED, because a server that
// will not go is a different fact from one that is slow and only the
// exit code can say which.
if (m_spawned.pid >= 0) {
if (m_socketTransport) {
m_socketTransport->Shutdown();
}
int exitCode = 0;
if (Server::ReapServer(m_spawned, 3000, &exitCode) != MOBILEGL_OK) {
MGLOG_W("MG_Remote client: the spawned server (pid %d) did not exit within 3 s",
m_spawned.pid);
} else if (exitCode != 0) {
MGLOG_W("MG_Remote client: the spawned server exited %d", exitCode);
}
}
Server::ServerLoopInstance().SetRemoteControlSink(nullptr, nullptr);
}
Wire::PipeWireEncoder& ClientSession::Encoder() { return m_encoder; }
@@ -871,11 +1389,10 @@ namespace MobileGL::MG_Remote::Client {
if (statusOut != nullptr) *statusOut = Wire::ReplySink::kStatusError;
if (replySizeOut != nullptr) *replySizeOut = 0;
if (!m_started) {
MGLOG_F("MGPipe: Fatal{NoClientSession, \"%s\"} - EmitAndWait on a session that has "
SessionFail(MGFatalFamily::NoClientSession, "MGPipe: Fatal{NoClientSession, \"%s\"} - EmitAndWait on a session that has "
"not started. There is no fall-through: a record that could not be emitted "
"is a verb that did not happen",
Wire::WireOpName(op));
std::abort();
}
// R-1's INVARIANT, AS A RUNTIME CHECK RATHER THAN A SENTENCE - but only while the
@@ -889,11 +1406,10 @@ namespace MobileGL::MG_Remote::Client {
// the fill quiescent during that apply). With the batch off, the original check
// stands as written.
if (MG_Config::Ipc.BatchWaits == 0 && ApplyThreadIsInsideApplier()) {
MGLOG_F("MGPipe: Fatal{BarrierViolation, \"%s\"} - the apply thread is inside the "
SessionFail(MGFatalFamily::BarrierViolation, "MGPipe: Fatal{BarrierViolation, \"%s\"} - the apply thread is inside the "
"applier while the GL thread is emitting. R-1 makes at most one of them "
"runnable, which is what keeps one process-wide gPipeInputs legal",
Wire::WireOpName(op));
std::abort();
}
Uint64 seq = m_encoder.EncodeRecord(op, payload, payloadBytes, tails, tailCount);
@@ -908,11 +1424,10 @@ namespace MobileGL::MG_Remote::Client {
const BarrierWaitScope waiting;
const auto wait = m_producer.WaitForCmdSpace(needed, kBarrierTimeoutMs);
if (wait != Transport::SessionWait::Reached) {
MGLOG_F("MGPipe: Fatal{RetirementWaitFailed, \"SEG_CMD\"} - %s needs %llu "
SessionFail(MGFatalFamily::RetirementWaitFailed, "MGPipe: Fatal{RetirementWaitFailed, \"SEG_CMD\"} - %s needs %llu "
"reclaimable bytes; the retirement wait ended on %s",
Wire::WireOpName(op), static_cast<unsigned long long>(needed),
wait == Transport::SessionWait::ShutDown ? "shutdown" : "timeout");
std::abort();
}
// P5e (ra, §2.6): EVERY WAIT EXIT DRAINS. The cmd-space wait is one of the two
// safety nets under run-ahead (the stage bell is the other), and a client parked
@@ -922,9 +1437,8 @@ namespace MobileGL::MG_Remote::Client {
DrainEventRing(m_events);
seq = m_encoder.EncodeRecord(op, payload, payloadBytes, tails, tailCount);
if (seq == Wire::kInvalidSeq) {
MGLOG_F("MGPipe: Fatal{RingOverrun, \"SEG_CMD\"} - %s refused after sufficient "
SessionFail(MGFatalFamily::RingOverrun, "MGPipe: Fatal{RingOverrun, \"SEG_CMD\"} - %s refused after sufficient "
"space retired", Wire::WireOpName(op));
std::abort();
}
}
@@ -1052,6 +1566,15 @@ namespace MobileGL::MG_Remote::Client {
const Transport::SessionWait wait =
WaitForAppliedBudget(m_producer, m_events, seq, waitBudgetMs);
if (wait == Transport::SessionWait::ShutDown) {
// `dl`: SHUTDOWN IS TWO DIFFERENT EVENTS AND ONLY ONE IS A DEVICE LOSS. Stop() kills
// this same bell to wake a parked applier, so an orderly exit arrives here too - and
// latching on Dead() alone would arm the device-lost flag on every clean teardown.
// PeerHungUp() is true only when a descriptor whose far end ONLY THE SERVER held
// reported hangup, which nothing this side can cause.
if (const Transport::Doorbell* bell = m_producer.SelfDoorbell();
bell != nullptr && bell->PeerHungUp()) {
LatchDeviceLost("the barrier woke on a peer that had hung up");
}
// The doorbell died: the server went away. The only thing that returns from a
// kWaitForever park, and therefore the only way a client blocked in the barrier
// survives a server that is gone. It is teardown, not a server fault - so the answer
@@ -1069,12 +1592,11 @@ namespace MobileGL::MG_Remote::Client {
return seq;
}
if (wait != Transport::SessionWait::Reached) {
MGLOG_F("MGPipe: Fatal{BarrierTimeout, \"%s\"} - appliedSeq did not reach %llu within "
SessionFail(MGFatalFamily::BarrierTimeout, "MGPipe: Fatal{BarrierTimeout, \"%s\"} - appliedSeq did not reach %llu within "
"%llu ms. A bounded wait is deliberate: a wedged CI job and a lost record look "
"identical from outside, and only one of them is a bug worth finding",
Wire::WireOpName(op), static_cast<unsigned long long>(seq),
static_cast<unsigned long long>(waitBudgetMs));
std::abort();
}
// THE REVERSE CHANNEL IS DRAINED HERE, and here is the only place it can be: under the
@@ -1101,11 +1623,10 @@ namespace MobileGL::MG_Remote::Client {
Uint64 replySize = 0;
Int32 status = Wire::ReplySink::kStatusError;
if (!ReadReply(seq, replyOut, replyBytes, &status, &replySize)) {
MGLOG_F("MGPipe: Fatal{ReplyMissing, \"%s\"} - seq %llu carries kReplySlot and the "
SessionFail(MGFatalFamily::ReplyMissing, "MGPipe: Fatal{ReplyMissing, \"%s\"} - seq %llu carries kReplySlot and the "
"server applied it, but its slot does not stamp that seq. The stamp is what "
"makes a wrong-slot read detectable rather than plausible (R-3)",
Wire::WireOpName(op), static_cast<unsigned long long>(seq));
std::abort();
}
if (statusOut != nullptr) *statusOut = status;
if (replySizeOut != nullptr) *replySizeOut = replySize;
@@ -1118,11 +1639,10 @@ namespace MobileGL::MG_Remote::Client {
// (R-5). A client that treated it as a failure would re-create ID-39 from the other
// side.
if (replyOut != nullptr && replySize > replyBytes) {
MGLOG_F("MGPipe: Fatal{ReplyTooLarge, \"%s\"} - the answer is %llu bytes and the "
SessionFail(MGFatalFamily::ReplyTooLarge, "MGPipe: Fatal{ReplyTooLarge, \"%s\"} - the answer is %llu bytes and the "
"caller offered %llu. P5 does not chunk a reply",
Wire::WireOpName(op), static_cast<unsigned long long>(replySize),
static_cast<unsigned long long>(replyBytes));
std::abort();
}
return seq;
}
@@ -1198,6 +1718,12 @@ namespace MobileGL::MG_Remote::Client {
const Transport::SessionWait wait =
WaitForAppliedBudget(m_producer, m_events, target, kBarrierTimeoutMs);
if (wait == Transport::SessionWait::ShutDown) {
// `dl`: the same two-events distinction the verb barrier makes. Only a peer that
// HUNG UP is a device loss; Stop() reaches this path too.
if (const Transport::Doorbell* bell = m_producer.SelfDoorbell();
bell != nullptr && bell->PeerHungUp()) {
LatchDeviceLost("a forced run-ahead wait woke on a peer that had hung up");
}
// The doorbell died: teardown, not a fault - the same answer EmitAndWaitTails
// gives, and for the same reason.
MGLOG_E("MG_Remote client: the forced wait for %s woke on a dead doorbell; the "
@@ -1205,12 +1731,11 @@ namespace MobileGL::MG_Remote::Client {
return;
}
if (wait != Transport::SessionWait::Reached) {
MGLOG_F("MGPipe: Fatal{BarrierTimeout, \"%s\"} - a forced run-ahead wait did not "
SessionFail(MGFatalFamily::BarrierTimeout, "MGPipe: Fatal{BarrierTimeout, \"%s\"} - a forced run-ahead wait did not "
"reach appliedSeq %llu within %u ms. The forced waits of CONTRACT-P5E §2.5 "
"are the points at which the client must be in step again, so a wedge here "
"is a wedge in the queue and not a slow frame",
why, static_cast<unsigned long long>(target), kBarrierTimeoutMs);
std::abort();
}
// EVERY WAIT EXIT DRAINS (§2.6). It is what the flow-control deadlock argument rests
// on: the server blocks only on a full event ring, the client blocks only on
@@ -1263,19 +1788,18 @@ namespace MobileGL::MG_Remote::Client {
if (wait != Transport::SessionWait::Reached) break;
Transport::RingControl* control = m_producer.Control();
if (control == nullptr ||
Transport::Watermark::Reached(control->presentAckSerial, awaited)) {
Transport::Watermark::Reached(control->Progress.presentAckSerial, awaited)) {
break;
}
DrainEventRing(m_events);
}
if (wait == Transport::SessionWait::TimedOut) {
MGLOG_F("MGPipe: Fatal{PresentCreditTimeout} - present %llu waited %u ms for "
SessionFail(MGFatalFamily::PresentCreditTimeout, "MGPipe: Fatal{PresentCreditTimeout} - present %llu waited %u ms for "
"swap %llu to come back with a credit of %u. The credit, never the "
"ring's bytes, is what paces a run-ahead client (CONTRACT-P5E §2.4), "
"so a credit that never returns is a server that stopped swapping",
static_cast<unsigned long long>(serial), kBarrierTimeoutMs,
static_cast<unsigned long long>(awaited), credit);
std::abort();
}
// ShutDown is teardown and returns: the present did not happen, the same answer
// the barrier gives on a dead doorbell.
@@ -1297,7 +1821,7 @@ namespace MobileGL::MG_Remote::Client {
// its own diagnostic; the client writes a different block and waits through appliedSeq.
Bool ClientSession::InBarrierWait() { return g_inBarrierWait; }
Bool ClientSession::ApplyThreadIsInsideApplier() {
if (MG_Pipe::MGPipeRoleSplitActive()) return g_roleInsideApplier;
if (MG_Pipe::MGPipeRoleSplitRehearsalActive()) return g_roleInsideApplier;
return g_applyThreadInsideApplier.load(std::memory_order_acquire);
}
@@ -1355,7 +1879,7 @@ namespace MobileGL::MG_Remote::Client {
// is exactly "no record is being applied" and not merely "not decoding".
if (isBarrieredFill && !ApplyThreadIsInsideApplier()) return;
if (Server::ServerLoop::OnApplyThread()) return; // the applier owns the block
MGLOG_F("MGPipe: Fatal{RoleViolation, \"gPipeInputs\"} - the GL thread touched "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"gPipeInputs\"} - the GL thread touched "
"gPipeInputs (%s) on a RUN-AHEAD session %s. With the client running ahead "
"the block is the server's to read for as long as ANY record is in flight "
"(CONTRACT-P5E §3), so the only legal GL-thread write is a barriered fill "
@@ -1364,7 +1888,6 @@ namespace MobileGL::MG_Remote::Client {
isBarrieredFill ? "in a barriered fill that did not first wait for the "
"applier to catch up"
: "outside a barriered fill");
std::abort();
}
// MOBILEGL_IPC_BATCH_WAITS=1 makes "the fill runs while the apply thread applies an
// earlier value record" the INTENDED shape: the fill writes only fields no record
@@ -1384,22 +1907,21 @@ namespace MobileGL::MG_Remote::Client {
// access in a shared library, and it must stay thread-local (see InBarrierWait's note
// above - a second GL thread would otherwise read the first one's wait as its own).
if (InBarrierWait()) return;
MGLOG_F("MGPipe: Fatal{RoleViolation, \"gPipeInputs\"} - the GL thread touched gPipeInputs "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"gPipeInputs\"} - the GL thread touched gPipeInputs "
"(%s) while the apply thread was inside the applier and this thread was not in a "
"barrier wait. R-1's barrier is the only thing that makes one process-wide "
"gPipeInputs legal (CONTRACT-P5 table 3); a touch in this window races the "
"applier's own reads of it",
surface);
std::abort();
}
void ClientSession::NoteApplyThreadEnteredApplier() {
g_roleInsideApplier = true;
if (!MG_Pipe::MGPipeRoleSplitActive())
if (!MG_Pipe::MGPipeRoleSplitRehearsalActive())
g_applyThreadInsideApplier.store(true, std::memory_order_release);
}
void ClientSession::NoteApplyThreadLeftApplier() {
g_roleInsideApplier = false;
if (!MG_Pipe::MGPipeRoleSplitActive())
if (!MG_Pipe::MGPipeRoleSplitRehearsalActive())
g_applyThreadInsideApplier.store(false, std::memory_order_release);
}
+91
View File
@@ -35,9 +35,13 @@
#pragma once
#include <Includes.h>
#include <atomic> // the device-lost latch is read off the GL thread
#include <Config.h>
#include <MG_Pipe/MGPipe.h>
#include "../Server/ServerSpawn.h"
#include "../Server/SurfaceControlFrame.h"
#include "../Transport/Doorbell.h"
#include "../Transport/EventRing.h"
#include "../Transport/ITransport.h"
@@ -45,6 +49,7 @@
#include "../Transport/Ring.h"
#include "../Transport/RoleMemory.h"
#include "../Transport/SessionRings.h"
#include "../Transport/SocketTransport.h"
#include "../Wire/PipeWireCodec.h"
#include "CapsMirror.h"
@@ -61,6 +66,36 @@ namespace MobileGL::MG_Remote::Client {
// Null until Start() succeeds; MG_Backend::Init() is the only caller of Start().
static ClientSession* Active();
// P6 `dl` (CONTRACT-P6 5.3). THE DEVICE-LOST LATCH, and the two words that matter are
// SESSION-SCOPED and LATCH: it is set at most once per session and never cleared, because
// a session whose server died has nothing left to recover into. MOBILEGL_IPC_RESPAWN is
// where the recovery would go and it is a named refusal until some stage writes it.
//
// SET FROM Doorbell::PeerHungUp(), NEVER FROM A TIMEOUT. 5.4's whole point is that slow
// and dead are different states and must be told apart without a threshold: under P5e
// run-ahead a server one frame behind is the INTENDED steady state, so a latch armed by a
// deadline would fire on a healthy session under load. The descriptor answers instead.
//
// The static form answers false whenever no session is active, so monolith and the pull
// build get the honest answer with no branch of their own.
static Bool DeviceLost();
// Arms the latch and says why, once. Safe to call repeatedly and from any thread; only
// the first call logs.
void LatchDeviceLost(const char* why);
// The bell this session parks on, for the `dl` red-once ONLY. A test cannot otherwise
// ask the question the latch turns on - "did the peer hang up" is a fact about a
// descriptor, and the pair of tests that pin D5c has to be able to kill a server and
// then watch this object, not a side effect three layers up.
Transport::Doorbell* SelfDoorbellForTest() { return m_producer.SelfDoorbell(); }
// CONTRACT-P6 4.3: THE PID THE SERVER STATED IN ITS Welcome, which is not the same fact
// as the pid this session's launcher recorded - that one is local knowledge, this one
// CROSSED THE WIRE. Under spawn they must agree and neither may be ours; under inproc
// the server states its own pid, which IS ours, and that is the honest answer there.
std::uint32_t PeerServerPid() const { return m_peerServerPid; }
~ClientSession();
// Builds the four segments, performs Hello/Welcome, takes the first CapsSnapshot, and
@@ -79,6 +114,41 @@ namespace MobileGL::MG_Remote::Client {
// come back as MOBILEGL_ERR_PROTOCOL_MISMATCH with the guard's own line. Not a second
// way to start a session: MG_Backend::Init() calls Start(), and nothing else may call
// this with a pair it did not just create.
// P6 `sm`: the spawn client's half. `transport` is this process's end of
// the control socket to an already-running server process; the two bell
// fds are this side's ends of the two bell pairs (ServerSpawn.h).
//
// It is the SAME handshake StartOverTransportPair runs, with three
// differences and no others: the server half happens in another process
// so there is no local Accept to call, the four segments arrive as
// descriptors over SCM_RIGHTS instead of being dup'ed from a local
// owner, and the bells are sockets rather than condvars. Everything
// below the attach - producer, reply pool, event ring, segment table,
// encoder - is byte for byte the inproc path, which is the property
// that makes "P6 is a transport swap" true of THIS function even though
// it is not true of the phase.
// `cp`: the remote control sink ServerLoop calls when the server is
// another process. Encode, send, wait for the SurfaceReply that carries
// OUR seq back.
static MobileGLResult RemoteControlSinkThunk(void* user, Server::SurfaceControlFrame& frame);
MobileGLResult RunRemoteSurfaceControlFrame(Server::SurfaceControlFrame& frame);
MobileGLResult FinishStartup(Transport::Doorbell* peerBell,
Transport::Doorbell* selfBell,
bool startApplyThreadHere);
// `transport` is this process's end of a connection to an ALREADY
// RUNNING server process. The two bells arrive over it, with the four
// segments, as SCM_RIGHTS offers - nothing here is inherited, because
// the two processes were started independently.
// P6: launch a server process and connect to it. The two are
// INDEPENDENT - the launcher hands over a rendezvous name and nothing
// else - so this is the same code path a client would use against a
// server that was already running when it started.
MobileGLResult StartSpawned();
MobileGLResult StartOverSocket(std::unique_ptr<Transport::SocketTransport> transport);
MobileGLResult StartOverTransportPair(std::unique_ptr<Transport::InProcessTransport> clientEnd,
std::unique_ptr<Transport::InProcessTransport> serverEnd);
@@ -352,6 +422,21 @@ namespace MobileGL::MG_Remote::Client {
Uint64 m_presentsSent = 0;
Uint64 m_presentCreditWaits = 0;
// sm: the spawn client owns ONE end and two bells. Held here rather
// than in the transport because which bell is "mine" is the session's
// knowledge, not the transport's - the same ruling as inproc's
// PeerDoorbell/SelfDoorbell split.
// cp: one control op at a time, and the client's own seq space.
std::mutex m_remoteControlMutex;
Uint64 m_remoteControlSeq = 0;
// The server we launched, if we launched one. Reaped in Stop().
Server::LaunchedServer m_spawned;
std::unique_ptr<Transport::SocketTransport> m_socketTransport;
std::unique_ptr<Transport::Doorbell> m_socketSelfBell;
std::unique_ptr<Transport::Doorbell> m_socketPeerBell;
std::unique_ptr<Transport::InProcessTransport> m_clientTransport;
std::unique_ptr<Transport::InProcessTransport> m_serverTransport;
Transport::SessionSegments m_shm;
@@ -361,6 +446,12 @@ namespace MobileGL::MG_Remote::Client {
Transport::ReplySlotPool m_replies;
Transport::ITransport* m_transport = nullptr;
Bool m_started = false;
// Written by whichever thread first notices the hangup - the GL thread in the barrier,
// or the event pump - and read by glGetGraphicsResetStatus on the GL thread.
std::atomic<bool> m_deviceLost{false};
// Welcome::serverPid, kept because §9.5's arm proof wants it and because a value that is
// only ever logged cannot be asserted on.
std::uint32_t m_peerServerPid = 0;
};
// One per process in P5, because P5 serves one context, and LEAKED AT EXIT like every other
+8 -14
View File
@@ -28,6 +28,7 @@
// regression re-committed at the transport layer.
#include "EmitTables.h"
#include <MG_Remote/FatalFunnel.h>
#include "ClientSession.h"
#include "GpuWritePending.h"
@@ -87,8 +88,7 @@ namespace MobileGL::MG_Remote::Client {
// The same shape as MGPipeInputPoisonFatal (generated/PipeFilled.inc:407-413): names the
// slot, live at every log level, aborts. Deliberately NOT MOBILEGL_ASSERT, which is
// inert in an INFO build - and INFO is what every device lane runs.
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"%s\"}", slot);
std::abort();
SessionFail(MGFatalFamily::UnmigratedVerb, "MGPipe: Fatal{UnmigratedVerb, \"%s\"}", slot);
}
namespace {
@@ -209,11 +209,10 @@ namespace MobileGL::MG_Remote::Client {
RequireClientTablesInstalled(slot);
ClientSession* session = ClientSession::Active();
if (session == nullptr) {
MGLOG_F("MGPipe: Fatal{NoClientSession, \"%s\"} - the remote emit table is "
SessionFail(MGFatalFamily::NoClientSession, "MGPipe: Fatal{NoClientSession, \"%s\"} - the remote emit table is "
"installed but no ClientSession is active. A slot may not fall through "
"to a driver this role does not have",
slot);
std::abort();
}
return *session;
}
@@ -836,11 +835,10 @@ namespace MobileGL::MG_Remote::Client {
// NOT a guess and not a zero-length reply. A format this build cannot size is a
// readback whose answer would be silently truncated, which is the one failure a
// picture comparison cannot see.
MGLOG_F("MGPipe: Fatal{UnsizedReadback, \"read_pixels\"} format=0x%04x type=0x%04x "
SessionFail(MGFatalFamily::UnsizedReadback, "MGPipe: Fatal{UnsizedReadback, \"read_pixels\"} format=0x%04x type=0x%04x "
"- the client must declare MGPReadbackInfo::DstSize and cannot size this "
"pair; P5's reduced path reads RGBA/UNSIGNED_BYTE",
static_cast<unsigned>(format), static_cast<unsigned>(type));
std::abort();
}
return static_cast<Uint64>(bytesPerPixel);
}
@@ -882,29 +880,25 @@ namespace MobileGL::MG_Remote::Client {
// an oversize reply, so the only failures left are a wrong status or a SHORT one.
void RequireReadbackReplyComplete(Int32 status, Uint64 replySize, Uint64 expected) {
if (status == Wire::ReplySink::kStatusError) {
MGLOG_F("MGPipe: Fatal{ReplyError, \"ReadPixels\"} - the readback answered ERROR; "
SessionFail(MGFatalFamily::ReplyError, "MGPipe: Fatal{ReplyError, \"ReadPixels\"} - the readback answered ERROR; "
"the destination is left untouched rather than filled with stale bytes");
std::abort();
}
if (status == Wire::ReplySink::kStatusDeclined) {
MGLOG_F("MGPipe: Fatal{ReadbackDeclined, \"ReadPixels\"} - the server has no "
SessionFail(MGFatalFamily::ReadbackDeclined, "MGPipe: Fatal{ReadbackDeclined, \"ReadPixels\"} - the server has no "
"GL.ReadPixels and DECLINED; a decline is a real answer for an acceptance "
"row (R-5) but a blocking readback has no pixels to return, so it is a "
"Fatal here rather than a buffer of stale bytes");
std::abort();
}
if (status != Wire::ReplySink::kStatusOk) {
MGLOG_F("MGPipe: Fatal{ReplyStatusInvalid, \"ReadPixels\"} - unknown reply status %d", status);
std::abort();
SessionFail(MGFatalFamily::ReplyStatusInvalid, "MGPipe: Fatal{ReplyStatusInvalid, \"ReadPixels\"} - unknown reply status %d", status);
}
if (replySize != expected) {
MGLOG_F("MGPipe: Fatal{ReadbackReplyShort, \"ReadPixels %llu < %llu\"} - the OK "
SessionFail(MGFatalFamily::ReadbackReplyShort, "MGPipe: Fatal{ReadbackReplyShort, \"ReadPixels %llu < %llu\"} - the OK "
"reply carried fewer bytes than the read's own DstSize (CONTRACT-P5 row "
"23's exact extent); the missing rows would otherwise be scattered as "
"whatever the destination held",
static_cast<unsigned long long>(replySize),
static_cast<unsigned long long>(expected));
std::abort();
}
}
@@ -7,6 +7,7 @@
// End of Source File Header
#include "GpuWritePending.h"
#include <MG_Remote/FatalFunnel.h>
#include "ClientSession.h"
// RunsAsTheServerRole: declared beside the wire emitters that need the same predicate, so this
@@ -252,12 +253,11 @@ namespace MobileGL::MG_Remote::Client {
// UnmigratedVerbFatal), and it is what gives the hole a red spelling before the
// transport arrives.
if (!buffer.HasOutstandingGpuWrite()) return;
MGLOG_F("MGPipe: Fatal{UnimplementedWritebackWait} - a ClientSession is active and buffer %u "
SessionFail(MGFatalFamily::UnimplementedWritebackWait, "MGPipe: Fatal{UnimplementedWritebackWait} - a ClientSession is active and buffer %u "
"still has an outstanding GPU write after its readback was emitted. The wait is "
"ClientSession::EmitAndWait's (R-3: the reply slot id IS the record seq); P5 package "
"b1 landed the third state and s1/c1 own the wait itself.",
buffer.GetExternalIndex());
std::abort();
}
} // namespace MobileGL::MG_Remote::Client
@@ -7,6 +7,7 @@
// End of Source File Header
#include "PersistentMapTracker.h"
#include <MG_Remote/FatalFunnel.h>
#include <MG_Pipe/MGPipeTypes.h>
#include <MG_State/GLState/BufferState/BufferObject.h>
@@ -640,9 +641,8 @@ namespace MobileGL::MG_Remote::Client {
void PersistentMapTracker::PushBlocksFor(BufferObject& buffer) {
if (!PushIsArmed()) return;
if (OnServerRole()) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"PushBlocksFor\"} - the persistent-map "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"PushBlocksFor\"} - the persistent-map "
"producer belongs to the client; the server consumes transported bytes");
std::abort();
}
PushBlocksForChecked(buffer);
}
@@ -856,9 +856,8 @@ namespace MobileGL::MG_Remote::Client {
void PersistentMapTracker::PushAllMembers() {
if (!PushIsArmed()) return;
if (OnServerRole()) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"PushAllMembers\"} - the persistent-map "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"PushAllMembers\"} - the persistent-map "
"producer belongs to the client; the server consumes transported bytes");
std::abort();
}
if (m_livePersistentMaps.empty()) return;
// Copied out first: PushBlocksFor can erase its own entry (a member that stopped
@@ -874,9 +873,8 @@ namespace MobileGL::MG_Remote::Client {
void PersistentMapTracker::PushDrawConsumers() {
if (!PushIsArmed()) return;
if (OnServerRole()) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"PushDrawConsumers\"} - the persistent-map "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"PushDrawConsumers\"} - the persistent-map "
"producer belongs to the client; the server consumes transported bytes");
std::abort();
}
if (m_livePersistentMaps.empty()) return;
// THE EPOCH SKIP, AND WHAT IT RESTS ON. A page of a tracked map is marked by
@@ -1047,16 +1045,23 @@ namespace MobileGL::MG_Remote::Client {
// map_persistent, so a mis-set run gets through EGL bring-up and a frame of setup
// first. Moving it to the parse means a knob-validity rule in ConfigLoader, which is
// c0's file; filed for the integrator rather than taken here.
// `dl` (CONTRACT-P6 5.2): THE FAMILY WORD THIS SITE NEVER CARRIED. a6 found two aborts
// under MG_Remote/ with no Fatal{ marker at all, so "the log stays verbatim" was not true
// of them and no family grep could see them - this is one. (The other, WireLog.cpp's, is
// the sanctioned funnel: every one of its callers passes a Fatal{ string of its own.)
if (tier <= 1) {
MGLOG_F("MGPipe: MOBILEGL_IPC_ADOPT_TIER=%u names adoption tier T%u, which P11 implements "
"and P5 does not; P5 runs at T2 (emulate) only.",
SessionFail(MGFatalFamily::UnimplementedAdoptTier,
"MGPipe: Fatal{UnimplementedAdoptTier, \"T%u\"} - MOBILEGL_IPC_ADOPT_TIER=%u "
"names an adoption tier P11 implements and P5 does not; P5 runs at T2 "
"(emulate) only.",
static_cast<unsigned>(tier), static_cast<unsigned>(tier));
} else {
MGLOG_F("MGPipe: MOBILEGL_IPC_ADOPT_TIER=%u is not an adoption tier; the only values are 0 "
"and 1 (P11) and 2 (emulate, the P5 default).",
static_cast<unsigned>(tier));
SessionFail(MGFatalFamily::UnimplementedAdoptTier,
"MGPipe: Fatal{UnimplementedAdoptTier, \"%u\"} - MOBILEGL_IPC_ADOPT_TIER=%u is "
"not an adoption tier; the only values are 0 and 1 (P11) and 2 (emulate, the "
"P5 default).",
static_cast<unsigned>(tier), static_cast<unsigned>(tier));
}
std::abort();
}
} // namespace MobileGL::MG_Remote::Client
+10 -18
View File
@@ -29,6 +29,7 @@
// before every `set_dynamic_state` - hundreds of times a frame, and each one a real record.
#include "WireTables.h"
#include <MG_Remote/FatalFunnel.h>
#if MOBILEGL_BUILD_DISAGGREGATED
@@ -113,11 +114,10 @@ namespace MobileGL::MG_Remote::Client {
RequireClientTablesInstalled(row);
ClientSession* session = ClientSession::Active();
if (session == nullptr) {
MGLOG_F("MGPipe: Fatal{NoClientSession, \"%s\"} - the client wire tables are "
SessionFail(MGFatalFamily::NoClientSession, "MGPipe: Fatal{NoClientSession, \"%s\"} - the client wire tables are "
"installed but no ClientSession is active. A row may not fall through to "
"a driver this role does not have",
row);
std::abort();
}
return *session;
}
@@ -129,12 +129,11 @@ namespace MobileGL::MG_Remote::Client {
MG_Pipe::MGPBlobRef StageRequired(ClientSession& session, const char* row,
const void* bytes, Uint64 count) {
if (bytes == nullptr || count == 0) {
MGLOG_F("MGPipe: Fatal{BlobMissing, \"%s\"} - the row's decoder requires a "
SessionFail(MGFatalFamily::BlobMissing, "MGPipe: Fatal{BlobMissing, \"%s\"} - the row's decoder requires a "
"declared blob and the call site handed over %llu bytes at %p. Under "
"monolith the companion pointer carries them; under split they have to "
"be staged, and there is nothing to stage",
row, static_cast<unsigned long long>(count), bytes);
std::abort();
}
return session.Encoder().StageBytes(bytes, count);
}
@@ -409,12 +408,11 @@ namespace MobileGL::MG_Remote::Client {
}
ClientSession& session = RequireSession("ResourceRespecify");
if (initialBytes != nullptr) {
MGLOG_F("MGPipe: Fatal{UncarriedInitialBytes, \"resource_respecify\"} - a call "
SessionFail(MGFatalFamily::UncarriedInitialBytes, "MGPipe: Fatal{UncarriedInitialBytes, \"resource_respecify\"} - a call "
"site handed initial content to a split respecify. R-13.3 rules that "
"initialBytes never crosses and that the content follows as "
"resource_subdata; a caller that still passes it has bytes nothing will "
"carry");
std::abort();
}
// The scope rides in the descriptor's own pads (CONTRACT-P5 table 1 row 19b, LANDED)
// and is written only through MGPipeSetRespecifiedLevel - three fields are one
@@ -438,10 +436,9 @@ namespace MobileGL::MG_Remote::Client {
// - the generated acceptance rows through MGPipeTakeReplyBool, and now these two
// escapes - answers ERROR with the same named Fatal.
if (status == 2) {
MGLOG_F("MGPipe: Fatal{ReplyError, \"resource_respecify\"} - the row answered "
SessionFail(MGFatalFamily::ReplyError, "MGPipe: Fatal{ReplyError, \"resource_respecify\"} - the row answered "
"ERROR, which is not an acceptance answer; folding it into accepted or "
"refused would make a transport fault look like a resource decision");
std::abort();
}
if (status == 1) ++g_declined;
return status == 0;
@@ -485,22 +482,20 @@ namespace MobileGL::MG_Remote::Client {
// the generated acceptance rows obey: status 2 is a transport fault, and returning
// nullptr for it would make it indistinguishable from R-6's legitimate decline.
if (status == 2) {
MGLOG_F("MGPipe: Fatal{ReplyError, \"map_persistent\"} - the row answered ERROR, "
SessionFail(MGFatalFamily::ReplyError, "MGPipe: Fatal{ReplyError, \"map_persistent\"} - the row answered ERROR, "
"which is not an acceptance answer; a transport fault is not a resource "
"decision and may not be folded into the decline R-6 predicts");
std::abort();
}
if (status == 1) ++g_declined;
// NOT "always nullptr": the answer is READ. R-6 says the server declines, and the
// day it stops declining this returns what it actually said rather than what the
// ruling predicted.
if (status == 0) {
MGLOG_F("MGPipe: Fatal{UnexpectedMapAccept, \"map_persistent\"} - the server "
SessionFail(MGFatalFamily::UnexpectedMapAccept, "MGPipe: Fatal{UnexpectedMapAccept, \"map_persistent\"} - the server "
"accepted a persistent map under split. R-6 makes the split answer a "
"constant decline because there is no way to hand a host pointer across "
"a process boundary in P5; a pointer arriving here is one this client "
"cannot dereference");
std::abort();
}
return nullptr;
}
@@ -522,12 +517,11 @@ namespace MobileGL::MG_Remote::Client {
}
ClientSession& session = RequireSession("CreateShaderState");
if (link == nullptr || spirv == nullptr) {
MGLOG_F("MGPipe: Fatal{ArtefactsMissing, \"create_shader_state\"} - the record's "
SessionFail(MGFatalFamily::ArtefactsMissing, "MGPipe: Fatal{ArtefactsMissing, \"create_shader_state\"} - the record's "
"two typed companions are null. Under monolith the applier reads the "
"modules out of spirv->generatedSpirv; under split there is nothing to "
"serialise, and emitting the record anyway would create a CSO with no "
"code");
std::abort();
}
// EncodeProgramArchive APPENDS and never fails - everything it walks is owned
// plain data - so an empty archive means the two structs themselves were empty,
@@ -547,9 +541,8 @@ namespace MobileGL::MG_Remote::Client {
static_cast<Uint64>(archive.size()));
}
if (archive.empty()) {
MGLOG_F("MGPipe: Fatal{ArchiveEmpty, \"create_shader_state\"} - the program's "
SessionFail(MGFatalFamily::ArchiveEmpty, "MGPipe: Fatal{ArchiveEmpty, \"create_shader_state\"} - the program's "
"artefacts serialised to nothing");
std::abort();
}
MG_Pipe::MGPProgramDesc record = *desc;
for (Uint32 i = 0; i < 6; ++i) record.Spirv[i] = MG_Pipe::MGPBlobRef{};
@@ -714,9 +707,8 @@ namespace MobileGL::MG_Remote::Client {
void RequireClientTablesInstalled(const char* row) {
if (g_clientTablesUninstalled.load(std::memory_order_acquire)) {
MGLOG_F("MGPipe: Fatal{ClientTablesUninstalled, \"%s\"} - the client tables are "
SessionFail(MGFatalFamily::ClientTablesUninstalled, "MGPipe: Fatal{ClientTablesUninstalled, \"%s\"} - the client tables are "
"being torn down; refusing before session or ring access", row);
std::abort();
}
}
+82
View File
@@ -0,0 +1,82 @@
// MobileGL - MobileGL/MG_Remote/FatalFamilies.def
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// P6 `dl` (CONTRACT-P6 5.2, D2 ruling). THE INTERNAL FATAL VOCABULARY, and its projection onto
// the SEVEN-value wire FatalCode.
//
// a6 censused 30 distinct family words against a 7-value wire enum, so Session::Fail(FatalCode,
// detail) cannot carry the vocabulary in its first argument - the word would collapse to one of
// seven and the log would say "ProtocolCorruption" where the code said "UnmigratedVerb". So the
// family is an INTERNAL enum, generated from this file, and the wire keeps FatalCode. Each row
// carries the coarse code the PEER is told when this family kills the session; the rich word
// stays in the local log and in the SessionFault frame's `family` string.
//
// THE PROJECTION IS A TOTAL TABLE, NOT A SWITCH WITH A DEFAULT. This build has no -Werror
// anywhere (measured: CMakeLists, every *.cmake, both workflows), so a gate premised on -Wswitch
// catching a missing arm is fiction. A row here IS the arm; a family with no row does not
// compile a call that names it.
//
// WHY EACH CODE. The wire FatalCode answers one question for the peer: what KIND of end was
// this. The buckets:
// ProtocolCorruption - the peer sent, or the session reached, something that cannot be
// honoured correctly: a malformed record, an unimplemented verb/surface,
// an invariant the roles must hold, a reply that does not fit its
// contract. The peer's takeaway is "we disagree about the protocol".
// RingOverrun - a shared ring or event channel overran. A transport-capacity fact.
// SegmentMismatch - a shared SEGMENT's geometry could not hold what a role needed to put
// in it. Distinct from a ring overrun: the segment is the wrong SIZE,
// not merely full this instant.
// AbiMismatch - the two builds do not agree on layout or protocol version.
// ServerCrashed - a liveness end the WAITING side attributes to the other: a drain that
// never completed, an apply thread that is gone or never started. The
// device-lost latch is armed from the doorbell, never from these, but the
// peer that was waiting is told the server is gone.
// DeviceLost - reserved: set by the latch (5.3), never raised as a Fatal family, so no
// row projects onto it.
//
// clang-format off
// X(Family, WireFatalCode, Why)
#define MGL_FATAL_FAMILY_LIST(X) \
X(ProtocolCorruption, ProtocolCorruption, "a record's bounds or self-describing length was violated") \
X(UnmigratedVerb, ProtocolCorruption, "a wire verb slot P5/P6 does not implement was reached") \
X(UnmigratedSurface, ProtocolCorruption, "a surface op named a client-process handle that means nothing here (P12)") \
X(UnmigratedPipeInput, ProtocolCorruption, "a PipeInputs field with no field-ownership row was read across the boundary") \
X(RoleViolation, ProtocolCorruption, "a call ran on the wrong role/thread - an invariant the two roles must hold") \
X(UnsetCallMask, ProtocolCorruption, "the CallMask was consulted before either half was published") \
X(ClientTablesUninstalled, ProtocolCorruption, "the applier ran before the client installed its tables") \
X(NoClientSession, ProtocolCorruption, "a path that needs the client session ran without one") \
X(UnexpectedMapAccept, ProtocolCorruption, "a persistent-map accept arrived where the protocol permits none") \
X(UncarriedInitialBytes, ProtocolCorruption, "a producer's initial bytes were required on the wire and absent") \
X(ReplyStatusInvalid, ProtocolCorruption, "a reply carried a status outside the defined set") \
X(ReplyError, ProtocolCorruption, "a reply-owning verb saw an error status it cannot represent") \
X(ReplyMissing, ProtocolCorruption, "a reply slot the protocol requires was empty") \
X(ReplyTooLarge, ProtocolCorruption, "an answer exceeded the size its verb's contract allows") \
X(ReadbackDeclined, ProtocolCorruption, "a readback that cannot return without complete pixels was declined") \
X(ReadbackReplyShort, ProtocolCorruption, "a readback reply carried fewer bytes than its shape requires") \
X(UnsizedReadback, ProtocolCorruption, "a readback arrived with no declared size") \
X(BlobMissing, ProtocolCorruption, "a record named a blob that was never staged") \
X(BlobNotStaged, ProtocolCorruption, "a blob was referenced before its staging completed") \
X(ArtefactsMissing, ProtocolCorruption, "a program create arrived with no artefacts") \
X(ArchiveEmpty, ProtocolCorruption, "a create_*_state archive carried no payload") \
X(BarrierViolation, ProtocolCorruption, "a field was pulled across a verb boundary the barrier forbids") \
X(UnimplementedAdoptTier, ProtocolCorruption, "MOBILEGL_IPC_ADOPT_TIER named a tier P5 does not implement") \
X(UnimplementedWritebackWait, ProtocolCorruption, "a writeback wait shape P5 does not implement was requested") \
X(UnimplementedRemoteBackendObject, ProtocolCorruption, "a BackendObject_Remote entry point P5 does not implement was called") \
X(UnimplementedClientSession, ProtocolCorruption, "a ClientSession entry point P5 does not implement was called") \
X(RingOverrun, RingOverrun, "a shared ring refused a record after sufficient space had retired") \
X(EventRingOverflow, RingOverrun, "the reverse event ring overflowed") \
X(StageSnapshotTooNarrow, SegmentMismatch, "SEG_STAGE was too small for a snapshot a verb had to place in it") \
X(AbiMismatch, AbiMismatch, "the two builds disagree on struct layout or protocol version") \
X(BarrierTimeout, ServerCrashed, "appliedSeq did not reach the target within the bounded wait") \
X(PresentCreditTimeout, ServerCrashed, "a present credit did not return within the bounded wait") \
X(RetirementWaitFailed, ServerCrashed, "a wait for the server to retire staging did not complete") \
X(ApplyThreadJoinTimeout, ServerCrashed, "the apply thread did not join within its bound at teardown") \
X(ApplyThreadNotRunning, ServerCrashed, "an operation needed the apply thread and it was not running")
// clang-format on
+68
View File
@@ -0,0 +1,68 @@
// MobileGL - MobileGL/MG_Remote/FatalFamily.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// P6 `dl` (CONTRACT-P6 5.2). The internal Fatal vocabulary and its total projection onto the
// wire FatalCode, both generated from FatalFamilies.def so a family, its name and its wire code
// cannot drift apart: adding a family is one row, and a row that forgets its code does not
// compile.
#pragma once
#include <MG_Remote/Protocol/generated/protocol_generated.h>
#include "FatalFamilies.def"
namespace MobileGL::MG_Remote {
// One value per row of FatalFamilies.def, in file order. The names ARE the family words that
// appear in every `Fatal{...}` log line, which is what lets FatalFamilyName round-trip
// against the string a site passes.
enum class MGFatalFamily : ::std::uint32_t {
#define X(Family, WireCode, Why) Family,
MGL_FATAL_FAMILY_LIST(X)
#undef X
};
// THE PROJECTION, AS A TOTAL TABLE. Not a switch with a default arm: this build has no
// -Werror, so a default would silently swallow a family added without a code. Every family
// that exists has a row, and a family that does not exist is not a value of the enum.
inline ::MobileGL::Wire::FatalCode FatalCodeForFamily(MGFatalFamily family) {
switch (family) {
#define X(Family, WireCode, Why) \
case MGFatalFamily::Family: return ::MobileGL::Wire::FatalCode::WireCode;
MGL_FATAL_FAMILY_LIST(X)
#undef X
}
// Unreachable for any real enum value; kept so the function is total for the compiler
// without a `default:` that would mask a missing row.
return ::MobileGL::Wire::FatalCode::ProtocolCorruption;
}
// The family's own word, byte-for-byte what appears inside `Fatal{<name>, ...}`. A death
// site passes both the enum and its full message string; a test asserts this name is present
// in that string, which is what keeps the two from diverging.
inline const char* FatalFamilyName(MGFatalFamily family) {
switch (family) {
#define X(Family, WireCode, Why) \
case MGFatalFamily::Family: return #Family;
MGL_FATAL_FAMILY_LIST(X)
#undef X
}
return "<unknown>";
}
// The count, for a test that walks every family.
inline constexpr ::std::size_t MGFatalFamilyCount() {
::std::size_t n = 0;
#define X(Family, WireCode, Why) ++n;
MGL_FATAL_FAMILY_LIST(X)
#undef X
return n;
}
} // namespace MobileGL::MG_Remote
+96
View File
@@ -0,0 +1,96 @@
// MobileGL - MobileGL/MG_Remote/FatalFunnel.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include <MG_Remote/FatalFunnel.h>
#include "../Includes.h" // MGLOG_F and the umbrella; a .cpp may pull it, a Transport/ header may not
#include "Client/ClientSession.h"
#include "Protocol/generated/protocol_generated.h"
#include "Server/ServerSession.h"
#include "Transport/ITransport.h"
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <flatbuffers/flatbuffers.h>
namespace MobileGL::MG_Remote {
namespace {
// One telemetry point (5.2). Bumped exactly once per death, before the abort, so a test
// that forks a child and reads it back sees the increment even though the child is gone -
// it reads its OWN process's counter for the funnel it drove, not the child's.
std::atomic<std::uint64_t> g_sessionFaultCount{0};
} // namespace
std::uint64_t SessionFaultCount() {
return g_sessionFaultCount.load(std::memory_order_relaxed);
}
void SessionFail(MGFatalFamily family, const char* fmt, ...) {
// The line, formatted exactly as the site's old MGLOG_F would have. Same buffer size and
// same fallback as WireLogFatal, so a death that used either path reads identically.
char line[512];
va_list args;
va_start(args, fmt);
const int written = std::vsnprintf(line, sizeof(line), fmt, args);
va_end(args);
if (written < 0) {
std::snprintf(line, sizeof(line),
"MG_Remote: unformattable Fatal diagnostic (format=%s)", fmt);
}
g_sessionFaultCount.fetch_add(1, std::memory_order_relaxed);
MGLOG_F("%s", line);
// The stderr echo is the half a death test can see: Defines.h builds the logger with the
// console sink off, so an MGLOG line reaches only the file - and a gtest death matcher
// reads the child's stderr. Flushed because abort() does not flush stdio.
std::fputs(line, stderr);
std::fputc('\n', stderr);
std::fflush(stderr);
// A SessionFault frame to the peer, BEFORE the abort, so the other side's log names the
// family instead of reading a bare EOF (5.2). Best-effort by nature: this thread is about
// to die, so a send that blocks or fails changes nothing it could have changed anyway.
//
// WHICHEVER ROLE THIS PROCESS IS. Under spawn only one session is active per process -
// the client has ClientSession, the server has ServerSession - so publishing on whatever
// control plane exists reaches the far side. Under inproc both exist and the frame goes
// to an in-process transport the aborting process will never read; harmless, and not
// worth a special case that would then be the untested one.
//
// `code` is the coarse seven-value projection; `family` carries the full word; `message`
// is the same line just logged. seq/op are not threaded through the 90 call sites and the
// message already names the op where it matters, so the frame carries what it can name
// honestly rather than a field that is always zero.
Transport::ITransport* control = nullptr;
if (Client::ClientSession* client = Client::ClientSession::Active()) {
control = client->Control_Plane();
}
if (control == nullptr) {
if (Server::ServerSession* server = Server::ServerSession::Active()) {
control = server->Control_Plane();
}
}
if (control != nullptr) {
::flatbuffers::FlatBufferBuilder builder(256);
const auto fatal = ::MobileGL::Wire::CreateFatalDirect(
builder, FatalCodeForFamily(family), line, FatalFamilyName(family));
const auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
builder, ::MobileGL::Wire::CtrlMsg::Fatal, fatal.Union());
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
(void)control->SendFrame(
MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()});
}
std::abort();
}
} // namespace MobileGL::MG_Remote
+50
View File
@@ -0,0 +1,50 @@
// MobileGL - MobileGL/MG_Remote/FatalFunnel.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// P6 `dl` (CONTRACT-P6 5.2). THE ONE PLACE A SESSION DIES.
//
// Every `Fatal{...}` under MG_Remote/ used to be an MGLOG_F followed by its own std::abort().
// a6 counted ~92 of them. Scattered, they gave the funnel's three benefits to nobody: there was
// no single place to publish a SessionFault to the peer before dying, no single telemetry point,
// and no way for a census to be sure a new death was named. This is that place.
//
// THE MESSAGE STRING IS PASSED VERBATIM, family word and all. The contract requires the log
// lines, the CI greps and every red-once to be byte-identical, so SessionFail does not compose
// the line from the family - it takes the SAME string the site used to hand MGLOG_F and forwards
// it unchanged. The family enum rides ALONGSIDE, redundantly, so the funnel knows the coarse wire
// FatalCode without parsing the string; a test asserts the enum's name appears in the string, so
// the redundancy cannot rot into disagreement.
//
// NOT in WireLog.h: that header is deliberately dependency-light (ITransport.h's rule, the
// include-graph purity gate), and this needs FatalFamily.h, which pulls the protocol header. The
// header-layer sites that must stay pure keep using WireLogFatal, whose own abort routes through
// the same publisher in WireLog.cpp.
#pragma once
#include <MG_Remote/FatalFamily.h>
#include <cstdint>
namespace MobileGL::MG_Remote {
// Logs the line (byte-identical to the old MGLOG_F), echoes it to stderr so a death test can
// see it, publishes a SessionFault{family, ...} to the peer if one is connected, bumps the
// telemetry counter, and aborts. `fmt` is the FULL original message, e.g.
// "MGPipe: Fatal{RingOverrun, \"SEG_CMD\"} - %s ...".
[[noreturn]]
#if defined(__GNUC__) || defined(__clang__)
__attribute__((format(printf, 2, 3)))
#endif
void SessionFail(MGFatalFamily family, const char* fmt, ...);
// How many times a session has ended through the funnel this process. Exit gate S8 asserts
// this is zero over a whole good run; a test reads it to prove the funnel was reached.
::std::uint64_t SessionFaultCount();
} // namespace MobileGL::MG_Remote
+17 -6
View File
@@ -7,6 +7,7 @@
// End of Source File Header
#include "SurfaceOpCodec.h"
#include <MG_Remote/FatalFunnel.h>
#include <MG_Backend/BackendObject.h>
#include <MG_Remote/Protocol/generated/protocol_generated.h>
@@ -47,9 +48,13 @@ namespace MobileGL::MG_Remote {
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::ReleaseResources));
static_assert(static_cast<Uint8>(SurfaceControlOp::SetWindowHandle) ==
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::SetWindowHandle));
// cp's one schema addition, on the same append-only terms.
static_assert(static_cast<Uint8>(SurfaceControlOp::InitCapabilities) ==
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::InitCapabilities));
static_assert(static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::SetSwapInterval) == 8 &&
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::ReleaseResources) == 9 &&
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::SetWindowHandle) == 10);
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::SetWindowHandle) == 10 &&
static_cast<Uint8>(::MobileGL::Wire::SurfaceOpKind::InitCapabilities) == 11);
static_assert(static_cast<Uint8>(::MobileGL::Wire::WindowKind::MetalLayer) == 6);
bool OpNeedsAWindowBackend(SurfaceControlOp op) {
@@ -80,8 +85,12 @@ namespace MobileGL::MG_Remote {
}
bool SurfaceControlOpForWireKind(::MobileGL::Wire::SurfaceOpKind kind, SurfaceControlOp* out) {
// THE UPPER BOUND IS THE LAST APPENDED KIND, and it moves with every
// append or the new tag decodes as out-of-range - which reads as
// Fatal{ProtocolCorruption} at ServerApplyWireSurfaceOp rather than as
// the missing row it is.
if (::flatbuffers::IsOutRange(kind, ::MobileGL::Wire::SurfaceOpKind::InitializeDisplay,
::MobileGL::Wire::SurfaceOpKind::SetWindowHandle)) {
::MobileGL::Wire::SurfaceOpKind::InitCapabilities)) {
return false;
}
const SurfaceControlOp op = static_cast<SurfaceControlOp>(static_cast<Uint8>(kind));
@@ -199,22 +208,24 @@ namespace MobileGL::MG_Remote {
const SurfaceWireError error = DecodeWireSurfaceOp(op, &frame);
if (error != SurfaceWireError::None) {
if (error == SurfaceWireError::AndroidNativeWindowArrived) {
MGLOG_F("MGPipe: Fatal{UnmigratedSurface, \"AndroidNativeWindow@P12\"} - a wire "
SessionFail(MGFatalFamily::UnmigratedSurface,
"MGPipe: Fatal{UnmigratedSurface, \"AndroidNativeWindow@P12\"} - a wire "
"SurfaceOp (%s) named an ANativeWindow*, which is a pointer into the "
"CLIENT's process and means nothing here. Real window arrival is P12; "
"until then the spawn surface path is pbuffer/surfaceless only",
::MobileGL::Wire::EnumNameSurfaceOpKind(op.kind()));
} else if (error == SurfaceWireError::MetalLayerArrived) {
MGLOG_F("MGPipe: Fatal{UnmigratedSurface, \"MetalLayer@P12\"} - a wire "
SessionFail(MGFatalFamily::UnmigratedSurface,
"MGPipe: Fatal{UnmigratedSurface, \"MetalLayer@P12\"} - a wire "
"SurfaceOp named a CAMetalLayer* in the CLIENT's process. "
"Real window arrival is P12");
} else {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp\"} - a wire surface op "
SessionFail(MGFatalFamily::ProtocolCorruption,
"MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp\"} - a wire surface op "
"failed validation: %s (wire kind %u, window kind %u)",
SurfaceWireErrorName(error), static_cast<unsigned>(op.kind()),
static_cast<unsigned>(op.windowKind()));
}
std::abort();
}
const MobileGLResult rc = Server::ServerLoopInstance().RunSurfaceControlFrame(frame);
if (replyOut != nullptr) *replyOut = frame;
@@ -125,11 +125,12 @@ enum class SurfaceOpKind : uint8_t {
SetSwapInterval = 8,
ReleaseResources = 9,
SetWindowHandle = 10,
InitCapabilities = 11,
MIN = None,
MAX = SetWindowHandle
MAX = InitCapabilities
};
inline const SurfaceOpKind (&EnumValuesSurfaceOpKind())[11] {
inline const SurfaceOpKind (&EnumValuesSurfaceOpKind())[12] {
static const SurfaceOpKind values[] = {
SurfaceOpKind::None,
SurfaceOpKind::InitializeDisplay,
@@ -141,13 +142,14 @@ inline const SurfaceOpKind (&EnumValuesSurfaceOpKind())[11] {
SurfaceOpKind::ReleaseCurrent,
SurfaceOpKind::SetSwapInterval,
SurfaceOpKind::ReleaseResources,
SurfaceOpKind::SetWindowHandle
SurfaceOpKind::SetWindowHandle,
SurfaceOpKind::InitCapabilities
};
return values;
}
inline const char * const *EnumNamesSurfaceOpKind() {
static const char * const names[12] = {
static const char * const names[13] = {
"None",
"InitializeDisplay",
"CreateWindowSurface",
@@ -159,13 +161,14 @@ inline const char * const *EnumNamesSurfaceOpKind() {
"SetSwapInterval",
"ReleaseResources",
"SetWindowHandle",
"InitCapabilities",
nullptr
};
return names;
}
inline const char *EnumNameSurfaceOpKind(SurfaceOpKind e) {
if (::flatbuffers::IsOutRange(e, SurfaceOpKind::None, SurfaceOpKind::SetWindowHandle)) return "";
if (::flatbuffers::IsOutRange(e, SurfaceOpKind::None, SurfaceOpKind::InitCapabilities)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesSurfaceOpKind()[index];
}
@@ -1460,7 +1463,8 @@ struct Fatal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
struct Traits;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_CODE = 4,
VT_MESSAGE = 6
VT_MESSAGE = 6,
VT_FAMILY = 8
};
MobileGL::Wire::FatalCode code() const {
return static_cast<MobileGL::Wire::FatalCode>(GetField<uint32_t>(VT_CODE, 0));
@@ -1468,12 +1472,17 @@ struct Fatal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
const ::flatbuffers::String *message() const {
return GetPointer<const ::flatbuffers::String *>(VT_MESSAGE);
}
const ::flatbuffers::String *family() const {
return GetPointer<const ::flatbuffers::String *>(VT_FAMILY);
}
template <bool B = false>
bool Verify(::flatbuffers::VerifierTemplate<B> &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<uint32_t>(verifier, VT_CODE, 4) &&
VerifyOffset(verifier, VT_MESSAGE) &&
verifier.VerifyString(message()) &&
VerifyOffset(verifier, VT_FAMILY) &&
verifier.VerifyString(family()) &&
verifier.EndTable();
}
};
@@ -1488,6 +1497,9 @@ struct FatalBuilder {
void add_message(::flatbuffers::Offset<::flatbuffers::String> message) {
fbb_.AddOffset(Fatal::VT_MESSAGE, message);
}
void add_family(::flatbuffers::Offset<::flatbuffers::String> family) {
fbb_.AddOffset(Fatal::VT_FAMILY, family);
}
explicit FatalBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@@ -1502,8 +1514,10 @@ struct FatalBuilder {
inline ::flatbuffers::Offset<Fatal> CreateFatal(
::flatbuffers::FlatBufferBuilder &_fbb,
MobileGL::Wire::FatalCode code = MobileGL::Wire::FatalCode::None,
::flatbuffers::Offset<::flatbuffers::String> message = 0) {
::flatbuffers::Offset<::flatbuffers::String> message = 0,
::flatbuffers::Offset<::flatbuffers::String> family = 0) {
FatalBuilder builder_(_fbb);
builder_.add_family(family);
builder_.add_message(message);
builder_.add_code(code);
return builder_.Finish();
@@ -1517,12 +1531,15 @@ struct Fatal::Traits {
inline ::flatbuffers::Offset<Fatal> CreateFatalDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
MobileGL::Wire::FatalCode code = MobileGL::Wire::FatalCode::None,
const char *message = nullptr) {
const char *message = nullptr,
const char *family = nullptr) {
auto message__ = message ? _fbb.CreateString(message) : 0;
auto family__ = family ? _fbb.CreateString(family) : 0;
return MobileGL::Wire::CreateFatal(
_fbb,
code,
message__);
message__,
family__);
}
struct LogLine FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
+11
View File
@@ -176,6 +176,12 @@ enum SurfaceOpKind : ubyte {
SetSwapInterval = 8,
ReleaseResources = 9,
SetWindowHandle = 10,
// P6 (package cp) appended this one. The draft held that InitCapabilities needs
// no wire form because "the CapsSnapshot answers it" - but a CapsSnapshot is the
// ANSWER and this is the REQUEST, and a spawn client has a live caller for it
// (Client/BackendObject_Remote.cpp). Without the tag the codec refused it by
// name and every spawned eglMakeCurrent failed with InprocOnlyOpOnTheWire.
InitCapabilities = 11,
}
enum WindowKind : ubyte {
@@ -258,6 +264,11 @@ enum FatalCode : uint {
table Fatal {
code: FatalCode;
message: string;
// P6 dl (CONTRACT-P6 5.2, D2). The internal MGFatalFamily word, so a peer that receives this
// frame before the sender aborts can name WHICH family ended the session instead of reading a
// bare EOF. `code` stays the coarse seven-value projection; this carries the full vocabulary.
// Append-only: an older peer that does not read it still gets `code` and `message`.
family: string;
}
// Severity-graded per plan B section 8.2: <= Warn is lossy, >= Error is
+11 -20
View File
@@ -9,6 +9,7 @@
// P5 package v1: the applier bridge, and the consumer for contract 7's five class-B verbs.
#include "PipeApplier.h"
#include <MG_Remote/FatalFunnel.h>
#include "ServerSession.h"
#include "../Transport/ReplySlot.h"
@@ -326,11 +327,10 @@ namespace MobileGL::MG_Remote::Server {
// is a protocol fault, because such a client is pacing on this answer and a 0 would
// acknowledge a frame nobody asked about.
if (present.FrameSerial == 0 && MGPipeServerPublishesRunAhead()) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"Present.FrameSerial\"} - a run-ahead "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"Present.FrameSerial\"} - a run-ahead "
"server was handed present serial 0. The client mints this 1-based and "
"waits on it for its credit (CONTRACT-P5E §2.4); returning a credit for "
"serial 0 would release a wait that is asking about frame N");
std::abort();
}
m_lastPresentSerial = present.FrameSerial != 0 ? present.FrameSerial : m_presents;
// §2.4's other half, and the reason ServerSession::ReturnPresentCredit has had no
@@ -385,11 +385,10 @@ namespace MobileGL::MG_Remote::Server {
// The decoder always passes its ReplySink; a null one means the applier was built
// without a reply pool, and answering nothing would leave the client's barrier
// waiting for a slot that never gets stamped - a hang, not a wrong picture.
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"read_pixels without a reply sink\"} - "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"read_pixels without a reply sink\"} - "
"the pixels' only destination in P5 is SEG_REPLY (contract table 1 row 23) "
"and a client blocked on seq %llu would never be answered",
static_cast<unsigned long long>(seq));
std::abort();
}
const MG_Backend::GlobalBackendFunctionsTable* table = Table("read_pixels");
if (table == nullptr || table->GL.ReadPixels == nullptr) {
@@ -482,10 +481,9 @@ namespace MobileGL::MG_Remote::Server {
// rather than rendering nothing. Named "(server sink)" in the message so a log reader can
// tell which half is missing.
[[noreturn]] static void ServerUnmigratedVerbFatal(const char* slot) {
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"%s\"} (server sink: the record crossed and "
SessionFail(MGFatalFamily::UnmigratedVerb, "MGPipe: Fatal{UnmigratedVerb, \"%s\"} (server sink: the record crossed and "
"ServerVerbSink has no body for it yet - CONTRACT-P5B.md names the package)",
slot);
std::abort();
}
// P5b d1 (MG_Remote/CONTRACT-P5B.md §2 d1): draw_vbo's whole cross product. The record
@@ -553,22 +551,20 @@ namespace MobileGL::MG_Remote::Server {
if (maxTouched < 0) return;
const Uint32 required = static_cast<Uint32>(maxTouched) + 1u;
if (st.SamplerViewStart != 0 || st.SamplerViewCount < required) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"SetSamplerViews.Count\"} - %s applies with "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"SetSamplerViews.Count\"} - %s applies with "
"units 0..%d touched, so set_sampler_views must carry Start=0 and Count >= %u "
"(CONTRACT-P5E.md §5.3); the applied window is Start=%u Count=%u, which drops "
"the sync of at least one texture this draw samples",
verb, static_cast<int>(maxTouched), required, st.SamplerViewStart,
st.SamplerViewCount);
std::abort();
}
if (st.SamplerStateStart != 0 || st.SamplerStateCount < required) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"BindSamplerStates.Count\"} - %s applies with "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"BindSamplerStates.Count\"} - %s applies with "
"units 0..%d touched, so bind_sampler_states must carry Start=0 and Count >= %u "
"(CONTRACT-P5E.md §5.3); the applied window is Start=%u Count=%u, which leaves "
"an earlier draw's sampler object on at least one unit",
verb, static_cast<int>(maxTouched), required, st.SamplerStateStart,
st.SamplerStateCount);
std::abort();
}
}
} // namespace
@@ -1147,13 +1143,12 @@ namespace MobileGL::MG_Remote::Server {
// accepted resets IS the expected value; anything else means the two ends disagree
// about how many make-current edges have crossed, which no backend answer can fix.
if (reset.ContextSerial != m_applierResetSerial) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ApplierReset.ContextSerial\"} - the "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ApplierReset.ContextSerial\"} - the "
"record carries %llu and this session has accepted %llu reset(s); the "
"serial is asserted against the session's own count, not dispatched on "
"(one context per session in P5c)",
static_cast<unsigned long long>(reset.ContextSerial),
static_cast<unsigned long long>(m_applierResetSerial));
std::abort();
}
++m_applierResetSerial;
// THE WHOLE POINT OF THE RECORD: the reset runs HERE, on the apply thread, against
@@ -1170,16 +1165,14 @@ namespace MobileGL::MG_Remote::Server {
// emits NOTHING in that case (§5.2) - so a null handle arriving here is corruption,
// not a no-op.
if (MG_Pipe::MGPipeHandleIsNull(death.Handle)) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Handle\"} - a null "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Handle\"} - a null "
"handle never crosses: the client emits nothing for an object its own "
"allocator cannot resolve (CONTRACT-P5C.md §5.2)");
std::abort();
}
if (death.Kind >= static_cast<Uint32>(MG_Pipe::MGPipeKind::KindCount)) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Kind\"} - %u is not an "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ObjectDeath.Kind\"} - %u is not an "
"MGPipeKind",
static_cast<unsigned>(death.Kind));
std::abort();
}
// The per-kind release, keyed by the handle the record carried. A false answer is
// NOT a decline: the kind's own delete opcode may already have released the twin
@@ -1201,10 +1194,9 @@ namespace MobileGL::MG_Remote::Server {
void PipeApplier::Attach(Transport::RingControl* control, MG_Backend::BackendObject* backend) {
if (control == nullptr || m_segments == nullptr) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::Attach\"} - no control "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::Attach\"} - no control "
"page or no segment table; ServerSession::Accept builds both before the "
"apply thread starts");
std::abort();
}
m_verbs.SetBackend(backend);
m_decoder = Wire::PipeWireDecoder(control, m_segments, m_replies);
@@ -1228,10 +1220,9 @@ namespace MobileGL::MG_Remote::Server {
Bool PipeApplier::ApplyOne(const Transport::RingRecordView& record) {
if (!m_attached) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::ApplyOne before Attach\"} "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"PipeApplier::ApplyOne before Attach\"} "
"- a record reached the applier with no decoder; the apply thread calls "
"Attach once before its first pop");
std::abort();
}
// R-1's INVARIANT, THE SERVER'S HALF (table 3's gPipeInputs row, c1-v1 8.1). The flag
// is raised for the WHOLE of this function and not only around DecodeAndApply: the
+19
View File
@@ -0,0 +1,19 @@
// MobileGL - MobileGL/MG_Remote/Server/ServerEntry.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// The server image's main(). Package `sm`.
//
// Deliberately the smallest thing that can be one: everything it could do
// belongs to mobilegl_server_main, which lives IN THE LIBRARY so that one
// shared library serves both roles (ARCHITECTURE.md:496). Keeping this file
// empty of logic is what stops the server growing a second, divergent copy of
// bring-up that the client half never executes.
extern "C" int mobilegl_server_main(int argc, char** argv);
int main(int argc, char** argv) { return mobilegl_server_main(argc, argv); }
+27 -14
View File
@@ -9,6 +9,7 @@
// P5 package v1: the apply thread, its affinity, its parking, and the EGL ownership move.
#include "ServerLoop.h"
#include <MG_Remote/FatalFunnel.h>
#include <MG_Backend/MGPipe/PipeInputs.h>
#include <Config.h>
@@ -343,6 +344,10 @@ namespace MobileGL::MG_Remote::Server {
// declaration: it is an identity, not a handshake, and this thread is the only writer.
Detail::g_applyThreadKey.store(Detail::CurrentThreadKey(), std::memory_order_relaxed);
NameThisThread("mgl-srv-apply");
// P6: THIS THREAD IS THE SERVER, and saying so is what sends its lines to the server's
// own log. Under spawn the process role already answers this; under INPROC it is the
// only thing that can, because the client role is another thread of this same process.
MG_Util::Debug::SetThreadLogRole(MG_Util::Debug::LogRole::Server);
Bool recognised = true;
const char* raw = AffinityStringFromConfig();
@@ -618,10 +623,9 @@ namespace MobileGL::MG_Remote::Server {
// Ring.h's own rule: a header the producer could not have written is
// Fatal{ProtocolCorruption}, never a retry. Retrying re-reads the same bytes
// for ever; skipping desynchronises seq, and seq IS the reply-slot id.
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"SEG_CMD record header\"} - the "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"SEG_CMD record header\"} - the "
"consumer refused a record header at applied seq %llu",
static_cast<unsigned long long>(consumer.AppliedSeq()));
std::abort();
}
if (!popped) break;
++applied;
@@ -632,13 +636,12 @@ namespace MobileGL::MG_Remote::Server {
// and PipeWireDecoder keeps its own count; a batched publish would move one and not
// the other, which a single counter could not have told apart (w1-v1 5).
if (applier.DecoderAppliedSeq() != consumer.AppliedSeq()) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"appliedSeq batched\"} - the "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"appliedSeq batched\"} - the "
"session's watermark is %llu and the decoder applied %llu records. P5 "
"forbids batching appliedSeq (R-9): the verb barrier's waiter reads it, "
"and a watermark ahead of the decoder promises work that has not run",
static_cast<unsigned long long>(consumer.AppliedSeq()),
static_cast<unsigned long long>(applier.DecoderAppliedSeq()));
std::abort();
}
// RETIRE. MANDATORY, not optional: RingProducer::FreeBytes() reclaims against
// retiredTail only, and w1's SEG_STAGE linear allocator reclaims on retiredSeq - so
@@ -655,8 +658,22 @@ namespace MobileGL::MG_Remote::Server {
return applied;
}
void ServerLoop::SetRemoteControlSink(RemoteControlSink sink, void* user) {
m_remoteSink = sink;
m_remoteSinkUser = user;
}
MobileGLResult ServerLoop::RunSurfaceControlFrame(SurfaceControlFrame& frame) {
if (frame.kind == SurfaceControlOp::None) return MOBILEGL_ERR_INVALID_ARGUMENT;
// `cp`: the server is another process, so the frame CROSSES instead of
// being posted. Checked before the seq mint below, because a wire request
// must carry the CLIENT's number all the way through dispatch and the
// reply - the local mint at :662 is for unnumbered LOCAL requests and
// renumbering a wire one would make its reply uncorrelatable.
if (m_remoteSink != nullptr) {
return m_remoteSink(m_remoteSinkUser, frame);
}
// Zero marks an unnumbered local request. A wire request is already numbered by its
// client and MUST retain that number all the way through dispatch and the reply.
if (frame.seq == 0) frame.seq = m_controlSeq.fetch_add(1, std::memory_order_acq_rel) + 1;
@@ -687,13 +704,12 @@ namespace MobileGL::MG_Remote::Server {
// render correctly with the context on the wrong thread - the one outcome R-1
// exists to make impossible. Fatal by name, never a fallback; compare
// CreateBackend's default: arm, which also refuses rather than substitutes.
MGLOG_F("MGPipe: Fatal{ApplyThreadNotRunning, \"EGL on the app thread\"} - a "
SessionFail(MGFatalFamily::ApplyThreadNotRunning, "MGPipe: Fatal{ApplyThreadNotRunning, \"EGL on the app thread\"} - a "
"control frame reached RunSurfaceControlFrame with the server's backend "
"built but no mgl-srv-apply thread running (ClientSession::Start failed "
"after ServerLoop::CreateBackend). Dispatching it inline would make the "
"context current on the APP thread - the split lane's whole premise. "
"Refusing by name rather than falling back to monolith");
std::abort();
}
// Backend already gone (post-Stop teardown, or the pre-Init window): the dispatch's
// null-backend arm would answer NOT_INITIALIZED anyway, so that is the honest result
@@ -787,7 +803,7 @@ namespace MobileGL::MG_Remote::Server {
// run on into the client's teardown, reading rings the client is about to unmap -
// a use-after-free whose only symptom is an intermittent crash somewhere else.
// Aborting here is red, immediate, and names the cause.
MGLOG_F("MGPipe: Fatal{ApplyThreadJoinTimeout} - mgl-srv-apply did not exit within "
SessionFail(MGFatalFamily::ApplyThreadJoinTimeout, "MGPipe: Fatal{ApplyThreadJoinTimeout} - mgl-srv-apply did not exit within "
"%u ms of Stop(). Stop() published m_stopRequested (in the park predicate) "
"BEFORE it rang, so a plain Notify should already have un-parked the thread; "
"Doorbell::Kill() (Doorbell.h, CondVarDoorbell::Kill; table 3 step 2) is "
@@ -796,7 +812,6 @@ namespace MobileGL::MG_Remote::Server {
"lost, not slow. Aborting rather than detaching: a detached apply thread still "
"owns the context and would read rings the client is about to unmap",
kJoinTimeoutMs);
std::abort();
}
m_thread.join();
// The identity is NOT cleared here any more: the thread clears it itself, under
@@ -864,10 +879,9 @@ namespace MobileGL::MG_Remote::Server {
MG_Backend::WindowBackend WindowBackendFromFrameValue(Int value) {
if (value < static_cast<Int>(MG_Backend::WindowBackend::Unknown) ||
value >= static_cast<Int>(MG_Backend::WindowBackend::WindowBackendCount)) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.windowBackend\"} - a "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.windowBackend\"} - a "
"control frame carried window backend tag %d, which names no "
"WindowBackend", value);
std::abort();
}
return static_cast<MG_Backend::WindowBackend>(value);
}
@@ -1016,7 +1030,7 @@ namespace MobileGL::MG_Remote::Server {
backend->SetWindowHandle(UnpackWindowHandle(frame));
frame.ok = true;
return MOBILEGL_OK;
case SurfaceControlOp::InitCapabilitiesInprocOnly:
case SurfaceControlOp::InitCapabilities:
// Inproc-only (f0-egl §4.2): on the wire the ANSWER to this op is the CapsSnapshot
// frame itself, so there is no SurfaceOp kind for it. The frame channel still has to
// carry it inproc because InitCapabilities runs GL queries and therefore belongs to
@@ -1051,9 +1065,8 @@ namespace MobileGL::MG_Remote::Server {
// A kind the switch does not know never legitimately posts (RunSurfaceControlFrame
// refuses None), so reaching this line means the slot's bytes were not written by the
// poster at all - the ring's Fatal{ProtocolCorruption} discipline, one channel over.
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.kind\"} - the control slot held "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"SurfaceOp.kind\"} - the control slot held "
"kind %d, which names no dispatchable op", static_cast<int>(frame.kind));
std::abort();
}
// ---------------------------------------------------------------------------------
@@ -1158,7 +1171,7 @@ namespace MobileGL::MG_Remote::Server {
Bool ServerInitCapabilities() {
SurfaceControlFrame frame;
frame.kind = SurfaceControlOp::InitCapabilitiesInprocOnly;
frame.kind = SurfaceControlOp::InitCapabilities;
const MobileGLResult rc = ServerLoopInstance().RunSurfaceControlFrame(frame);
return rc == MOBILEGL_OK && frame.ok;
}
+18
View File
@@ -223,6 +223,21 @@ namespace MobileGL::MG_Remote::Server {
// What did NOT move: the blocking handshake, the one slot, and the apply-thread
// ownership. Under spawn the same frame is what SurfaceOpCodec encodes into a
// Wire::SurfaceOp - this signature is the seam both transports share.
// P6 `cp`: where a control frame goes when the server is ANOTHER PROCESS.
//
// All twelve Server* forwarders funnel through RunSurfaceControlFrame, so
// this is ONE seam rather than twelve (a6 row A4-13 counted them). The
// client installs a sink at handshake; with none installed the behaviour
// is exactly what it was - post into the one-slot mailbox, or run inline
// when we are already on the apply thread.
//
// A HOOK RATHER THAN A CALL INTO ClientSession, deliberately: the server
// half calling the client half is four of the six symbols a6 found
// MG_Remote owes itself (a6-link-experiment §5), and this is the one
// place that would have added a fifth.
using RemoteControlSink = MobileGLResult (*)(void* user, SurfaceControlFrame& frame);
void SetRemoteControlSink(RemoteControlSink sink, void* user);
MobileGLResult RunSurfaceControlFrame(SurfaceControlFrame& frame);
// The TEST seam through the same channel: posts a ProbeForTesting frame whose dispatch
@@ -364,6 +379,9 @@ namespace MobileGL::MG_Remote::Server {
Bool ControlIsPending() const;
private:
RemoteControlSink m_remoteSink = nullptr;
void* m_remoteSinkUser = nullptr;
void ApplyThreadMain();
// Runs a posted control frame, if there is one. Returns true if it ran one.
Bool PumpControlRequest();
+445
View File
@@ -0,0 +1,445 @@
// MobileGL - MobileGL/MG_Remote/Server/ServerMain.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// The server process's entry point. Package `sm` (CONTRACT-P6.md §3).
//
// ARCHITECTURE.md:488-496 has described this symbol for three phases and a6
// found it existed nowhere in the tree. This is the real one.
//
// THE TWO PROCESSES ARE INDEPENDENT. This process is started by whoever starts
// it - a shell, a test, an Android Service - and it LISTENS. The client is
// started separately and CONNECTS. Nothing is inherited: no fds, no memory, no
// parent.
//
// That is a deliberate change from this package's first shape, which forked the
// server and handed it fds 3..6. Inheritance works and is less code, but it can
// only ever produce a server that is a CHILD OF ITS CLIENT - the one arrangement
// the end state cannot use, because there the server is a standing application
// and the client is somewhere else entirely, possibly on another kernel.
// CONTRACT-P6 §3.1 calls this Dial == Connect and had it as a later shape. It is
// the primary one.
//
// WHAT THIS PACKAGE OWNS: the process, the rendezvous, the backend, the session,
// the descriptor hand-off and the exit discipline. NOT what a control frame
// means - that is `cp` - and not the data-plane seam, which is `lk`.
//
// _exit, NOT exit (CONTRACT-P6 §12.4). It decides whether g_processTeardown is
// ever set, and therefore whether seven twin destructors take their early-out or
// call into a driver whose context is already gone. The log is flushed first,
// because _exit runs no atexit handler and a server that died without saying why
// is the diagnostic this project refuses.
#include "../Transport/Doorbell.h" // kWaitForever, SocketDoorbell
#include "../Transport/FdPassing.h"
#include "../Transport/SocketTransport.h"
#include "../Transport/WireLog.h"
#include "../Protocol/SurfaceOpCodec.h"
#include "ServerLoop.h"
#include "ServerSession.h"
#include "SurfaceControlFrame.h"
#include <Config.h> // MG_Config::Transport - D1 pins it to Spawn in this process
#include <MG_Backend/MGPipe/PipeInputs.h> // D1c: MGPipeSetServerProcessRole
#include <MG_Backend/ServerRole.h>
#include <MG_Util/Metrics/PipeStats.h> // step 1.6: the counters' latch, server-process half
#include <Init.h> // MG_ConfigLoader::Init - the child loads its own config (step 1.5)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <vector>
#if defined(__unix__) || defined(__APPLE__) || defined(__ANDROID__)
# include <sys/socket.h>
# include <unistd.h>
#endif
namespace {
// The server must not be able to become a client. CONTRACT-P6 §3.1: this is
// catch (a), STRUCTURAL and separate from role selection, because forcing
// MG_Config::Transport to Monolith - what ARCHITECTURE.md:488 says - would
// flip 148 MG_Backend lines to the frontend arm in the one process with no
// frontend. Catch (b) is the launcher's envp scrub, and the two report
// through DIFFERENT exit codes so they are distinguishable: two safeties
// that cannot be told apart are one safety.
bool DialingIsForbidden() {
const char* dial = std::getenv("MOBILEGL_IPC_DIAL");
return dial != nullptr && std::strcmp(dial, "no") == 0;
}
bool LooksLikeAClientEnvironment() {
static constexpr const char* kNames[] = {"MOBILEGL_TRANSPORT", "MOBILEGL_IPC_SERVER_PATH",
"MOBILEGL_IPC_RING_MB", "MOBILEGL_IPC_STAGE_MB"};
for (const char* name : kNames) {
if (std::getenv(name) != nullptr) {
return true;
}
}
return false;
}
// The rendezvous. A NAME, because independent processes have no other way to
// find each other. No default: a default rendezvous is one that two unrelated
// runs can collide on.
std::string Endpoint(int argc, char** argv) {
if (argc > 1 && argv[1] != nullptr && argv[1][0] != '\0') {
return argv[1];
}
if (const char* fromEnv = std::getenv("MOBILEGL_IPC_ENDPOINT")) {
return fromEnv;
}
return std::string();
}
} // namespace
extern "C" __attribute__((visibility("default"))) int mobilegl_server_main(int argc, char** argv) {
using namespace MobileGL::MG_Remote;
using namespace MobileGL::MG_Remote::Transport;
const int selfPid = static_cast<int>(::getpid());
// The arm-proof line (CONTRACT-P6 §9.5). ID-124 proved a lane can run
// monolith and pass every other gate, so each entry leaves its own evidence.
WireLogError("MG_Remote server: pid=%d transport=spawn role=server", selfPid);
if (!DialingIsForbidden()) {
std::fprintf(stderr,
"MG_Remote server: pid=%d refusing to start - MOBILEGL_IPC_DIAL=no was not "
"set; anti-recursion catch (a) is missing\n",
selfPid);
std::fflush(nullptr);
::_exit(64);
}
if (LooksLikeAClientEnvironment()) {
std::fprintf(stderr,
"MG_Remote server: pid=%d the envp scrub FAILED - a client knob survived "
"into this process; catch (a) held, catch (b) did not\n",
selfPid);
std::fflush(nullptr);
::_exit(65);
}
const std::string endpoint = Endpoint(argc, argv);
if (endpoint.empty()) {
std::fprintf(stderr,
"MG_Remote server: pid=%d no endpoint - pass one as argv[1] or set "
"MOBILEGL_IPC_ENDPOINT\n",
selfPid);
std::fflush(nullptr);
::_exit(71);
}
// ---- 1. listen, BEFORE the backend. The client's bounded connect retry is
// what tolerates the backend taking a while; a client that connected and then
// waited for a Welcome a failed bring-up will never send would have to learn
// about death from a timeout, which §5.4 forbids.
int listenFd = -1;
if (SocketTransport::Listen(endpoint, &listenFd) != MOBILEGL_OK) {
std::fprintf(stderr, "MG_Remote server: pid=%d could not listen on \"%s\"\n", selfPid,
endpoint.c_str());
std::fflush(nullptr);
::_exit(72);
}
WireLogError("MG_Remote server: pid=%d listening on \"%s\"", selfPid, endpoint.c_str());
// ---- 1.5. CONFIG, AND THEN D1.
//
// TWO SEPARATE DEFECTS LIVED HERE, and both were silent.
//
// (a) NOTHING LOADED THE CONFIG AT ALL. mobilegl_server_main calls
// InitServerRoleForSpawn directly rather than MobileGL::Initialize, and
// MG_ConfigLoader::Init is a step of the latter - so every MG_Config
// value in this process was its STATIC DEFAULT. MOBILEGL_BACKEND_TYPE
// survives the launcher's scrub on purpose, and it was being read by
// nobody: a DirectVulkan session would have brought up a DirectGLES
// server and then disagreed with its client about which backend the
// capability mask describes.
//
// (b) THE CHILD RESOLVED Transport == Monolith. CONTRACT-P6 §3.1 (D1) says
// it must read as Spawn, and a6 measured the cost of getting it wrong:
// 226 live lines test `Transport != Monolith` to select the SERVER arm,
// 148 of them in MG_Backend. Monolith flips all of them to frontend glue
// in the one process that has no frontend. Observed, exactly as
// predicted: TextureImpl::UnitTexturesByHandle() answered false, Clear
// took the legacy arm that dereferences borrowed FRONTEND slot pointers,
// and the apply thread took a SIGSEGV inside SyncNeccessaryTextures on
// the first Clear record of the OpenRA retrace.
//
// IT IS SET HERE AND NOT THROUGH THE ENVIRONMENT because the environment is
// where it must NOT appear: LooksLikeAClientEnvironment above exits 65 if
// MOBILEGL_TRANSPORT survived into this process, and that check is
// anti-recursion catch (b). D1's own answer is that Dial - not Transport -
// is the anti-recursion axis, so Transport is free to say what is true.
MobileGL::MG_ConfigLoader::Init();
MobileGL::MG_Config::Transport = MobileGL::MG_Config::TransportMode::Spawn;
// D1c/D10: THIS PROCESS IS THE SERVER, stated once and before any GL work.
//
// Four guards used to ask "am I on the apply thread" or "is a ClientSession active" - both
// questions a server PROCESS answers wrongly: it has no ClientSession at all, and every one
// of its threads is a server thread, not just the applier's. Saying it here is what arms
// them; without it they are compiled in and permanently false, which is worse than absent
// because it reads as coverage.
MobileGL::MG_Pipe::MGPipeSetServerProcessRole(true);
// ---- 1.6. THE MGPIPE COUNTERS, and this is the ONLY call site outside
// MobileGL::Initialize().
//
// GATE 8'S SERVER HALF WAS STRUCTURALLY ZERO WITHOUT THIS, and the shape of the
// defect is worth stating: the child never runs MobileGL::Initialize, so
// PipeStats::Init() - a step of it - never ran here, and g_pipeStatsEnabled
// stayed false. Every one of the ~80 `if (Enabled())` sites in the backends and
// in MG_Remote (ServerLoop's own ServerWaits/ServerParks publish included)
// compiled in and was permanently false in this process. The contract's
// mandatory "socket doorbell vs inproc condvar" number therefore had no server
// half under `spawn` at all, and its absence read exactly like a real zero:
// `wait[srv=0 srvpark=0]` is what "the server never waited" looks like too.
//
// IT GOES AFTER THE CONFIG LOAD AND AFTER THE ROLE IS STATED, and both halves
// of that order are load-bearing:
//
// * AFTER MG_ConfigLoader::Init, because Init() LATCHES the flag out of
// MG_Config::Features.PipeStats, and the parser does not exist until the
// line above has run. Calling it earlier would latch the static default
// (false) and the MOBILEGL_PIPE_STATS the launcher passed would be read by
// nobody - the same class of defect the config load itself used to have.
// * AFTER MGPipeSetServerProcessRole, because that is what makes the LOG SINK
// know this process is the server, and PipeStats' summary line is emitted
// through MGLOG_I. The sink resolves its role from MOBILEGL_IPC_ROLE (which
// the launcher sets and its envp scrub preserves) and would in fact be
// right either way, but ordering it this way means the line cannot be filed
// under the client by a future change to that resolution. What the contract
// requires - that the summary lands in `<base>.server.log` - is asserted by
// the lane, not assumed from this comment.
//
// MOBILEGL_PIPE_STATS / _PERIOD / _FILE MEAN EXACTLY WHAT THEY MEAN IN THE
// CLIENT PROCESS, and that is the whole point of routing through Init(): all
// three are read from the child's own environment by the same parser and
// latched by the same function. Nothing about the stats channel is spawn-shaped.
// One asymmetry is real and intended: this process has no backend Present of
// its own, so its line cadence rides the present RECORDS it applies
// (PipeApplier -> DirectGLES/DirectVulkan Present -> OnPresent) rather than a
// swap the server does not perform. A spawn session that presents N times
// produces N windows here, which is the same N the client's own line counts.
MobileGL::MG_Util::PipeStats::Init();
WireLogError("MG_Remote server: pid=%d config loaded, backend=%d, Transport pinned to Spawn "
"(D1: this process IS the server arm)",
selfPid, static_cast<int>(MobileGL::MG_Config::ActiveBackendType));
// ---- 2. the backend, through the SAME entry point the inproc server role
// uses (MG_Backend/ServerRole.h). No EGL yet: the context is created on the
// apply thread when the client's first eglMakeCurrent crosses.
if (!MobileGL::MG_Backend::InitServerRoleForSpawn()) {
std::fprintf(stderr,
"MG_Remote server: pid=%d could not create a backend; refusing to accept a "
"session it could never apply\n",
selfPid);
::close(listenFd);
::unlink(endpoint.c_str());
std::fflush(nullptr);
::_exit(66);
}
// ---- 3. accept the client's TWO connections: control, then aux.
std::unique_ptr<SocketTransport> control;
if (SocketTransport::AcceptPair(listenFd, 30000, control) != MOBILEGL_OK) {
std::fprintf(stderr, "MG_Remote server: pid=%d no client within 30 s\n", selfPid);
::close(listenFd);
::unlink(endpoint.c_str());
std::fflush(nullptr);
::_exit(73);
}
// One session per process (CONTRACT-P6 §12.3), so the door closes behind the
// one client that came through it. A second would collide on four process
// globals and on DirectGLES's single per-process EGL tuple.
::close(listenFd);
::unlink(endpoint.c_str());
// ---- 4. the two bells, created HERE and handed over. NOT inherited: there
// is no parent to inherit from. One socketpair per DIRECTION, because
// SocketDoorbell is "write a byte to wake the peer, poll to be woken" and a
// single pair would have each side reading the byte it wrote to the other.
int serverBell[2] = {-1, -1};
int clientBell[2] = {-1, -1};
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, serverBell) != 0 ||
::socketpair(AF_UNIX, SOCK_STREAM, 0, clientBell) != 0) {
std::fprintf(stderr, "MG_Remote server: pid=%d bell socketpair failed\n", selfPid);
std::fflush(nullptr);
::_exit(74);
}
// PARK AND NOTIFY ON DIFFERENT DESCRIPTORS, and this is not a refinement -
// the single-fd form CANNOT WAKE ITSELF. send() on one end of a socketpair
// is delivered to the OTHER end, so a one-fd bell built on serverBell[0]
// writes to serverBell[1] and polls serverBell[0]: correct for waking a
// PEER, useless for waking a thread in this process. The server needs
// exactly that, because the control pump posts into the apply thread's
// mailbox and then has to ring the bell that thread is parked on. Measured
// symptom when it was wrong: every eglInitialize crossed, landed in the
// mailbox, and timed out at 5 s because nothing ever woke mgl-srv-apply.
SocketDoorbell selfBell(/*parkFd=*/serverBell[0], /*notifyFd=*/serverBell[1], /*code=*/1,
/*ownsFds=*/true);
// RINGS ONLY. The client parks on clientBell[0]; writing clientBell[1] is
// what reaches it. parkFd = -1 says in the type that this side never waits.
SocketDoorbell peerBell(/*parkFd=*/-1, /*notifyFd=*/clientBell[1], /*code=*/1,
/*ownsFds=*/true);
Server::ServerSession& session = Server::ServerSessionInstance();
session.SetExternalDoorbells(&selfBell, &peerBell);
// ---- 5. Accept: the ABI assertion, the four segments, and Welcome.
const MobileGLResult accepted = session.Accept(*control);
if (accepted != MOBILEGL_OK) {
std::fprintf(stderr, "MG_Remote server: pid=%d Accept failed (rc=%d)\n", selfPid,
static_cast<int>(accepted));
std::fflush(nullptr);
::_exit(67);
}
// ---- 6. hand SIX descriptors over. THIS IS WHY SCM_RIGHTS IS IN THIS
// DESIGN: the segments are anonymous - ASharedMemory_create has no filesystem
// name at all, and memfd / shm_open+unlink are not openable either
// (ShmSegmentPosix.cpp says so) - so the descriptor IS the only key, and this
// process is the side that created them.
//
// The slot travels in the sideband rather than being inferred from arrival
// order, so a reordered or dropped offer is a NAMED mismatch on arrival
// instead of two segments quietly swapped.
{
struct Sideband {
std::uint32_t slot;
std::uint64_t bytes;
};
using Slot = SessionSegmentSlot;
static constexpr Slot kSlots[4] = {Slot::Cmd, Slot::Stage, Slot::Reply, Slot::Event};
for (const Slot slot : kSlots) {
const std::uint32_t tag = static_cast<std::uint32_t>(slot);
const int fd = session.Shm().DescriptorFor(slot);
if (fd < 0) {
std::fprintf(stderr, "MG_Remote server: pid=%d segment %u has no descriptor\n",
selfPid, tag);
std::fflush(nullptr);
::_exit(68);
}
Sideband sideband{tag, session.Shm().AnnouncedSize(slot)};
if (control->ShareFd(fd, MobileGLByteSpan{&sideband, sizeof(sideband)}) !=
MOBILEGL_OK) {
std::fprintf(stderr, "MG_Remote server: pid=%d could not share segment %u\n",
selfPid, tag);
std::fflush(nullptr);
::_exit(69);
}
}
// SLOTS 4, 5 AND 6 ARE THE BELLS - three, not two, and the third is the
// one the two-fd form above forces:
// 4 serverBell[1] the client's handle to RING THE SERVER
// 5 clientBell[0] the client's PARK end
// 6 clientBell[1] the client's handle to ring ITSELF, for the same
// reason the server needs serverBell[1]
// Sharing DUPs, so the descriptors these bells own stay valid here.
const int bellFds[3] = {serverBell[1], clientBell[0], clientBell[1]};
for (std::uint32_t index = 0; index < 3; ++index) {
Sideband sideband{4 + index, 0};
if (control->ShareFd(bellFds[index], MobileGLByteSpan{&sideband, sizeof(sideband)}) !=
MOBILEGL_OK) {
std::fprintf(stderr, "MG_Remote server: pid=%d could not share bell %u\n", selfPid,
index);
std::fflush(nullptr);
::_exit(69);
}
}
// clientBell[0] is the CLIENT's park end and no bell here owns it; the
// other three belong to selfBell and peerBell and are closed with them.
::close(clientBell[0]);
}
// ---- 7. the apply thread. It holds the native context for its whole life,
// which is what turns MakeCurrent's cache-invalidation storm into a one-off.
Server::ServerLoop& loop = Server::ServerLoopInstance();
if (loop.Start(session) != MOBILEGL_OK) {
std::fprintf(stderr, "MG_Remote server: pid=%d the apply thread did not start\n", selfPid);
std::fflush(nullptr);
::_exit(70);
}
WireLogError("MG_Remote server: pid=%d transport=spawn role=server ready "
"(backend up, seven descriptors handed over, apply thread running)",
selfPid);
// ---- 8. the control pump. EOF is the whole exit condition: no timeout may
// ever stand in for the death fact (§5.4), because a server one frame behind
// is the intended steady state and a server that is gone is a different thing.
std::vector<std::uint8_t> buffer(64 * 1024);
for (;;) {
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
const MobileGLResult result = control->ReceiveFrame(span, &size, kWaitForever);
if (result == MOBILEGL_ERR_TRANSPORT_CLOSED) {
WireLogError("MG_Remote server: pid=%d peer closed the control stream; exiting",
selfPid);
break;
}
if (result == MOBILEGL_ERR_BUFFER_TOO_SMALL) {
buffer.resize(static_cast<std::size_t>(size));
continue; // still queued: ITransport's contract
}
if (result != MOBILEGL_OK) {
WireLogError("MG_Remote server: pid=%d control stream failed (rc=%d); exiting", selfPid,
static_cast<int>(result));
break;
}
// `cp`: decode, apply, reply. THIS THREAD IS NOT THE APPLY THREAD, which
// is what CONTRACT-P6 §6.2 requires - a control arrival must not wake the
// applier, and frame decode must not happen on the thread holding the
// native context. ServerApplyWireSurfaceOp posts through ServerLoop's
// existing one-slot mailbox, unchanged.
const ::MobileGL::Wire::CtrlEnvelope* envelope = nullptr;
{
::flatbuffers::Verifier verifier(buffer.data(), static_cast<std::size_t>(size));
if (::MobileGL::Wire::VerifyCtrlEnvelopeBuffer(verifier)) {
envelope = ::MobileGL::Wire::GetCtrlEnvelope(buffer.data());
}
}
if (envelope == nullptr || envelope->msg_type() != ::MobileGL::Wire::CtrlMsg::SurfaceOp ||
envelope->msg_as_SurfaceOp() == nullptr) {
WireLogError("MG_Remote server: pid=%d a control frame that is not a verifiable "
"SurfaceOp arrived; ignoring it would be the silent drop this project "
"refuses, so the session ends here",
selfPid);
break;
}
Server::SurfaceControlFrame reply{};
const MobileGLResult applied =
ServerApplyWireSurfaceOp(*envelope->msg_as_SurfaceOp(), &reply);
(void)applied; // carried in the reply's ok/result, not thrown away here
::flatbuffers::FlatBufferBuilder builder(256);
EncodeSurfaceReplyFrame(reply, &builder);
if (control->SendFrame(
MobileGLByteSpan{builder.GetBufferPointer(), builder.GetSize()}) != MOBILEGL_OK) {
break;
}
}
loop.Stop();
session.Close();
control->Shutdown();
// Step 1.6's other half, and its position is the same argument MobileGL::Destroy
// makes: AFTER loop.Stop(), because the apply thread is what publishes
// ServerWaits / ServerParks and a dump taken while it still runs is a race; and
// BEFORE _exit, because _exit runs no atexit handler and this is the only place
// the server's run totals and its JSON dump can be written at all. Without it
// the server printed whatever windows its last period boundary happened to
// reach and lost the final one - the same "the last frame's numbers can be
// lost" case Init.cpp's Shutdown call exists to avoid on the client side.
MobileGL::MG_Util::PipeStats::Shutdown();
std::fflush(nullptr);
::_exit(0);
}
+58 -31
View File
@@ -9,6 +9,7 @@
// P5 package s1: the server half of a session.
#include "ServerSession.h"
#include <MG_Remote/FatalFunnel.h>
#include "../CapsCodec.h"
#include "../Protocol/generated/protocol_generated.h"
@@ -24,8 +25,27 @@
#include <cstring>
#include <vector>
// CONTRACT-P6 4.3: the one value in the handshake that a same-process session cannot fake.
#if defined(_WIN32)
#include <process.h>
#else
#include <unistd.h>
#endif
namespace MobileGL::MG_Remote::Server {
namespace {
// File-local on purpose: two callers, both handshake facts. A process-id helper on a
// public header invites uses that are not.
std::uint32_t SelfProcessId() {
#if defined(_WIN32)
return static_cast<std::uint32_t>(::_getpid());
#else
return static_cast<std::uint32_t>(::getpid());
#endif
}
} // namespace
// THE THREE FLAG-SPACE COLLISIONS, AS TRIPWIRES RATHER THAN AS A COMMENT.
//
// MGPipeCallFlags (MG_Pipe/MGPipe.h:42-54) and RingRecordFlags (Ring.h) are separate spaces
@@ -96,7 +116,7 @@ namespace MobileGL::MG_Remote::Server {
// DynamicBackendParameters still carries SizeT, so a peer built from a different
// tree hands over a caps block whose members are at different offsets and whose
// bytes are all individually plausible.
MGLOG_F("MGPipe: Fatal{AbiMismatch, \"%s\"} ours=%llu theirs=%llu ourBuild=%s "
SessionFail(MGFatalFamily::AbiMismatch, "MGPipe: Fatal{AbiMismatch, \"%s\"} ours=%llu theirs=%llu ourBuild=%s "
"theirBuild=%s - the two peers were not built from the same struct shapes, "
"and there is no downgrade path: the caps block's size is ABI-dependent "
"(MGPipeTypes.h:145-146) and every field past the first difference would be "
@@ -104,7 +124,6 @@ namespace MobileGL::MG_Remote::Server {
what, static_cast<unsigned long long>(ours),
static_cast<unsigned long long>(theirs),
ourStamp == nullptr ? "?" : ourStamp, theirStamp == nullptr ? "?" : theirStamp);
std::abort();
}
// MOBILEGL_IPC_RING_MB / MOBILEGL_IPC_STAGE_MB, actually applied.
@@ -145,7 +164,7 @@ namespace MobileGL::MG_Remote::Server {
// SetCapabilityBits / SetConsumedSubsystems for why the one that used to be here was
// the phase's marquee defect committed from the server's side.
[[noreturn]] void FatalUnsetCallMask(Bool capBitsSet, Bool consumedSet) {
MGLOG_F("MGPipe: Fatal{UnsetCallMask} - %s%s%s was never set on this ServerSession, "
SessionFail(MGFatalFamily::UnsetCallMask, "MGPipe: Fatal{UnsetCallMask} - %s%s%s was never set on this ServerSession, "
"and there is no default: a guessed consumer mask makes the client's R-8 "
"liveness gates answer from a server-side fact the server never stated. The "
"client would stop emitting whole record families, clear its dirty flags on "
@@ -155,7 +174,6 @@ namespace MobileGL::MG_Remote::Server {
capBitsSet ? "" : "SetCapabilityBits",
(!capBitsSet && !consumedSet) ? " and " : "",
consumedSet ? "" : "SetConsumedSubsystems");
std::abort();
}
// ---- P5c ev: the reverse channel's PRODUCER callbacks (CONTRACT-P5C §4.1) --------
@@ -173,12 +191,11 @@ namespace MobileGL::MG_Remote::Server {
// a Reserve that returns nullptr is Fatal{EventRingOverflow}. CountDrop and the
// eventRingFull latch stay built and stay unused-by-policy; P9 owns the policy.
[[noreturn]] void FatalEventRingOverflow(const char* eventName, Uint64 payloadBytes) {
MGLOG_F("MGPipe: Fatal{EventRingOverflow} - the producer of %s could not reserve "
SessionFail(MGFatalFamily::EventRingOverflow, "MGPipe: Fatal{EventRingOverflow} - the producer of %s could not reserve "
"%llu bytes on SEG_EVENT. P5c's events are lossless and a full ring under "
"lockstep is a producer burst no measured workload has, so this is a "
"defect, not a drop (CONTRACT-P5C §4.4; the drop policy is P9's)",
eventName, static_cast<unsigned long long>(payloadBytes));
std::abort();
}
// ---- P5e (ra), CONTRACT-P5E §2.6: the ring stops being a Fatal and becomes a queue --
@@ -220,14 +237,13 @@ namespace MobileGL::MG_Remote::Server {
// be a hang with a comment on it.
const Uint64 cap = session.Events().Ring().MaxRecordBytes();
if (payloadBytes + sizeof(Transport::RingRecordHeader) > cap) {
MGLOG_F("MGPipe: Fatal{EventRingOverflow} - %s needs %llu bytes and SEG_EVENT "
SessionFail(MGFatalFamily::EventRingOverflow, "MGPipe: Fatal{EventRingOverflow} - %s needs %llu bytes and SEG_EVENT "
"caps ONE record at %llu (half its capacity). Flow control cannot help: "
"no amount of draining makes a record fit a ring that is too small for "
"it. Raise MOBILEGL_IPC_EVENT_KB or slice the event at its producer, as "
"the writeback path already does",
eventName, static_cast<unsigned long long>(payloadBytes),
static_cast<unsigned long long>(cap));
std::abort();
}
Transport::RingControl& control = session.Control();
@@ -242,12 +258,11 @@ namespace MobileGL::MG_Remote::Server {
session.PublishEvents();
if (!drained() && !bell.Wait(control.consumerParked, drained, /*spinUs=*/0,
kEventBacklogWaitMs)) {
MGLOG_F("MGPipe: Fatal{EventRingOverflow} - %s waited %u ms for the client "
SessionFail(MGFatalFamily::EventRingOverflow, "MGPipe: Fatal{EventRingOverflow} - %s waited %u ms for the client "
"to drain SEG_EVENT and it never did. Under run-ahead the apply "
"thread parks on this ring (CONTRACT-P5E §2.6); a client that does "
"not drain is one that is not running",
eventName, kEventBacklogWaitMs);
std::abort();
}
slot = session.Events().Reserve(kind, payloadBytes);
if (slot != nullptr) return slot;
@@ -255,11 +270,10 @@ namespace MobileGL::MG_Remote::Server {
// Two full rounds against a ring the record provably fits: something else is
// producing into it, which on this side is impossible (one producer, the apply
// thread, by construction).
MGLOG_F("MGPipe: Fatal{EventRingOverflow} - %s could not reserve %llu bytes on an "
SessionFail(MGFatalFamily::EventRingOverflow, "MGPipe: Fatal{EventRingOverflow} - %s could not reserve %llu bytes on an "
"emptied SEG_EVENT. The apply thread is SEG_EVENT's only producer, so a "
"drained ring that still refuses a record it fits is a corrupt cursor set",
eventName, static_cast<unsigned long long>(payloadBytes));
std::abort();
}
// Accept owns the single process callback table. Its owner need not be the
@@ -267,9 +281,8 @@ namespace MobileGL::MG_Remote::Server {
ServerSession& ReverseCallbackOwner(const char* callback) {
auto* session = ServerSession::Active();
if (session == nullptr) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"%s.session-missing\"} - "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"%s.session-missing\"} - "
"a reverse callback has no accepted session owner", callback);
std::abort();
}
return *session;
}
@@ -281,12 +294,11 @@ namespace MobileGL::MG_Remote::Server {
// The backend handed over a segment-tagged blobref. The ONLY legal shape at
// this boundary is the monolith one - Offset is the mapped address, valid
// for this call - because the segment copy is THIS function's own job.
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Seg\"} - the "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"OnBufferWriteback.Seg\"} - the "
"writeback producer was handed Seg %u; at the backend boundary the "
"blobref names the backend's own mapped bytes (Seg = "
"kMGHostSpanSegNone) and the copy into SEG_EVENT is the producer's",
bytes.Seg);
std::abort();
}
const Uint64 payloadBytes = sizeof(Transport::EventBufferWritebackHead) + bytes.Size;
void* slot = ReserveEventOrBlock(session, Transport::kEventBufferWriteback,
@@ -356,11 +368,10 @@ namespace MobileGL::MG_Remote::Server {
template <typename Fn>
void InstallReverseCallback(Fn& entry, Fn producer) {
if (entry != nullptr && entry != producer) {
MGLOG_F("MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - a reverse "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - a reverse "
"MGPipeCallbacks entry is already claimed by a different function. With "
"an active transport the four reverse entries are the server "
"session's producers; the client installs them under monolith only");
std::abort();
}
entry = producer;
}
@@ -423,9 +434,8 @@ namespace MobileGL::MG_Remote::Server {
if (!g_sessionOwner.compare_exchange_strong(expectedOwner, this,
std::memory_order_acq_rel, std::memory_order_acquire)) {
if (expectedOwner == this) return MOBILEGL_ERR_INVALID_ARGUMENT;
MGLOG_F("MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - another "
SessionFail(MGFatalFamily::RoleViolation, "MGPipe: Fatal{RoleViolation, \"callback-double-install\"} - another "
"ServerSession already owns or is accepting the process reverse channel");
std::abort();
}
struct ReleaseFailedClaim {
ServerSession* self;
@@ -531,7 +541,15 @@ namespace MobileGL::MG_Remote::Server {
auto stamp = builder.CreateString(GIT_COMMIT_HASH_SHORT);
auto welcome = ::MobileGL::Wire::CreateWelcome(
builder, MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR,
static_cast<Uint32>(hello->pid()), cmd, stage, reply, event, stamp, ourFingerprint);
// CONTRACT-P6 4.3: THE SERVER'S OWN PID, not an echo of the client's.
//
// This field echoed hello->pid() - which is itself hard-coded 0 - so serverPid
// was ALWAYS 0 and named nothing. §9.5's arm-proof gate wants the child pid and
// this is its natural carrier: under spawn it is the one value in the handshake
// that a same-process session cannot produce, because there the two pids are
// equal by construction.
static_cast<Uint32>(SelfProcessId()),
cmd, stage, reply, event, stamp, ourFingerprint);
auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
builder, ::MobileGL::Wire::CtrlMsg::Welcome, welcome.Union());
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
@@ -693,9 +711,8 @@ namespace MobileGL::MG_Remote::Server {
Transport::RingControl& ServerSession::Control() {
Transport::RingControl* control = m_shm.CmdControl();
if (control == nullptr) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ServerSession::Control\"} - the control "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ServerSession::Control\"} - the control "
"page does not exist until Accept() has mapped SEG_CMD");
std::abort();
}
return *control;
}
@@ -706,11 +723,21 @@ namespace MobileGL::MG_Remote::Server {
// The bell the apply thread parks on. On the server endpoint of an InProcessTransport that
// is SelfDoorbell(); the client reaches the same bell through its own PeerDoorbell().
void ServerSession::SetExternalDoorbells(Transport::Doorbell* consumer,
Transport::Doorbell* producer) {
m_externalConsumerBell = consumer;
m_externalProducerBell = producer;
}
Transport::Doorbell& ServerSession::ConsumerDoorbell() {
// sm: injected first, because a spawn session's bells are sockets the
// entry point made and the transport has never heard of.
if (m_externalConsumerBell != nullptr) {
return *m_externalConsumerBell;
}
if (m_transport == nullptr) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ConsumerDoorbell\"} - no "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ConsumerDoorbell\"} - no "
"transport; Accept() has not run");
std::abort();
}
if (m_transport->Role() == Transport::TransportRole::InProcess) {
return static_cast<Transport::InProcessTransport*>(m_transport)->SelfDoorbell();
@@ -718,25 +745,25 @@ namespace MobileGL::MG_Remote::Server {
// P6: SocketTransport's pair. The accessors stay off ITransport by ruling (contract
// §3.9) precisely so that this stays one switch in one file rather than two virtuals
// every transport has to invent a home for.
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ConsumerDoorbell\"} - transport "
SessionFail(MGFatalFamily::UnmigratedVerb, "MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ConsumerDoorbell\"} - transport "
"role %u has no doorbell pair yet; that is P6's SocketTransport",
static_cast<unsigned>(m_transport->Role()));
std::abort();
}
Transport::Doorbell& ServerSession::ProducerDoorbell() {
if (m_externalProducerBell != nullptr) {
return *m_externalProducerBell;
}
if (m_transport == nullptr) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ProducerDoorbell\"} - no "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ServerSession::ProducerDoorbell\"} - no "
"transport; Accept() has not run");
std::abort();
}
if (m_transport->Role() == Transport::TransportRole::InProcess) {
return static_cast<Transport::InProcessTransport*>(m_transport)->PeerDoorbell();
}
MGLOG_F("MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ProducerDoorbell\"} - transport "
SessionFail(MGFatalFamily::UnmigratedVerb, "MGPipe: Fatal{UnmigratedVerb, \"ServerSession::ProducerDoorbell\"} - transport "
"role %u has no doorbell pair yet; that is P6's SocketTransport",
static_cast<unsigned>(m_transport->Role()));
std::abort();
}
Transport::SessionSegments& ServerSession::Shm() { return m_shm; }
+19
View File
@@ -82,11 +82,27 @@ namespace MobileGL::MG_Remote::Server {
ReplyPool& Replies();
// The client rings this one; the apply thread parks on it.
// P6 `sm`: the bells a spawn session parks on, injected because they do
// not come from the transport. CONTRACT-P5 §3.9 kept these accessors on
// the session precisely so this would be ONE switch in ONE file rather
// than two virtuals on every transport - and the switch it produced
// aborts for every role but InProcess, which is where a spawn apply
// thread died before popping its first record (a6 row A7-1).
//
// This is the narrow fix, not the general one: `lk` moves both bells
// behind ILink and DELETES these accessors, which is what CONTRACT-P6
// §8.1 means by retiring the ruling rather than amending it. Until then
// an injected pair is honest about where they come from, and the
// InProcess arm below is untouched.
void SetExternalDoorbells(Transport::Doorbell* consumer, Transport::Doorbell* producer);
Transport::Doorbell& ConsumerDoorbell();
// The server rings this one, but only when producerParked is set (a store to a shared
// cache line otherwise burns a big core for a whole frame on a phone).
Transport::Doorbell& ProducerDoorbell();
bool HasExternalDoorbells() const { return m_externalConsumerBell != nullptr; }
// ---- s1's additions beyond c0's signature block ---------------------------------
// The sizes to create the segments with. Must be called before Accept; after it, the
@@ -183,6 +199,9 @@ namespace MobileGL::MG_Remote::Server {
void LogMemory(const char* phase) const;
private:
// sm: non-owning; the spawn entry point owns the SocketDoorbells.
Transport::Doorbell* m_externalConsumerBell = nullptr;
Transport::Doorbell* m_externalProducerBell = nullptr;
Transport::RingConsumer m_commands;
Wire::SegmentTable m_segments;
PipeApplier m_applier;
+319
View File
@@ -0,0 +1,319 @@
// MobileGL - MobileGL/MG_Remote/Server/ServerSpawn.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "ServerSpawn.h"
#include "../Transport/FdPassing.h"
#include "../Transport/WireLog.h"
#include <Config.h>
#include <cerrno>
#include <cstring>
#include <vector>
#if defined(__unix__) || defined(__APPLE__) || defined(__ANDROID__)
# define MOBILEGL_SERVER_SPAWN_POSIX 1
# include <dirent.h>
# include <fcntl.h>
# include <dlfcn.h>
# include <sys/socket.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <sys/wait.h>
# include <unistd.h>
#else
# define MOBILEGL_SERVER_SPAWN_POSIX 0
#endif
namespace MobileGL::MG_Remote::Server {
#if MOBILEGL_SERVER_SPAWN_POSIX
namespace {
constexpr int kChildStreamFd = 3;
constexpr int kChildAuxFd = 4;
constexpr int kChildServerBellFd = 5;
constexpr int kChildClientBellFd = 6;
bool IsExecutableFile(const std::string& path) {
if (path.empty()) {
return false;
}
struct stat st {};
if (::stat(path.c_str(), &st) != 0) {
return false;
}
return S_ISREG(st.st_mode) && ::access(path.c_str(), X_OK) == 0;
}
// MOBILEGL_IPC_SERVER_PATH, then dladdr beside our own library.
// The fallback exists because the integration tests link MobileGL_s
// statically and trace replay's executable does not live in the library
// directory - ARCHITECTURE.md §15.1 names both.
std::string ResolveImage(const std::string& requested) {
if (!requested.empty()) {
return requested; // caller's explicit choice; validated below
}
const std::string configured(MG_Config::Ipc.ServerPath.c_str());
if (!configured.empty()) {
return configured;
}
Dl_info info{};
if (::dladdr(reinterpret_cast<void*>(&ResolveImage), &info) != 0 &&
info.dli_fname != nullptr) {
const std::string self(info.dli_fname);
const std::size_t slash = self.find_last_of('/');
if (slash != std::string::npos) {
return self.substr(0, slash + 1) + "libMobileGLServer.so";
}
}
return std::string();
}
// Every MOBILEGL_TRANSPORT and MOBILEGL_IPC_* goes. Built BEFORE fork:
// between fork and execve only async-signal-safe calls are allowed, and
// allocating a vector of strings is not one of them.
bool ShouldScrub(const char* entry) {
static constexpr const char* kPrefixes[] = {"MOBILEGL_TRANSPORT=", "MOBILEGL_IPC_"};
for (const char* prefix : kPrefixes) {
if (std::strncmp(entry, prefix, std::strlen(prefix)) == 0) {
return true;
}
}
return false;
}
struct ScrubbedEnv {
std::vector<std::string> storage;
std::vector<char*> pointers; // NULL-terminated, valid while `storage` lives
int removed = 0;
};
ScrubbedEnv BuildChildEnv(const std::string& imageDir) {
// `environ` is glibc/bionic's, declared by <unistd.h> at global
// scope. Re-declaring it inside this anonymous namespace made it a
// NEW symbol that nothing defines - which the linker caught, and
// which is worth a comment because the error names a mangled name
// that looks nothing like the variable.
ScrubbedEnv env;
for (char** e = ::environ; e != nullptr && *e != nullptr; ++e) {
if (ShouldScrub(*e)) {
++env.removed;
continue;
}
env.storage.emplace_back(*e);
}
// (a) of the two catches: the child is told, structurally, that it
// must not dial. Separate from which ROLE it plays - CONTRACT-P6
// §3.1 is the whole argument for why those are two axes.
env.storage.emplace_back("MOBILEGL_IPC_ROLE=server");
env.storage.emplace_back("MOBILEGL_IPC_DIAL=no");
// LD_LIBRARY_PATH, BECAUSE THE SERVER IS EXEC'd AND NOT dlopen'd.
//
// It links libMobileGL.so, and an exec'd process gets a FRESH linker
// namespace with the default search path - not the one the app built
// for its own libraries. An APK's lib/<abi>/ is not on that path, and
// the failure is total and immediate:
//
// CANNOT LINK EXECUTABLE ".../libMobileGLServer.so":
// library "libMobileGL.so" not found: needed by main executable
//
// It is invisible on desktop, where CMake gives build-tree targets an
// absolute RPATH of their own - so the WSL server had been resolving
// its dependency through a path no phone has.
//
// $ORIGIN WOULD BE THE TIDIER ANSWER and the target asks for it, but
// the NDK toolchain drops RPATH from the link: measured with readelf
// on the APK's own copy, which carries NEEDED libMobileGL.so and no
// RUNPATH at all. So the launcher states it instead - it is the one
// component that has already resolved where the image lives, and a
// pair that is not co-located is not a pair.
if (!imageDir.empty()) {
env.storage.emplace_back("LD_LIBRARY_PATH=" + imageDir);
}
env.pointers.reserve(env.storage.size() + 1);
for (auto& entry : env.storage) {
env.pointers.push_back(entry.data());
}
env.pointers.push_back(nullptr);
return env;
}
} // namespace
int CountOwnChildren() {
const pid_t self = ::getpid();
DIR* proc = ::opendir("/proc");
if (proc == nullptr) {
return -1; // not Linux-shaped; the gate must say so rather than read 0
}
int children = 0;
while (const dirent* entry = ::readdir(proc)) {
if (entry->d_name[0] < '0' || entry->d_name[0] > '9') {
continue;
}
std::string statPath = std::string("/proc/") + entry->d_name + "/stat";
FILE* file = std::fopen(statPath.c_str(), "r");
if (file == nullptr) {
continue;
}
// `comm` can contain spaces and parentheses, so parse from the LAST
// ')' rather than by field index - the classic /proc/pid/stat trap.
char buffer[512] = {};
const std::size_t read = std::fread(buffer, 1, sizeof(buffer) - 1, file);
std::fclose(file);
if (read == 0) {
continue;
}
const char* close = std::strrchr(buffer, ')');
if (close == nullptr) {
continue;
}
int ppid = 0;
char state = 0;
if (std::sscanf(close + 1, " %c %d", &state, &ppid) == 2 && ppid == self) {
++children;
}
}
::closedir(proc);
return children;
}
MobileGLResult LaunchServer(const std::string& imagePath, const std::string& endpoint,
LaunchedServer* out) {
if (out == nullptr || endpoint.empty()) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
*out = LaunchedServer{};
const std::string image = ResolveImage(imagePath);
if (!IsExecutableFile(image)) {
// NAMED, never a fallback. ConfigLoader.cpp's own comment names the
// accident this prevents: a lane that asked for spawn, silently got
// monolith, and went green on the wrong arm.
Transport::WireLogError(
"MG_Remote spawn: the server image is not executable: \"%s\" - refusing. Set "
"MOBILEGL_IPC_SERVER_PATH, or place libMobileGLServer.so beside libMobileGL.so. "
"There is NO monolith fallback from here.",
image.empty() ? "<unresolved>" : image.c_str());
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
// The image's directory, which is where its libMobileGL.so is.
const std::string::size_type slash = image.find_last_of('/');
ScrubbedEnv env =
BuildChildEnv(slash == std::string::npos ? std::string() : image.substr(0, slash));
std::string argv0 = image;
std::string argv1 = endpoint;
char* argv[] = {argv0.data(), argv1.data(), nullptr};
// A close-on-exec pipe so an execve that fails reports its errno back
// instead of vanishing: the app process's stderr is /dev/null on Android
// (ARCHITECTURE.md §15.2), so a silent exec failure would look exactly
// like a server that started and then died.
int report[2] = {-1, -1};
if (::pipe(report) != 0) {
return MOBILEGL_ERR_UNSUPPORTED;
}
::fcntl(report[1], F_SETFD, FD_CLOEXEC);
const pid_t pid = ::fork();
if (pid < 0) {
Transport::WireLogError("MG_Remote spawn: fork failed: %s", std::strerror(errno));
::close(report[0]);
::close(report[1]);
return MOBILEGL_ERR_UNSUPPORTED;
}
if (pid == 0) {
// ---- child: async-signal-safe calls ONLY until execve -------------
// NOTHING IS HANDED OVER. No dup2, no fixed fd numbers, no
// close-on-exec dance - the child gets an endpoint name in argv and
// finds everything else by listening. That is the whole difference
// between a launcher and a fork-coupled pair, and it is why this
// function is now twenty lines shorter than the version that tried
// to be both.
::close(report[0]);
::execve(image.c_str(), argv, env.pointers.data());
const int failure = errno;
const ssize_t ignored = ::write(report[1], &failure, sizeof(failure));
(void)ignored;
::_exit(127);
}
// ---- parent ---------------------------------------------------------
::close(report[1]);
int childErrno = 0;
const ssize_t got = ::read(report[0], &childErrno, sizeof(childErrno));
::close(report[0]);
if (got == static_cast<ssize_t>(sizeof(childErrno))) {
Transport::WireLogError("MG_Remote spawn: execve(\"%s\") failed in the child: %s",
image.c_str(), std::strerror(childErrno));
int status = 0;
::waitpid(pid, &status, 0);
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
out->pid = static_cast<int>(pid);
out->endpoint = endpoint;
Transport::WireLogError("MG_Remote spawn: server pid=%d image=\"%s\" endpoint=\"%s\" "
"transport=spawn (env scrubbed: %d entries removed)",
out->pid, image.c_str(), endpoint.c_str(), env.removed);
return MOBILEGL_OK;
}
MobileGLResult ReapServer(LaunchedServer& server, std::uint32_t timeoutMs,
int* outExitCode) {
if (server.pid < 0) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
// NOTHING TO CLOSE HERE ANY MORE. The launcher holds no descriptor
// into the child: whoever owns the CONNECTION closes it, and that EOF is
// what the child exits on. A launcher that also owned the connection is
// what made the two processes one unit.
const auto deadline = timeoutMs;
std::uint32_t waited = 0;
for (;;) {
int status = 0;
const pid_t done = ::waitpid(server.pid, &status, WNOHANG);
if (done == server.pid) {
if (outExitCode != nullptr) {
*outExitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status);
}
server.pid = -1;
return MOBILEGL_OK;
}
if (done < 0) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
if (waited >= deadline) {
return MOBILEGL_ERR_TIMEOUT;
}
::usleep(1000);
waited += 1;
}
}
#else // !MOBILEGL_SERVER_SPAWN_POSIX
MobileGLResult LaunchServer(const std::string&, const std::string&, LaunchedServer*) {
Transport::WireLogError("MG_Remote spawn: unsupported on this platform - P6 lands POSIX only "
"(CONTRACT-P6 §2.6); there is no fork() to build a second process from");
return MOBILEGL_ERR_UNSUPPORTED;
}
MobileGLResult ReapServer(LaunchedServer&, std::uint32_t, int*) {
return MOBILEGL_ERR_UNSUPPORTED;
}
int CountOwnChildren() { return -1; }
#endif
} // namespace MobileGL::MG_Remote::Server
+87
View File
@@ -0,0 +1,87 @@
// MobileGL - MobileGL/MG_Remote/Server/ServerSpawn.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// LAUNCHING a server process, and the process discipline around it.
// Package `sm` (CONTRACT-P6.md §3).
//
// IT LAUNCHES; IT DOES NOT COUPLE. The two processes are independent: this
// hands the child an endpoint NAME and nothing else - no inherited descriptors,
// no shared memory, no handshake. The child listens on that name and the client
// connects to it, exactly as it would to a server someone started by hand or
// that an Android Service started minutes earlier.
//
// An earlier shape of this file forked the server and handed it fds 3..6.
// Inheritance works and is less code, but it can only ever produce a server
// that is a CHILD OF ITS CLIENT - which the end state cannot use, because there
// the server is a standing application and the client is elsewhere, possibly on
// another kernel. So fork/execve survives here only as A WAY TO START A
// PROCESS, which is all it ever needed to be, and every fd it used to carry is
// gone.
//
// ANTI-RECURSION IS STILL TWO INDEPENDENT CATCHES, and CONTRACT-P6 §3.1 is why
// neither is ARCHITECTURE.md:488's. That rule says the child hard-sets
// Transport to Monolith; a6 measured that 226 live lines test
// `Transport != Monolith` to select the SERVER arm, 148 of them in MG_Backend,
// so obeying it flips the whole backend to frontend glue in the one process
// with no frontend. Instead:
// (a) STRUCTURAL: MOBILEGL_IPC_DIAL=no, a separate axis from which role the
// process plays;
// (b) ENVIRONMENTAL: MOBILEGL_TRANSPORT and every MOBILEGL_IPC_* removed
// from the child's envp.
// The child refuses with exit 64 for (a) and 65 for (b), so the two safeties
// are distinguishable - two that cannot be told apart are one.
#pragma once
#include <Includes.h>
#include "../Protocol/mg_protocol_base.h"
#include <memory>
#include <string>
namespace MobileGL::MG_Remote::Server {
struct LaunchedServer {
// -1 when nothing was spawned. Non-negative means this process owes the
// child a wait(): a SpawnedServer that goes out of scope without being
// reaped leaves a zombie, which is exactly what the process-tree gate
// (CONTRACT-P6 §9.4) counts.
// -1 when nothing was launched. Non-negative means this process owes the
// child a wait(): a LaunchedServer that goes out of scope unreaped leaves
// a zombie, which is what the process-tree gate (§9.4) counts.
int pid = -1;
// The endpoint the child was told to listen on. The launcher's only
// output besides the pid: everything else the client needs, it gets by
// connecting.
std::string endpoint;
};
// Locates the server image and starts it on `endpoint`. Returns as soon as
// the process exists; the client's bounded connect retry is what waits for
// it to finish binding (SocketTransport::ConnectTo).
//
// `imagePath` empty means "resolve it": MOBILEGL_IPC_SERVER_PATH first, then
// dladdr on our own library to find libMobileGLServer.so beside it. An
// unresolvable path is a NAMED REFUSAL and never a monolith fallback -
// ConfigLoader.cpp names that accident and this is the code that must not
// repeat it.
MobileGLResult LaunchServer(const std::string& imagePath, const std::string& endpoint,
LaunchedServer* out);
// Waits for the child, up to `timeoutMs`. Returns MOBILEGL_ERR_TIMEOUT if it
// is still running, in which case the caller decides whether to escalate -
// this function never signals a child it did not have to.
MobileGLResult ReapServer(LaunchedServer& server, std::uint32_t timeoutMs, int* outExitCode);
// How many children this process currently has, by scanning for our own
// pid as a parent. The process-tree gate needs a number, not a promise:
// "exactly one while running, zero after".
int CountOwnChildren();
} // namespace MobileGL::MG_Remote::Server
@@ -23,7 +23,7 @@ namespace MobileGL::MG_Remote::Server {
case SurfaceControlOp::SetSwapInterval: return "SetSwapInterval";
case SurfaceControlOp::ReleaseResources: return "ReleaseResources";
case SurfaceControlOp::SetWindowHandle: return "SetWindowHandle";
case SurfaceControlOp::InitCapabilitiesInprocOnly: return "InitCapabilitiesInprocOnly";
case SurfaceControlOp::InitCapabilities: return "InitCapabilities";
case SurfaceControlOp::SwapBuffersInprocOnly: return "SwapBuffersInprocOnly";
case SurfaceControlOp::InitWindowSurfaceInprocOnly: return "InitWindowSurfaceInprocOnly";
case SurfaceControlOp::ProbeForTesting: return "ProbeForTesting";
@@ -43,6 +43,10 @@ namespace MobileGL::MG_Remote::Server {
case SurfaceControlOp::SetSwapInterval:
case SurfaceControlOp::ReleaseResources:
case SurfaceControlOp::SetWindowHandle:
// cp: the request half of InitCapabilities. Its ANSWER is a CapsSnapshot
// frame, which is why this row was missing; the request still has to
// cross, because under spawn the apply thread is in another process.
case SurfaceControlOp::InitCapabilities:
return true;
default:
return false;
@@ -55,12 +55,18 @@ namespace MobileGL::MG_Remote::Server {
SetSwapInterval = 8,
ReleaseResources = 9,
SetWindowHandle = 10,
// P6 (cp) MOVED THIS ONE ONTO THE WIRE, and the old name was a lie the
// moment spawn existed. f0-egl reasoned that the wire's ANSWER to
// InitCapabilities is the CapsSnapshot frame, which is true and beside
// the point: the REQUEST still has to reach the apply thread, and under
// spawn that thread is in another process. Measured before the fix -
// every spawned eglMakeCurrent died at "surface op kind 11 cannot cross
// the wire (InprocOnlyOpOnTheWire)", one call after the backend came up.
InitCapabilities = 11,
// INPROC-ONLY kinds: legal inside this process's frame channel, NEVER encodable onto the
// wire (SurfaceOpCodec refuses them by name). f0-egl's census found no production caller
// for the two dead forwarders and a CapsSnapshot answer for the third; they ride the same
// frame channel because the function-pointer mailbox is GONE, not because they are wire
// ops.
InitCapabilitiesInprocOnly = 11, // the wire's answer is the CapsSnapshot frame itself
// for the two dead forwarders; they ride the same frame channel because the
// function-pointer mailbox is GONE, not because they are wire ops.
SwapBuffersInprocOnly = 12, // present travels as a record (the class-B Present emitter)
InitWindowSurfaceInprocOnly = 13,// a client-side no-op; kept for the inproc test lane
ProbeForTesting = 14, // MG_Test's arbitrary-work seam through the same channel
+89 -17
View File
@@ -22,6 +22,22 @@
// Same fallback as FdPassing.cpp: on macOS / BSD the protection is SO_NOSIGPIPE on the
// socket, set in SocketDoorbell's constructor, not a per-send flag.
// THE WITNESS'S `events`, and the whole reason it can watch a socket it must not read.
//
// POLLRDHUP is what Linux and bionic report when the PEER shuts down its writing end - the exact
// fact the death witness wants - and asking for it alone means poll never reports POLLIN for that
// descriptor, so unread control replies queued on it can neither wake this bell nor be consumed
// from under SocketTransport's reassembler. POLLHUP / POLLERR / POLLNVAL arrive in revents whether
// requested or not, so an 0 here would still catch a full close; POLLRDHUP only makes the
// half-close case - the one a dying peer actually produces first - visible too.
#if !defined(_WIN32)
#if defined(POLLRDHUP)
#define MOBILEGL_POLL_PEER_HANGUP POLLRDHUP
#else
#define MOBILEGL_POLL_PEER_HANGUP 0
#endif
#endif
#if !defined(_WIN32) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
@@ -212,7 +228,7 @@ namespace MobileGL::MG_Remote::Transport {
// -----------------------------------------------------------------------
SocketDoorbell::SocketDoorbell(int fd, std::uint8_t code, bool ownsFd)
: m_fd(fd), m_code(code), m_ownsFd(ownsFd) {
: m_fd(fd), m_notifyFd(fd), m_code(code), m_ownsFd(ownsFd) {
#if defined(SO_NOSIGPIPE)
// The per-socket form of MSG_NOSIGNAL, on the platforms that lack the per-call one:
// a Notify to a hung-up peer must come back as EPIPE, not as a fatal signal.
@@ -223,19 +239,44 @@ namespace MobileGL::MG_Remote::Transport {
#endif
}
// The two-fd form: park on one descriptor, ring another. See the header for
// why the server needs it and the cross-process form cannot provide it.
SocketDoorbell::SocketDoorbell(int parkFd, int notifyFd, std::uint8_t code, bool ownsFds)
: m_fd(parkFd), m_notifyFd(notifyFd), m_code(code), m_ownsFd(ownsFds) {
#if defined(SO_NOSIGPIPE)
for (int fd : {m_fd, m_notifyFd}) {
if (fd >= 0) {
const int one = 1;
(void)::setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one));
}
}
#endif
}
SocketDoorbell::~SocketDoorbell() {
if (m_ownsFd && m_fd >= 0) {
if (!m_ownsFd) {
return;
}
if (m_fd >= 0) {
::close(m_fd);
}
// Only when they are different: the single-fd form has m_notifyFd == m_fd
// and closing it twice is a double close, which on a busy process closes
// somebody else's descriptor rather than failing.
if (m_notifyFd >= 0 && m_notifyFd != m_fd) {
::close(m_notifyFd);
}
}
void SocketDoorbell::Notify() {
if (m_fd < 0) {
// The NOTIFY descriptor, not the park one: a ring-only bell has no park
// fd at all and must still be able to ring.
if (m_notifyFd < 0) {
return;
}
const std::uint8_t byte = m_code;
for (;;) {
const ssize_t written = ::send(m_fd, &byte, 1, MSG_DONTWAIT | MSG_NOSIGNAL);
const ssize_t written = ::send(m_notifyFd, &byte, 1, MSG_DONTWAIT | MSG_NOSIGNAL);
if (written == 1) {
return;
}
@@ -250,7 +291,7 @@ namespace MobileGL::MG_Remote::Transport {
if (written < 0 && (errno == EPIPE || errno == ECONNRESET)) {
// The peer is gone: it can never ring back either, so latch it
// here too rather than waiting for a Park to discover it.
m_dead = true;
m_dead.store(true, std::memory_order_release);
return;
}
MGLOG_D("MG_Remote doorbell: send failed (errno=%d)", errno);
@@ -259,7 +300,12 @@ namespace MobileGL::MG_Remote::Transport {
}
bool SocketDoorbell::Park(std::uint32_t timeoutMs) {
if (m_fd < 0 || m_dead) {
// A ring-only bell was never a waiter. Saying so immediately is the
// honest answer; blocking forever on -1 would be a hang with no cause.
if (m_fd < 0) {
return false;
}
if (m_fd < 0 || m_dead.load(std::memory_order_acquire)) {
return false;
}
const auto start = std::chrono::steady_clock::now();
@@ -272,10 +318,22 @@ namespace MobileGL::MG_Remote::Transport {
const long long remaining = static_cast<long long>(timeoutMs) - elapsed;
pollTimeout = remaining <= 0 ? 0 : static_cast<int>(remaining);
}
struct pollfd pfd{};
pfd.fd = m_fd;
pfd.events = POLLIN;
const int ready = ::poll(&pfd, 1, pollTimeout);
// THE WITNESS ASKS FOR HANGUP AND NOTHING ELSE. POLLHUP/POLLERR/POLLNVAL are
// reported in revents whether or not they were requested, so an `events` of
// POLLRDHUP alone gets the peer's shutdown and never POLLIN - which is the whole
// point: the control socket legitimately carries unread REPLY bytes, and asking for
// readability there would make every queued reply a wakeup, spin this loop, and race
// SocketTransport's reassembler for the same bytes. Nothing is ever recv'd from it.
struct pollfd pfds[2]{};
pfds[0].fd = m_fd;
pfds[0].events = POLLIN;
const bool watching = m_witnessFd >= 0;
if (watching) {
pfds[1].fd = m_witnessFd;
pfds[1].events = MOBILEGL_POLL_PEER_HANGUP;
}
const int ready = ::poll(pfds, watching ? 2 : 1, pollTimeout);
struct pollfd& pfd = pfds[0];
if (ready < 0) {
if (errno == EINTR) {
continue; // a signal is not a wakeup; keep the deadline
@@ -286,6 +344,20 @@ namespace MobileGL::MG_Remote::Transport {
if (ready == 0) {
return false; // timed out
}
// THE WITNESS FIRST, because a peer that is gone makes every other answer stale. It
// reports only hangup shapes by construction, so any revent on it IS the death.
if (watching && pfds[1].revents != 0) {
MGLOG_I("MG_Remote doorbell: the peer hung up (witness fd %d, revents=0x%X) - "
"this is the DEATH FACT, taken from a descriptor and not from a "
"deadline: a server one frame behind is the intended steady state and "
"must never be mistaken for one that is gone (CONTRACT-P6 5.4)",
m_witnessFd, static_cast<unsigned>(pfds[1].revents));
// THE CAUSE BEFORE THE FACT, so a reader that sees Dead() can never find
// PeerHungUp() still false and conclude "orderly teardown".
m_peerHungUp.store(true, std::memory_order_release);
m_dead.store(true, std::memory_order_release);
return false;
}
// revents has to be inspected, not just `ready > 0`. Once the peer
// closes its end the descriptor is permanently poll-ready with
// nothing to read (measured on Linux: revents=POLLIN|POLLHUP,
@@ -296,14 +368,14 @@ namespace MobileGL::MG_Remote::Transport {
if ((pfd.revents & (POLLERR | POLLNVAL)) != 0) {
MGLOG_D("MG_Remote doorbell: fd %d unusable (revents=0x%X)", m_fd,
static_cast<unsigned>(pfd.revents));
m_dead = true;
m_dead.store(true, std::memory_order_release);
return false;
}
if ((pfd.revents & POLLIN) != 0) {
if (Drain() != 0) {
return true; // a real wakeup byte
}
if (m_dead) {
if (m_dead.load(std::memory_order_acquire)) {
return false; // EOF, not an event
}
// Ready but empty and still alive: someone else drained it.
@@ -311,7 +383,7 @@ namespace MobileGL::MG_Remote::Transport {
return true;
}
if ((pfd.revents & POLLHUP) != 0) {
m_dead = true;
m_dead.store(true, std::memory_order_release);
return false;
}
// Readiness with no bit we requested or recognise: there is
@@ -319,7 +391,7 @@ namespace MobileGL::MG_Remote::Transport {
// poll this descriptor again.
MGLOG_D("MG_Remote doorbell: fd %d ready with revents=0x%X", m_fd,
static_cast<unsigned>(pfd.revents));
m_dead = true;
m_dead.store(true, std::memory_order_release);
return false;
}
}
@@ -338,7 +410,7 @@ namespace MobileGL::MG_Remote::Transport {
if (got == 0) {
// Orderly shutdown on a stream socket: the peer is gone and
// will never ring again.
m_dead = true;
m_dead.store(true, std::memory_order_release);
return consumed;
}
if (errno == EINTR) {
@@ -348,13 +420,13 @@ namespace MobileGL::MG_Remote::Transport {
return consumed; // drained
}
MGLOG_D("MG_Remote doorbell: recv failed (errno=%d)", errno);
m_dead = true;
m_dead.store(true, std::memory_order_release);
return consumed;
}
}
void SocketDoorbell::Reset() {
if (m_fd < 0 || m_dead) {
if (m_fd < 0 || m_dead.load(std::memory_order_acquire)) {
return;
}
(void)Drain();
+59 -3
View File
@@ -171,6 +171,17 @@ namespace MobileGL::MG_Remote::Transport {
// bell that cannot die.
virtual bool Dead() const { return false; }
// P6 `dl`: DEAD AND DEAD-BECAUSE-THE-PEER-DIED ARE NOT THE SAME FACT, and only the
// second one is a device loss. Dead() is also true after an ORDERLY teardown -
// CondVarDoorbell::Kill() is how Stop() wakes a parked applier, and the barrier reports
// SessionWait::ShutDown for that too. Latching device-lost from Dead() would therefore
// arm it on every clean exit.
//
// This says the peer HUNG UP: a descriptor whose far end only the peer held reported
// hangup. Nothing this side did can produce it. False for every doorbell that has no
// peer process, which is what makes the whole latch a no-op under inproc and monolith.
virtual bool PeerHungUp() const { return false; }
// How many Wait() calls on this bell exhausted their spin budget and
// really blocked. THE WAIT LEDGER'S RAW READING: the pair (waits, parks)
// is what says whether the spin budget is sized for the workload, and it
@@ -397,15 +408,52 @@ namespace MobileGL::MG_Remote::Transport {
// When `ownsFd` the descriptor is closed with this object. `code` is
// the byte written by Notify.
SocketDoorbell(int fd, std::uint8_t code, bool ownsFd);
// P6: PARK AND NOTIFY ON DIFFERENT DESCRIPTORS.
//
// The single-fd form above is the cross-process one: send() on this end
// is delivered to the PEER's end, so the peer's own SocketDoorbell is
// what receives it. That is correct, and it is also why the single-fd
// form cannot wake ITSELF - and the server needs exactly that, because
// its control pump posts into the apply thread's mailbox and must ring
// the bell that thread is parked on. Under inproc CondVarDoorbell has no
// such split: notify and wait are the same object.
//
// So: `parkFd` is polled, `notifyFd` is written. For a socketpair where
// this side holds both ends they are [0] and [1], and a peer that must
// also be able to ring it gets a DUP of [1]. `parkFd` may be -1 for a
// bell this side only ever RINGS - Park then returns immediately, which
// is the honest answer for an object that was never a waiter.
SocketDoorbell(int parkFd, int notifyFd, std::uint8_t code, bool ownsFds);
~SocketDoorbell() override;
void Notify() override;
bool Park(std::uint32_t timeoutMs) override;
void Reset() override;
bool Dead() const override { return m_dead; }
bool Dead() const override { return m_dead.load(std::memory_order_acquire); }
bool PeerHungUp() const override { return m_peerHungUp.load(std::memory_order_acquire); }
int Fd() const { return m_fd; }
// P6 `dl` (CONTRACT-P6 D5c). THE DESCRIPTOR THAT ANSWERS "IS THE PEER STILL THERE",
// which for this object can never be the one it parks on.
//
// The client parks on clientBell[0] and rings ITSELF through clientBell[1], so it holds
// BOTH ends of that socketpair. EOF arrives only when every writer closes and the client
// is one of them, so that descriptor cannot hang up no matter what happens to the server.
// A bell that can wake itself is a bell that cannot hear a death. Measured: a server that
// died on its first Clear left the client waiting out the full 120 s barrier and
// reporting Fatal{BarrierTimeout} - the wrong diagnosis, two minutes late.
//
// The witness is a descriptor whose FAR END ONLY THE PEER HOLDS - in practice the control
// socket. It is NOT OWNED here and is NEVER READ FROM: Park adds it to the poll set with
// `events` asking for hangup ALONE, so a control reply sitting unread in its queue cannot
// wake the bell and cannot be consumed from under SocketTransport's reassembler. What it
// contributes is exactly one fact, and only once: the peer is gone.
//
// -1 disables it, which is what every bell that has no peer socket uses.
void SetDeathWitness(int fd) { m_witnessFd = fd; }
private:
// Consumes every queued wakeup byte and returns how many. Latches
// m_dead on EOF: recv returning 0 on a stream socket is the peer's
@@ -413,10 +461,18 @@ namespace MobileGL::MG_Remote::Transport {
// afterwards.
std::uint64_t Drain();
int m_fd;
int m_fd; // polled
int m_notifyFd; // written; equals m_fd in the single-fd (cross-process) form
int m_witnessFd = -1; // polled for hangup only; NOT owned, NEVER read
// Set ONLY by the witness branch of Park, never by Kill or by our own EOF. See
// Doorbell::PeerHungUp for why the distinction is the whole design.
std::atomic<bool> m_peerHungUp{false};
std::uint8_t m_code;
bool m_ownsFd;
bool m_dead = false;
// ATOMIC BECAUSE THE LATCH READS IT ACROSS THREADS. Park() runs on whichever thread is
// waiting; the device-lost latch is consulted from the GL thread and from
// glGetGraphicsResetStatus. It was a plain bool while Dead() had no cross-thread reader.
std::atomic<bool> m_dead{false};
};
#endif
+302
View File
@@ -0,0 +1,302 @@
// MobileGL - MobileGL/MG_Remote/Transport/ILink.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// The DATA-plane seam. Declared by package c6, implemented by package lk.
// Authority: CONTRACT-P6.md §8.
//
// WHY THIS EXISTS AND WHY IT IS NOT ITransport. ITransport.h:16-20 says in its
// own header that everything on the hot path bypasses it: it carries the
// handshake, surface ops, resync, aux requests and fatals, and that scope is
// already correct for a socket. Below it there was NO interface of any kind -
// Ring.h, ReplySlot.h and EventRing.h each take a raw `void* base` plus a
// capacity, so "swap the transport" had nothing to swap. This header is that
// missing thing, and ITransport is neither extended nor changed by it.
//
// NOTHING INCLUDES THIS FILE IN c6. That is the whole of c6's behaviour
// guarantee: the seam is declared, StreamLink.h is declared against it (which
// is the adequacy proof - see below), and not one call site moves. Package lk
// implements ShmLink by relocating today's SessionSegments / Ring /
// ReplySlotPool / EventRing behind it, line for line, and only then rewrites
// the call sites.
//
// THE SEAM IS SETUP-TIME, NOT HOT-PATH. No method here is called per record,
// per publish, or inside a spin predicate. The producer takes a LinkArena once
// at attach and reserves through it non-virtually; every wait predicate reads
// LinkProgress through a raw pointer taken once. Three grounds, the second
// decisive (CONTRACT-P6.md §8.2):
//
// 1. Two virtuals per record at the 4000 records/frame SEG_CMD is sized
// against is ~8000 indirect calls/frame, about 0.5% of the measured
// 15.72 ms client frame - affordable, but the only lane that could
// measure it has +/-4% dispersion, EIGHT TIMES the effect. A gate that
// can only ever print "within noise" is ID-124's failure mode one level
// down.
// 2. Doorbell::Wait is a non-virtual template whose spin loop calls ready()
// up to SpinItersPerUs() * spinUs times; at 916 waits/frame with 99.8%
// resolved inside the spin, the predicate runs 1e5-1e6 times per frame
// and reads the watermarks straight off the shared page. That is the
// 31.58%-of-the-GL-thread path. A virtual there is not a rounding
// question.
// 3. The encode path already depends on four inline accessors around its one
// Reserve; virtualising Reserve alone forces either four more virtuals or
// moving R-10's wrap counters behind the seam, and those are deliberately
// encoder-owned.
//
// So lk's gate is an objdump call-count of the encode path, not a wall clock:
// after lk that path has no more out-of-line calls than before. That is
// falsifiable; "within noise" is not.
//
// WHAT THIS HEADER DELIBERATELY DOES NOT DO.
// - It does not define Watermark::Reached or any other predicate that
// SessionRings.h already defines. One definition, one owner.
// - It does not relocate the bodies of RingProducer::Reserve or
// RingConsumer::Pop. Those log (MGLOG_E / MGLOG_D) and use Align8 and
// <cstring>; no header under Transport/ pulls the logger in, and this one
// does not start. They stay out of line and move to ShmLink.cpp in lk.
// - It declares no function it does not define. Every entry point here is
// pure virtual or a POD accessor.
// - It does not regroup RingControl. That regroup is real and necessary
// (CONTRACT-P6.md §8.3) but its rename blast radius is 109 production
// sites, five of them behind a non-Android #if, so it is lk's with a
// published per-file itemisation - not a side effect of declaring a seam.
#pragma once
#include "../Protocol/mg_protocol_base.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
namespace MobileGL::MG_Remote::Transport {
class Doorbell;
// Which end of the link this instance is. Deliberately NOT ITransport's
// TransportRole: that enum's InProcess value names a control-plane
// hand-off, and a data plane's two ends are producer and consumer whatever
// the control plane did.
enum class TransportRoleTag : std::uint32_t {
ClientProducer = 1,
ServerConsumer = 2,
};
// ---- the progress block -------------------------------------------------
//
// The watermarks every wait predicate reads. On ShmLink this aliases the
// shared control page and the loads are cross-process acquire loads; on
// StreamLink it is process-local and a reader thread stores into it from
// decoded progress messages.
//
// THE RULES SURVIVE THE MECHANISM VERBATIM, and that is the point of naming
// the block rather than the page: late-never-early (Ring.h's "BATCHING MAY ONLY MAKE A WATERMARK LATE"), `>=`
// never `==` (SessionRings.h's Watermark::Reached), monotone with a
// backwards move Fatal (Ring.cpp's AdvanceMonotonic). A stream link changes
// only HOW a value arrives, never what it means.
//
// WHY THESE FOUR AND NOT THE WHOLE PAGE, AND WHY THE EVENT FLAGS ARE NOT
// HERE. RingControl's watermark cache line HELD, until lk regrouped it, {appliedSeq,
// submittedSeq, retiredSeq, completedFrameSerial, presentAckSerial}, and
// submittedSeq is PRODUCER-written (Ring.h's "THE FIVE WATERMARKS" block,
// "Advanced by the PRODUCER after it publishes") while the other four are consumer-written - so the
// line has MIXED WRITERS as it stands and no single-writer block can be
// aliased over it. lk's regroup moves submittedSeq out to the producer's
// own line, beside cmdHead, which is the other thing the producer writes;
// what is left IS this struct, and it IS a named member of RingControl,
// pinned there by per-field offsetof static_asserts (Ring.h).
//
// THE TWO EVENT FLAGS ARE DELIBERATELY EXCLUDED, and an earlier draft of
// this header had them in and was wrong. eventRingFull has TWO writers:
// the server latches it with store(1) when SEG_EVENT fills
// (EventRing.h:140) and the CLIENT clears it with an exchange(0) on EVERY
// DRAIN (EventRing.h:200). Promoting it here would put a per-drain RMW by
// the client on the same cache line as appliedSeq - which the server
// release-stores every 64 records and the client's spin predicate reads
// 1e5-1e6 times per frame. That is new false sharing on the hottest line
// in the system, and it would land in exactly the numbers lk's gate has to
// hold constant. They stay in the doorbell/generation group, where mixed
// writers already live beside consumerParked/producerParked, and cross the
// seam through EventFlags() instead.
//
// It was free to regroup while both peers are the same binary; a wire break the day a second build exists,
// which is why it is booked now rather than later.
struct LinkProgress {
std::atomic<std::uint64_t> appliedSeq; // records applied
std::atomic<std::uint64_t> retiredSeq; // GPU finished
std::atomic<std::uint64_t> completedFrameSerial; // releases *RetiredTail / SEG_ADOPT
std::atomic<std::uint64_t> presentAckSerial; // returns present credit
};
// The reverse channel's two flags. Separated from LinkProgress for the
// false-sharing reason above, not for a taxonomic one: both roles read
// eventRingFull in a park predicate, and both roles write it.
struct LinkEventFlags {
std::atomic<std::uint32_t> eventRingFull; // server latches, client clears
std::atomic<std::uint32_t> eventDropped; // server-only counter
};
// ---- the producer's handle ----------------------------------------------
//
// POD state, taken ONCE at attach and used non-virtually thereafter. The
// reserve/commit algorithm is NOT inlined here (see the header comment):
// ShmLink keeps today's out-of-line body, StreamLink writes its own.
// `Base` is null on a link that has no mapping, and a link that publishes
// that shape must answer every span through ResolveSpan.
struct LinkArena {
void* Base = nullptr;
std::uint64_t Capacity = 0;
std::uint64_t Mask = 0;
std::uint64_t LocalHead = 0;
};
// The consumer's mirror of the same.
struct LinkCursor {
const void* Base = nullptr;
std::uint64_t Capacity = 0;
std::uint64_t Mask = 0;
std::uint64_t LocalTail = 0;
};
// A run of bulk bytes named on the wire. On ShmLink `Offset` indexes the
// shared SEG_STAGE mapping; on StreamLink it indexes the trailing staged
// region of the batch that carried the record. MGPBlobRef's spelling and
// every honesty check over it (R-2) are unchanged either way - which is the
// property that lets the whole record catalogue cross a boundary with no
// mapping without a single record layout changing.
struct LinkSpan {
std::uint64_t Offset = 0;
std::uint64_t Size = 0;
};
// Which segment a span or a view belongs to. Mirrors SegmentKind's wire
// values; declared here so ILink does not pull the protocol headers in.
enum class LinkSegment : std::uint32_t {
Cmd = 1,
Stage = 2,
Reply = 3,
Event = 4,
};
// What a link can do. A caller may not infer any of these from the
// transport's role, and a link may not answer "sometimes" - rule G's
// second clause is that a transport DECLARES what it supports and may not
// invent a third answer.
struct LinkCapabilities {
bool SharedMapping = false; // peers see one set of bytes; no copy on read
bool DescriptorPassing = false;
bool PublishIsDelivery = false; // false => Flush() is mandatory before any wait
std::uint64_t MaxRecordBytes = 0;
std::uint64_t MaxReplyBytes = 0;
};
// -------------------------------------------------------------------------
// The seam itself.
//
// Nineteen entry points, every one taken at attach, at a park boundary, or
// once per control operation. None on the hot path.
// -------------------------------------------------------------------------
class ILink {
public:
virtual ~ILink() = default;
ILink(const ILink&) = delete;
ILink& operator=(const ILink&) = delete;
// ---- setup ----------------------------------------------------------
virtual LinkCapabilities Capabilities() const = 0;
// The watermark block. Taken once; every wait predicate reads through
// the returned pointer with no further virtual dispatch. Never null on
// an attached link.
virtual LinkProgress* Progress() = 0;
// The reverse channel's flags. A separate ACCESSOR, for the reason
// LinkEventFlags documents. NOT a separate cache line: they sit in the
// doorbell/generation group beside serverEpoch, which is where mixed
// writers already live.
virtual LinkEventFlags* EventFlags() = 0;
// The command-record arena (producer side) and cursor (consumer side).
// Exactly one of the two is valid on a given peer.
virtual LinkArena* RecordArena() = 0;
virtual LinkCursor* RecordCursor() = 0;
// ---- bulk bytes -----------------------------------------------------
// Reserve `bytes` of staging and return where the record should name
// it. MOBILEGL_ERR_RING_OVERRUN when the request cannot be satisfied at
// any occupancy; the caller's existing back-pressure path is unchanged.
virtual MobileGLResult StageBytes(std::uint64_t bytes, LinkSpan* outSpan,
void** outWritePtr) = 0;
// Resolve a span the peer named. On a shared mapping this is pointer
// arithmetic over the peer's segment; on a stream it points into the
// reassembly buffer of the batch that carried the record, and the
// lifetime rule ("valid until retiredSeq passes the record") is
// restated against that buffer rather than against the mapping.
//
// THIS IS THE METHOD WRITING StreamLink REVEALED. The brief's list -
// progress transmission, send window, flush - did not name it, and
// without it a stream link has no way to answer the eleven
// ResolveOrFatal call sites in the decoder.
virtual MobileGLResult ResolveSpan(LinkSegment segment, LinkSpan span,
const void** outPtr) = 0;
// ---- replies --------------------------------------------------------
virtual MobileGLResult PostReply(std::uint64_t seq, std::int32_t status,
const void* payload, std::uint64_t size) = 0;
virtual MobileGLResult ReadReply(std::uint64_t seq, std::int32_t* outStatus,
const void** outPayload, std::uint64_t* outSize) = 0;
// ---- the reverse channel --------------------------------------------
virtual LinkArena* EventArena() = 0;
virtual LinkCursor* EventCursor() = 0;
// ---- wakeups --------------------------------------------------------
//
// THESE TWO RETIRE CONTRACT-P5 §3.9. That ruling kept the doorbell
// accessors on the session "so that this stays one switch in one file
// rather than two virtuals every transport has to invent a home for"
// (ServerSession.cpp:709-724) - and the switch it produced aborts for
// every role but InProcess, so a spawn apply thread dies in
// ConsumerDoorbell before it pops its first record. The seam is the
// home the ruling said did not exist. lk deletes both accessors rather
// than growing them a socket arm.
virtual Doorbell& ConsumerBell() = 0;
virtual Doorbell& ProducerBell() = 0;
// ---- publication -----------------------------------------------------
// Make everything published so far visible to the peer. On a shared
// mapping publish IS delivery and this is a no-op; on a stream it is a
// write(), and CONTRACT-P6.md requires every transition into a wait to
// call it first, or a kWaitReply record sitting in a send buffer while
// the client parks is a hang rather than a slowdown.
virtual MobileGLResult Flush() = 0;
// Push the local progress block to the peer. A no-op on a shared
// mapping, where a release-store IS the transmission. Named separately
// from Flush because the two have different triggers: Flush is about
// records the peer has not seen, this is about watermarks the peer is
// waiting on. The second method writing StreamLink revealed.
virtual MobileGLResult FlushProgress() = 0;
// ---- lifecycle -------------------------------------------------------
virtual bool Attached() const = 0;
virtual void Detach() = 0;
virtual TransportRoleTag Role() const = 0;
protected:
ILink() = default;
};
} // namespace MobileGL::MG_Remote::Transport
+16 -10
View File
@@ -391,7 +391,7 @@ namespace MobileGL::MG_Remote::Transport {
}
void AdvanceApplied(RingControl& control, std::uint64_t seq) {
AdvanceMonotonic(control.appliedSeq, seq, "appliedSeq");
AdvanceMonotonic(control.Progress.appliedSeq, seq, "appliedSeq");
}
void AdvanceRetired(RingControl& control, std::uint64_t seq) {
@@ -399,16 +399,16 @@ namespace MobileGL::MG_Remote::Transport {
// reclaims behind it, so a retire ahead of the apply hands live bytes
// back to the producer. Clamped rather than refused, because a
// caller that retires "everything applied" is the normal shape.
const std::uint64_t applied = control.appliedSeq.load(std::memory_order_acquire);
AdvanceMonotonic(control.retiredSeq, seq > applied ? applied : seq, "retiredSeq");
const std::uint64_t applied = control.Progress.appliedSeq.load(std::memory_order_acquire);
AdvanceMonotonic(control.Progress.retiredSeq, seq > applied ? applied : seq, "retiredSeq");
}
void AdvanceCompletedFrame(RingControl& control, std::uint64_t serial) {
AdvanceMonotonic(control.completedFrameSerial, serial, "completedFrameSerial");
AdvanceMonotonic(control.Progress.completedFrameSerial, serial, "completedFrameSerial");
}
void AdvancePresentAck(RingControl& control, std::uint64_t serial) {
AdvanceMonotonic(control.presentAckSerial, serial, "presentAckSerial");
AdvanceMonotonic(control.Progress.presentAckSerial, serial, "presentAckSerial");
}
} // namespace Watermark
@@ -488,7 +488,7 @@ namespace MobileGL::MG_Remote::Transport {
return SessionWait::TimedOut;
}
RingControl* control = m_control;
return Park([control, seq] { return Watermark::Reached(control->appliedSeq, seq); },
return Park([control, seq] { return Watermark::Reached(control->Progress.appliedSeq, seq); },
timeoutMs);
}
@@ -497,7 +497,7 @@ namespace MobileGL::MG_Remote::Transport {
return SessionWait::TimedOut;
}
RingControl* control = m_control;
return Park([control, serial] { return Watermark::Reached(control->presentAckSerial, serial); },
return Park([control, serial] { return Watermark::Reached(control->Progress.presentAckSerial, serial); },
timeoutMs);
}
@@ -515,7 +515,7 @@ namespace MobileGL::MG_Remote::Transport {
RingControl* control = m_control;
return Park(
[control, seq] {
return Watermark::Reached(control->appliedSeq, seq) ||
return Watermark::Reached(control->Progress.appliedSeq, seq) ||
control->eventRingFull.load(std::memory_order_acquire) != 0;
},
timeoutMs);
@@ -529,7 +529,7 @@ namespace MobileGL::MG_Remote::Transport {
RingControl* control = m_control;
return Park(
[control, serial] {
return Watermark::Reached(control->presentAckSerial, serial) ||
return Watermark::Reached(control->Progress.presentAckSerial, serial) ||
control->eventRingFull.load(std::memory_order_acquire) != 0;
},
timeoutMs);
@@ -554,7 +554,7 @@ namespace MobileGL::MG_Remote::Transport {
m_peerBell = peerBell;
m_selfBell = selfBell;
m_spinUs = spinUs;
m_appliedSeq = control == nullptr ? 0 : control->appliedSeq.load(std::memory_order_acquire);
m_appliedSeq = control == nullptr ? 0 : control->Progress.appliedSeq.load(std::memory_order_acquire);
m_retirableCursor = cmd == nullptr ? 0 : cmd->LocalTail();
m_borrowHeld = false;
}
@@ -678,6 +678,12 @@ namespace MobileGL::MG_Remote::Transport {
mix(inputs.RendererInfoCodecVersion);
mix(inputs.OpCount);
mix(inputs.AbiVersion);
// CONTRACT-P6 4.2: THE BUILD SYSTEM'S OWN ANSWER, mixed before the bytes and separately
// from them. `BuildStampPresent == 0` means the build could not determine a commit at
// all; that is a different claim from "the commit is the empty string", and before this
// field existed the two collapsed - so every stampless build agreed with every other,
// which is the exact agreement the stamp is there to refuse.
mix(inputs.BuildStampPresent);
// A presence marker before the bytes, so that "no stamp" (nullptr) and
// "an empty stamp" ("") are different inputs rather than the same
// absence of bytes.
+93 -7
View File
@@ -43,13 +43,19 @@
// land without changing shape.
//
// ---------------------------------------------------------------------------
// THE FIVE WATERMARKS (P5 R-9). One sentence each, and they are a contract:
// THE FIVE WATERMARKS (P5 R-9). Four of them are Transport::LinkProgress and
// are reached as `control.Progress.<name>`; submittedSeq is the fifth and stays
// at RingControl scope, on the producer's line (lk, CONTRACT-P6 §8.3).
// One sentence each, and they are a contract:
// every one of the five was declared here at P0 and written by nobody but
// InitRingControl, so until P5 there was nothing to disagree with.
//
// submittedSeq Advanced by the PRODUCER after it publishes. NOBODY
// WAITS ON IT - it is diagnostic, the answer to "how far
// ahead of the server is the client right now".
// ahead of the server is the client right now". It lives
// on the producer's own cache line beside cmdHead; it is
// the ONE of the five that is not in LinkProgress, and
// that is why LinkProgress can be single-writer.
// appliedSeq Advanced by the CONSUMER for EVERY SINGLE RECORD it
// applies. The client's verb barrier and every reply wait
// read it, so it is the one watermark P5 FORBIDS BATCHING:
@@ -88,9 +94,11 @@
#pragma once
#include "../Protocol/mg_protocol_base.h"
#include "ILink.h" // LinkProgress: the four consumer-written watermarks, lk
#include <atomic>
#include <cstddef>
#include <type_traits>
#include <cstdint>
namespace MobileGL::MG_Remote::Transport {
@@ -99,7 +107,13 @@ namespace MobileGL::MG_Remote::Transport {
// each contended group on its own cache line.
struct alignas(4096) RingControl {
// ---- SEG_CMD cursors ------------------------------------------------
//
// cmdHead and submittedSeq share a line because they share a WRITER:
// the producer publishes the head and then stamps how far it has got.
// submittedSeq used to sit with the four consumer-written watermarks,
// which made that group mixed-writer and unaliasable (lk, §8.3).
alignas(64) std::atomic<std::uint64_t> cmdHead; // producer: bytes written
std::atomic<std::uint64_t> submittedSeq; // producer: records published
alignas(64) std::atomic<std::uint64_t> cmdAppliedTail; // consumer: bytes decoded/copied out
std::atomic<std::uint64_t> cmdRetiredTail; // consumer: borrowed slots released
@@ -132,11 +146,16 @@ namespace MobileGL::MG_Remote::Transport {
std::atomic<std::uint64_t> stageRetiredTail;
// ---- sequence / frame watermarks -------------------------------------
alignas(64) std::atomic<std::uint64_t> appliedSeq; // records applied
std::atomic<std::uint64_t> submittedSeq; // handed to the driver
std::atomic<std::uint64_t> retiredSeq; // GPU finished
std::atomic<std::uint64_t> completedFrameSerial;
std::atomic<std::uint64_t> presentAckSerial;
//
// THE CONSUMER-WRITTEN FOUR, AND ONLY THOSE. This is Transport::LinkProgress
// (ILink.h), named so that a data plane with no shared page can own the
// same four values and every wait predicate in SessionRings.h keeps ONE
// implementation at source level. Single-writer by construction now that
// submittedSeq has moved up to the producer's line; the two event flags
// stay in the doorbell group below, because the client clears
// eventRingFull with an RMW on every drain and that traffic may not land
// on the line the client also spins on.
alignas(64) LinkProgress Progress;
// ---- doorbell / generation -------------------------------------------
alignas(64) std::atomic<std::uint32_t> serverEpoch; // ++ on context loss / server restart
@@ -148,6 +167,73 @@ namespace MobileGL::MG_Remote::Transport {
};
static_assert(sizeof(RingControl) == 4096, "RingControl must be exactly one page");
// lk (CONTRACT-P6 §8.3). The regroup is free while both peers are the same binary
// and a LAYOUT BREAK the day they are not, so the shape is pinned here - by asserts
// that can each go red for the reason they exist, which the first revision of this
// block did not manage.
//
// NOTHING ELSE IN THE TREE PINS ANY OF THIS. The ABI fingerprint
// (SessionRings.h's AbiFingerprintInputs) takes three sizeofs, the caps geometry, two
// codec versions, kOpCount, the protocol version and the build stamp - and NO input
// from this page at all. sizeof(RingControl) is 4096 whatever the members do, because
// alignas(4096) makes it so. So a silent field reorder here would leave every gate in
// the tree green and both peers hashing identically.
static_assert(std::is_standard_layout_v<RingControl> && std::is_standard_layout_v<LinkProgress>,
"the offsetof gates below are defined only for standard-layout types");
// The producer's line: cmdHead and submittedSeq, together and nothing else waiting on them.
static_assert(offsetof(RingControl, submittedSeq) == offsetof(RingControl, cmdHead) + 8,
"submittedSeq sits immediately after cmdHead");
static_assert(offsetof(RingControl, submittedSeq) / 64 == offsetof(RingControl, cmdHead) / 64,
"submittedSeq shares the producer's cache line with cmdHead");
// The Progress line, and it owns that line ALONE.
//
// Written as `serverEpoch == Progress + 64` rather than the obvious
// `Progress + sizeof(LinkProgress) <= offsetof(serverEpoch)`, because the obvious one
// CANNOT GO RED: serverEpoch is alignas(64) and is declared next, so the compiler puts
// it at the following 64-multiple no matter what precedes it, and the `<=` holds for
// every layout including a wrong one.
//
// WHAT THIS PAIR DOES NOT CATCH, stated because a gate nobody can falsify is worse
// than no gate: a SMALL member inserted between Progress and serverEpoch lands at
// offset 288, inside Progress's own line - and serverEpoch's alignas(64) absorbs it,
// so both asserts still pass. Verified by trying it. Up to 32 bytes can be hidden
// there. Growth INSIDE LinkProgress is caught, by sizeof below; growth BESIDE it is
// not, and the only thing standing between that and a false-sharing regression is
// this comment and the group's own.
static_assert(offsetof(RingControl, Progress) % 64 == 0,
"LinkProgress starts a cache line of its own");
static_assert(offsetof(RingControl, serverEpoch) == offsetof(RingControl, Progress) + 64,
"the Progress line holds Progress and nothing else");
// PER FIELD, which is what §8.3 asks for and what the aggregate asserts above cannot
// do: the field ORDER inside LinkProgress is a wire-visible fact about a page both
// roles map, and swapping two of them passes every other check in this file.
static_assert(offsetof(LinkProgress, appliedSeq) == 0, "LinkProgress field order: appliedSeq");
static_assert(offsetof(LinkProgress, retiredSeq) == 8, "LinkProgress field order: retiredSeq");
static_assert(offsetof(LinkProgress, completedFrameSerial) == 16,
"LinkProgress field order: completedFrameSerial");
static_assert(offsetof(LinkProgress, presentAckSerial) == 24,
"LinkProgress field order: presentAckSerial");
static_assert(sizeof(LinkProgress) == 32,
"four consumer-written watermarks; the event flags are NOT in here");
// The two event flags stay in the doorbell group on purpose (see the group's comment).
// LinkEventFlags mirrors them, so the mirror's shape is pinned too.
static_assert(offsetof(RingControl, eventDropped) == offsetof(RingControl, eventRingFull) + 4,
"the two event flags are adjacent, in that order");
static_assert(offsetof(RingControl, eventRingFull) / 64 == offsetof(RingControl, serverEpoch) / 64,
"the event flags share the doorbell group's line, NOT the Progress line");
static_assert(offsetof(LinkEventFlags, eventRingFull) == 0 &&
offsetof(LinkEventFlags, eventDropped) == 4 && sizeof(LinkEventFlags) == 8,
"LinkEventFlags mirrors the pair in RingControl");
// The page's real content must fit the page it claims. sizeof(RingControl) == 4096
// above cannot catch a member that grew, because alignas(4096) forces that number;
// the struct's content ends far short of it and the tail is padding.
static_assert(offsetof(RingControl, eventDropped) + sizeof(std::uint32_t) <= 4096,
"RingControl's members must fit the page it claims to be");
static_assert(alignof(RingControl) == 4096, "RingControl must be page aligned");
static_assert(std::atomic<std::uint64_t>::is_always_lock_free,
"the ring cursors are shared across processes: they must be lock-free");
+36 -3
View File
@@ -159,6 +159,24 @@ namespace MobileGL::MG_Remote::Transport {
// travels in SegmentRef instead), so there it still aliases and says so.
MobileGLResult AttachInProcess(SessionSegments& owner, MemoryRole role);
// P6 `sm`: the spawn client's half. The four descriptors arrived over
// SCM_RIGHTS and this side adopts and maps them.
//
// IT IS THE SAME THREE CALLS AttachInProcess ALREADY MAKES - Adopt, then
// Map, per slot - because that was the point of writing the inproc attach
// as dup+Adopt+Map rather than as an alias (see the comment above it).
// The fstat size check inside Adopt, the alignment, the peer lifetime and
// the ledger booking have all been exercised on every inproc run since
// P5; what is new here is only where the fd came from.
//
// OWNERSHIP: on success this object owns all four descriptors and closes
// them in Close(). On failure it closes none of them - the caller still
// owns what it received and is the only one that can report which slot
// failed, so a half-consuming failure path would lose descriptors in the
// one situation where the diagnostic matters.
MobileGLResult AdoptFromDescriptors(const int fds[4], const std::uint64_t sizes[4],
std::uint32_t replySlotCount, MemoryRole role);
void Close();
bool Valid() const { return m_valid; }
@@ -558,10 +576,25 @@ namespace MobileGL::MG_Remote::Transport {
// MOBILEGL_ABI_VERSION(major, minor): a protocol change that left every
// struct the same size, which nothing above can see.
std::uint32_t AbiVersion = 0;
// GIT_COMMIT_HASH_SHORT: two builds of the same sizes can still disagree
// about a FIELD ORDER, which no sizeof can see. nullptr and "" are
// distinct inputs and neither equals a real stamp.
// MOBILEGL_BUILD_STAMP_VALUE: two builds of the same sizes can still
// disagree about a FIELD ORDER, which no sizeof can see. nullptr and ""
// are distinct inputs and neither equals a real stamp.
const char* BuildStamp = nullptr;
// CONTRACT-P6 4.2. WHETHER THE BUILD COULD NAME ITS COMMIT AT ALL, which
// is not the same question as whether BuildStamp is empty - and telling
// them apart is the entire fix.
//
// The old mix took GIT_COMMIT_HASH_SHORT, and a `git rev-parse` that
// FAILED yielded "" with nothing reporting it (no RESULT_VARIABLE).
// Every stampless build in the world then mixed the same "" and agreed
// with every other, which is precisely the agreement the stamp exists to
// refuse. Measured in this worktree: WSL cannot resolve the Windows path
// in its `.git` file, so every WSL build was stampless and silent.
//
// Mixed as its own field so that 0-with-"" and 1-with-"" are different
// fingerprints: a build that says "I have no stamp" must not collide
// with one whose stamp genuinely is the empty string.
std::uint32_t BuildStampPresent = 0;
};
// FNV-1a over every field above, in declaration order. Never 0: that value is
@@ -373,6 +373,65 @@ namespace MobileGL::MG_Remote::Transport {
return MOBILEGL_OK;
}
MobileGLResult SessionSegments::AdoptFromDescriptors(const int fds[4],
const std::uint64_t sizes[4],
std::uint32_t replySlotCount,
MemoryRole role) {
Close();
#if defined(_WIN32)
(void)fds; (void)sizes; (void)replySlotCount; (void)role;
// ShmSegment::Adopt is POSIX-only and a Windows peer resolves the section
// by the name in SegmentRef instead. Refused BY NAME rather than silently
// producing an unmapped session (CONTRACT-P6 §2.6).
MGLOG_E("MG_Remote session: AdoptFromDescriptors is POSIX-only - P6 lands POSIX only");
return MOBILEGL_ERR_UNSUPPORTED;
#else
for (std::size_t index = 0; index < kSlotCount; ++index) {
if (fds[index] < 0 || sizes[index] == 0) {
MGLOG_E("MG_Remote session: slot %zu arrived with fd=%d size=%llu - the server's "
"SCM_RIGHTS hand-off is incomplete",
index, fds[index], static_cast<unsigned long long>(sizes[index]));
Close();
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
}
m_owns = true;
for (std::size_t index = 0; index < kSlotCount; ++index) {
// Adopt takes ownership only on success, and it fstats the descriptor
// against the announced size - which is the only bound there is on a
// peer's claim about how big a segment is (CONTRACT-P6 §4.4 notes it
// has no analogue on a link with no fd).
const MobileGLResult adopted = ShmSegment::Adopt(fds[index], sizes[index],
m_owned[index]);
if (adopted != MOBILEGL_OK) {
MGLOG_E("MG_Remote session: adopting slot %zu (fd=%d, %llu bytes) failed",
index, fds[index], static_cast<unsigned long long>(sizes[index]));
Close();
return adopted;
}
const MobileGLResult mapped = m_owned[index].Map(false);
if (mapped != MOBILEGL_OK) {
Close();
return mapped;
}
}
m_replySlotCount = replySlotCount;
// NOT DeriveViews' control-page initialisation: the SERVER created these
// and already initialised both RingControls. Re-initialising here would
// zero the owner's cursors out from under a session that is already
// running - the same reason AttachInProcess does not do it either.
DeriveViews();
if (!m_valid) {
Close();
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
m_role = role;
LedgerAddSegment(role, m_mappedBytes);
m_booked = true;
return MOBILEGL_OK;
#endif
}
void SessionSegments::DeriveViews() {
m_valid = false;
if (m_owns) {
@@ -0,0 +1,532 @@
// MobileGL - MobileGL/MG_Remote/Transport/SocketTransport.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#include "SocketTransport.h"
#include "Doorbell.h" // kWaitForever
#include "FdPassing.h"
#include "WireLog.h"
#include <cerrno>
#include <cstddef>
#include <cstring>
#include <memory>
#if defined(__unix__) || defined(__APPLE__) || defined(__ANDROID__)
# define MOBILEGL_SOCKET_TRANSPORT_POSIX 1
# include <poll.h>
# include <sys/stat.h>
# include <sys/un.h>
# include <sys/socket.h>
# include <sys/types.h>
# include <unistd.h>
#else
# define MOBILEGL_SOCKET_TRANSPORT_POSIX 0
#endif
namespace MobileGL::MG_Remote::Transport {
#if MOBILEGL_SOCKET_TRANSPORT_POSIX
namespace {
constexpr std::uint64_t kPumpChunkBytes = 64ull * 1024;
void CloseIfOpen(int& fd) {
if (fd >= 0) {
::close(fd);
fd = -1;
}
}
// poll() for readability. Returns:
// 1 readable 0 timed out -1 error (errno set)
// EINTR is retried rather than reported: a signal is not a transport
// event, and reporting it as one would make every caller's timeout
// budget a lie on a process that takes signals (and `sm`'s child takes
// SIGCHLD by construction).
int WaitReadable(int fd, std::uint32_t timeoutMs) {
for (;;) {
struct pollfd pfd {};
pfd.fd = fd;
pfd.events = POLLIN;
const int timeout =
timeoutMs == kWaitForever ? -1 : static_cast<int>(timeoutMs);
const int rc = ::poll(&pfd, 1, timeout);
if (rc < 0 && errno == EINTR) {
continue;
}
return rc;
}
}
} // namespace
namespace {
// A filesystem AF_UNIX path, bounded by sun_path. Refused BY NAME when it
// does not fit rather than silently truncated - a truncated path is a
// different socket, and both sides would then "succeed" onto two
// different names.
// A LEADING '@' MEANS THE ABSTRACT NAMESPACE, which is the convention systemd and D-Bus
// use and the only rendezvous that works on Android.
//
// A filesystem AF_UNIX endpoint needs a writable directory, and an Android app has no
// /tmp - measured, not assumed: the first device run of the spawn arm launched its server
// fine and then died on `could not connect to "/tmp/mgl-15731-...sock" ... No such file or
// directory`, because bind() in the child had nowhere to put the node. The app's own cache
// dir would work, but only if every integrator remembered to say where it is, and the
// library has no way to ask.
//
// An abstract name has no filesystem presence at all: no directory, no mode bits, no stale
// node to unlink after a crash - which is the bind() failure `Listen` currently works
// around. It is scoped to the network namespace, so the two processes of ONE app find each
// other and nothing else can, which is exactly the reach this needs.
//
// Linux-only by construction. A path without '@' still works everywhere, and that is what
// an explicit endpoint (P12's "connect to something somebody else is listening on") uses.
bool IsAbstractEndpoint(const std::string& path) {
return !path.empty() && path[0] == '@';
}
bool FillAddress(const std::string& path, sockaddr_un* out, socklen_t* outLen) {
std::memset(out, 0, sizeof(*out));
out->sun_family = AF_UNIX;
if (path.empty() || path.size() >= sizeof(out->sun_path)) {
WireLogError("MG_Remote SocketTransport: endpoint path is empty or longer than "
"sun_path allows (%zu >= %zu): \"%s\"",
path.size(), sizeof(out->sun_path), path.c_str());
return false;
}
if (IsAbstractEndpoint(path)) {
// sun_path[0] STAYS NUL and the rest is the name. The length carries the name's
// end - there is no terminator - so it is offsetof + 1 + (size - 1), which is
// offsetof + size. Getting this wrong does not fail: it binds a DIFFERENT name
// (one padded with NULs), and the peer then connects to something that is not
// there.
std::memcpy(out->sun_path + 1, path.c_str() + 1, path.size() - 1);
*outLen = static_cast<socklen_t>(offsetof(sockaddr_un, sun_path) + path.size());
return true;
}
std::memcpy(out->sun_path, path.c_str(), path.size());
*outLen = static_cast<socklen_t>(offsetof(sockaddr_un, sun_path) + path.size() + 1);
return true;
}
MobileGLResult ConnectOne(const std::string& path, std::uint32_t timeoutMs, int* outFd) {
sockaddr_un address{};
socklen_t length = 0;
if (!FillAddress(path, &address, &length)) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
// Retry with a bound budget: the server may not have reached bind()
// yet. An exhausted budget is a NAMED refusal, never a fallback -
// CONTRACT-P6 §3.4 calls for a bounded retry and says so.
const std::uint32_t deadline = timeoutMs == 0 ? 1 : timeoutMs;
for (std::uint32_t waited = 0;; waited += 5) {
const int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
WireLogError("MG_Remote SocketTransport: socket() failed: %s",
std::strerror(errno));
return MOBILEGL_ERR_UNSUPPORTED;
}
if (::connect(fd, reinterpret_cast<sockaddr*>(&address), length) == 0) {
*outFd = fd;
return MOBILEGL_OK;
}
const int failure = errno;
::close(fd);
if (waited >= deadline) {
WireLogError("MG_Remote SocketTransport: could not connect to \"%s\" within "
"%u ms: %s - REFUSING BY NAME, there is no monolith fallback "
"from here",
path.c_str(), deadline, std::strerror(failure));
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
::usleep(5000);
}
}
} // namespace
MobileGLResult SocketTransport::Listen(const std::string& path, int* outListenFd) {
if (outListenFd == nullptr) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
*outListenFd = -1;
sockaddr_un address{};
socklen_t length = 0;
if (!FillAddress(path, &address, &length)) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
// A stale socket file from a server that died is the normal case, not the
// exceptional one, and bind() fails on it with EADDRINUSE. Unlinking first
// is what every AF_UNIX server does; the alternative is a server that
// cannot restart until someone cleans up by hand. An ABSTRACT name has no
// node to go stale and unlink("@...") would delete a file of that literal
// name if one happened to exist.
const bool abstractEndpoint = IsAbstractEndpoint(path);
if (!abstractEndpoint) {
::unlink(path.c_str());
}
const int listenFd = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (listenFd < 0) {
WireLogError("MG_Remote SocketTransport: socket() failed: %s", std::strerror(errno));
return MOBILEGL_ERR_UNSUPPORTED;
}
if (::bind(listenFd, reinterpret_cast<sockaddr*>(&address), length) != 0) {
WireLogError("MG_Remote SocketTransport: bind(\"%s\") failed: %s", path.c_str(),
std::strerror(errno));
::close(listenFd);
return MOBILEGL_ERR_UNSUPPORTED;
}
// 0600: the rendezvous is between one user's processes. An AF_UNIX path
// is a filesystem object and its mode is the only access control there is.
// An abstract name is not a filesystem object and has none; its reach is
// the network namespace, which for an Android app is the app.
if (!abstractEndpoint) {
::chmod(path.c_str(), 0600);
}
if (::listen(listenFd, 4) != 0) {
WireLogError("MG_Remote SocketTransport: listen(\"%s\") failed: %s", path.c_str(),
std::strerror(errno));
::close(listenFd);
if (!abstractEndpoint) {
::unlink(path.c_str());
}
return MOBILEGL_ERR_UNSUPPORTED;
}
*outListenFd = listenFd;
return MOBILEGL_OK;
}
MobileGLResult SocketTransport::AcceptPair(int listenFd, std::uint32_t timeoutMs,
std::unique_ptr<SocketTransport>& outServer) {
outServer.reset();
if (listenFd < 0) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
int accepted[2] = {-1, -1};
for (int index = 0; index < 2; ++index) {
const int ready = WaitReadable(listenFd, timeoutMs);
if (ready <= 0) {
for (int fd : accepted) {
if (fd >= 0) ::close(fd);
}
// Half a client is not a client. Both connections or neither, so
// a peer that died between the two cannot leave a session that
// looks up but has no way to receive a descriptor.
WireLogError("MG_Remote SocketTransport: only %d of 2 connections arrived within "
"%u ms", index, timeoutMs);
return ready == 0 ? MOBILEGL_ERR_TIMEOUT : MOBILEGL_ERR_TRANSPORT_CLOSED;
}
accepted[index] = ::accept(listenFd, nullptr, nullptr);
if (accepted[index] < 0) {
for (int fd : accepted) {
if (fd >= 0) ::close(fd);
}
WireLogError("MG_Remote SocketTransport: accept failed: %s", std::strerror(errno));
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
}
// First connection is control, second is aux. The order IS the protocol;
// it is stated here and in ConnectTo and nowhere else.
outServer = std::make_unique<SocketTransport>(accepted[0], accepted[1],
TransportRole::Server);
return MOBILEGL_OK;
}
MobileGLResult SocketTransport::ConnectTo(const std::string& path, std::uint32_t timeoutMs,
std::unique_ptr<SocketTransport>& outClient) {
outClient.reset();
int control = -1;
const MobileGLResult first = ConnectOne(path, timeoutMs, &control);
if (first != MOBILEGL_OK) {
return first;
}
int aux = -1;
// The second connect has a SHORT budget: the server is provably up - we
// just connected to it - so a slow second connection means something is
// wrong rather than something is starting.
const MobileGLResult second = ConnectOne(path, 2000, &aux);
if (second != MOBILEGL_OK) {
::close(control);
return second;
}
outClient = std::make_unique<SocketTransport>(control, aux, TransportRole::Client);
return MOBILEGL_OK;
}
MobileGLResult SocketTransport::CreatePair(std::unique_ptr<SocketTransport>& outClient,
std::unique_ptr<SocketTransport>& outServer) {
outClient.reset();
outServer.reset();
int stream[2] = {-1, -1};
// SOCK_STREAM, not SOCK_SEQPACKET: Doorbell.h:390-398 already chose a
// stream socket for the bell so that a closed peer surfaces as
// POLLIN|POLLHUP with recv()==0 rather than as a hang, and the control
// plane must not disagree with the bell about what death looks like.
// Framing.h is what makes a stream safe: the message boundary is in the
// payload, not in the socket.
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, stream) != 0) {
WireLogError("MG_Remote SocketTransport: socketpair(SOCK_STREAM) failed: %s",
std::strerror(errno));
return MOBILEGL_ERR_UNSUPPORTED;
}
int aux[2] = {-1, -1};
const MobileGLResult auxResult = FdPassing::CreateSocketPair(aux);
if (auxResult != MOBILEGL_OK) {
::close(stream[0]);
::close(stream[1]);
WireLogError("MG_Remote SocketTransport: the aux (SCM_RIGHTS) pair failed");
return auxResult;
}
outClient = std::make_unique<SocketTransport>(stream[0], aux[0], TransportRole::Client);
outServer = std::make_unique<SocketTransport>(stream[1], aux[1], TransportRole::Server);
return MOBILEGL_OK;
}
SocketTransport::SocketTransport(int streamFd, int auxFd, TransportRole role)
: m_streamFd(streamFd), m_auxFd(auxFd), m_role(role) {}
SocketTransport::~SocketTransport() { Shutdown(); }
MobileGLResult SocketTransport::SendFrame(MobileGLByteSpan bytes) {
if (bytes.size > kMaxFramePayloadSize) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
if (bytes.size != 0 && bytes.data == nullptr) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
std::lock_guard<std::mutex> lock(m_sendMutex);
if (m_closed || m_streamFd < 0) {
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
// Framed into ONE buffer and written as one span. Not because a stream
// needs it - it does not - but because a partial write of the header
// followed by a failure would leave the peer's reassembler parked on a
// length it will never receive, which is indistinguishable from a slow
// sender and therefore not detectable at all.
std::vector<std::uint8_t> framed;
framed.reserve(static_cast<std::size_t>(kFrameHeaderSize + bytes.size));
const MobileGLResult appended = AppendFrame(framed, bytes.data, bytes.size);
if (appended != MOBILEGL_OK) {
return appended;
}
std::uint64_t written = 0;
while (written < framed.size()) {
const ssize_t n = ::send(m_streamFd, framed.data() + written,
static_cast<std::size_t>(framed.size() - written),
MSG_NOSIGNAL);
if (n > 0) {
written += static_cast<std::uint64_t>(n);
continue;
}
if (n < 0 && errno == EINTR) {
continue;
}
// EPIPE / ECONNRESET are the peer being gone, which is a transport
// state and not an error to shout about: the device-lost latch (dl)
// is what turns it into a GL-visible fact.
if (n < 0 && (errno == EPIPE || errno == ECONNRESET)) {
m_closed = true;
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
WireLogError("MG_Remote SocketTransport: send failed after %llu of %llu bytes: %s",
static_cast<unsigned long long>(written),
static_cast<unsigned long long>(framed.size()), std::strerror(errno));
m_closed = true;
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
return MOBILEGL_OK;
}
MobileGLResult SocketTransport::PumpOnce(std::uint32_t timeoutMs) {
// Caller holds m_recvMutex.
if (m_failed) {
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
if (m_streamFd < 0) {
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
const int ready = WaitReadable(m_streamFd, timeoutMs);
if (ready == 0) {
return MOBILEGL_ERR_TIMEOUT;
}
if (ready < 0) {
WireLogError("MG_Remote SocketTransport: poll failed: %s", std::strerror(errno));
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
std::uint8_t chunk[kPumpChunkBytes];
for (;;) {
const ssize_t n = ::recv(m_streamFd, chunk, sizeof(chunk), 0);
if (n > 0) {
const MobileGLResult fed =
m_reader.Feed(chunk, static_cast<std::uint64_t>(n));
if (fed != MOBILEGL_OK) {
// Bad magic or an over-long length. FrameReader latches
// itself failed and never recovers; mirror that here so a
// caller cannot retry its way past a corrupt stream.
m_failed = true;
WireLogError("MG_Remote SocketTransport: framing violated on the stream; "
"the transport is latched failed");
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
return MOBILEGL_OK;
}
if (n == 0) {
// Clean EOF. The peer is gone - but anything already reassembled
// stays readable, which ITransport promises in as many words.
m_closed = true;
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return MOBILEGL_ERR_TIMEOUT;
}
if (errno == ECONNRESET) {
m_closed = true;
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
WireLogError("MG_Remote SocketTransport: recv failed: %s", std::strerror(errno));
m_closed = true;
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
}
MobileGLResult SocketTransport::ReceiveFrame(MobileGLMutableByteSpan buffer,
std::uint64_t* outSize,
std::uint32_t timeoutMs) {
if (outSize == nullptr) {
return MOBILEGL_ERR_INVALID_ARGUMENT;
}
*outSize = 0;
std::lock_guard<std::mutex> lock(m_recvMutex);
if (m_failed) {
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
for (;;) {
// Drain the reassembler FIRST, every time. A message that is already
// whole must be returned even when the peer has since closed, and
// must be returned without a syscall when the caller is polling.
if (m_reader.HasMessage()) {
return m_reader.TakeMessage(buffer, outSize);
}
if (m_closed) {
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
const MobileGLResult pumped = PumpOnce(timeoutMs);
if (pumped == MOBILEGL_OK) {
continue; // maybe a whole message now; maybe a fragment - loop decides
}
if (pumped == MOBILEGL_ERR_TRANSPORT_CLOSED && m_reader.HasMessage()) {
return m_reader.TakeMessage(buffer, outSize);
}
return pumped;
}
}
std::uint64_t SocketTransport::PeekFrameSize() {
std::lock_guard<std::mutex> lock(m_recvMutex);
if (m_failed) {
return 0;
}
if (!m_reader.HasMessage() && !m_closed) {
// A non-blocking pump, so a caller that has not received yet can
// still size its buffer. Errors are not reported here: PeekFrameSize
// answers "how big is the next message", and 0 means "none buffered",
// which is the truthful answer for every failure this can hit.
(void)PumpOnce(0);
}
return m_reader.PendingMessageSize();
}
MobileGLResult SocketTransport::ShareFd(int fd, MobileGLByteSpan sideband) {
if (m_auxFd < 0) {
// A link that declared no descriptor passing. Rule G: it does not
// invent a third answer, and the caller transfers the bytes instead.
return MOBILEGL_ERR_UNSUPPORTED;
}
std::lock_guard<std::mutex> lock(m_sendMutex);
if (m_closed) {
return MOBILEGL_ERR_TRANSPORT_CLOSED;
}
return FdPassing::SendFd(m_auxFd, fd, sideband);
}
MobileGLResult SocketTransport::ReceiveFd(int* outFd, MobileGLMutableByteSpan sideband,
std::uint64_t* outSidebandSize,
std::uint32_t timeoutMs) {
if (m_auxFd < 0) {
return MOBILEGL_ERR_UNSUPPORTED;
}
return FdPassing::ReceiveFd(m_auxFd, outFd, sideband, outSidebandSize, timeoutMs);
}
void SocketTransport::Shutdown() {
// Idempotent, and tears down BOTH directions - which on a socket is what
// closing does anyway. Taking both locks in a fixed order (send, then
// recv) so a concurrent sender and the dedicated reader cannot deadlock
// against each other here; every other path takes exactly one.
std::lock_guard<std::mutex> sendLock(m_sendMutex);
std::lock_guard<std::mutex> recvLock(m_recvMutex);
if (m_streamFd >= 0) {
// shutdown() before close() so a peer blocked in recv() wakes now
// rather than whenever the last duplicate of this fd goes away.
::shutdown(m_streamFd, SHUT_RDWR);
}
CloseIfOpen(m_streamFd);
CloseIfOpen(m_auxFd);
m_closed = true;
}
#else // !MOBILEGL_SOCKET_TRANSPORT_POSIX
// Windows has no SCM_RIGHTS and ShmSegment::Adopt is POSIX-only, so P6 lands
// POSIX only (CONTRACT-P6 §2.6). The refusal is NAMED at construction rather
// than at first use: a transport that accepts a connection and then fails
// every operation is the silent-fallback shape this project forbids.
MobileGLResult SocketTransport::CreatePair(std::unique_ptr<SocketTransport>&,
std::unique_ptr<SocketTransport>&) {
WireLogError("MG_Remote SocketTransport: unsupported on this platform - P6 lands POSIX "
"only (CONTRACT-P6 §2.6); `unix:` and `pipe:` stay named refusals");
return MOBILEGL_ERR_UNSUPPORTED;
}
SocketTransport::SocketTransport(int, int, TransportRole role) : m_role(role) {}
SocketTransport::~SocketTransport() = default;
MobileGLResult SocketTransport::SendFrame(MobileGLByteSpan) { return MOBILEGL_ERR_UNSUPPORTED; }
MobileGLResult SocketTransport::ReceiveFrame(MobileGLMutableByteSpan, std::uint64_t*,
std::uint32_t) {
return MOBILEGL_ERR_UNSUPPORTED;
}
std::uint64_t SocketTransport::PeekFrameSize() { return 0; }
MobileGLResult SocketTransport::ShareFd(int, MobileGLByteSpan) {
return MOBILEGL_ERR_UNSUPPORTED;
}
MobileGLResult SocketTransport::ReceiveFd(int*, MobileGLMutableByteSpan, std::uint64_t*,
std::uint32_t) {
return MOBILEGL_ERR_UNSUPPORTED;
}
MobileGLResult SocketTransport::PumpOnce(std::uint32_t) { return MOBILEGL_ERR_UNSUPPORTED; }
void SocketTransport::Shutdown() { m_closed = true; }
#endif
} // namespace MobileGL::MG_Remote::Transport
@@ -0,0 +1,150 @@
// MobileGL - MobileGL/MG_Remote/Transport/SocketTransport.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// ITransport over a connected stream socket. Package `so` (CONTRACT-P6.md).
//
// WHY THIS IS THE FIRST P6 CODE THAT RUNS. It is the whole control plane for a
// second process, and it needs NOTHING from the second process to be correct:
// CONTRACT-P6 and the spawn plan both require it green over a plain
// socketpair() with two threads, running the WHOLE InProcessTransportTest
// suite, BEFORE a child is ever forked. Same discipline as SessionRings.h's
// "the attach half is the half P6 replaces, so exercise it now" - a transport
// first exercised on the day the process appears is a transport whose bugs all
// arrive at once.
//
// WHAT IT IS NOT. It is not the data plane. The hot path bypasses ITransport
// entirely (ITransport.h) and crosses through ILink, which is a separate seam
// with a separate implementation. This class carries the handshake, surface
// ops, resync, aux requests and fatals - the rare, variable-length,
// must-evolve traffic.
//
// THREE THINGS IT DOES NOT REINVENT, because they are already in the tree and
// already tested:
// Framing.h - AppendFrame writes [u32 'MGLF'][u32 len][payload]; FrameReader
// is a real byte-stream reassembler with the BUFFER_TOO_SMALL
// keep-the-message semantics ITransport requires. A socket
// hands you arbitrary fragments, which is precisely what
// FrameReader was written for and what InProcessTransport's
// message queue never needed.
// FdPassing.h - SCM_RIGHTS over a DEDICATED SOCK_DGRAM aux socket, so an fd
// offer is one datagram and cannot be half-consumed.
// Doorbell.h - SocketDoorbell already exists, is unit-tested, and has NO
// production construction site until now. It was written for
// this and is priced as new work here, not as already paid for.
//
// LIFETIME. The transport owns its stream fd and its aux fd and closes both in
// Shutdown/dtor. Shutdown is idempotent and tears down BOTH directions, which
// is what ITransport promises and what a socket does anyway: after either end
// calls it, the peer's reads return 0 and its sends fail.
#pragma once
#include "Framing.h"
#include "ITransport.h"
#include <cstdint>
#include <string>
#include <memory>
#include <mutex>
#include <vector>
namespace MobileGL::MG_Remote::Transport {
class SocketTransport final : public ITransport {
public:
// Creates a connected pair and hands back one transport per end, with
// the aux (fd-passing) socketpair already made. POSIX only; on a
// platform without SCM_RIGHTS this refuses BY NAME rather than handing
// back a transport whose ShareFd would surprise its caller later.
static MobileGLResult CreatePair(std::unique_ptr<SocketTransport>& outClient,
std::unique_ptr<SocketTransport>& outServer);
// ---- independent processes: listen / connect -----------------------
//
// THE TWO PROCESSES ARE NOT COUPLED BY INHERITANCE. An earlier shape of
// this package forked the server and handed it fds 3..6; that can never
// be the end state, where the server is a standing application and the
// client connects to it from somewhere else entirely - possibly from
// another kernel. So the rendezvous is a NAME, and both sides are
// started by whoever starts them.
//
// TWO CONNECTIONS, not one. SCM_RIGHTS needs a socket of its own: an fd
// offer is a sendmsg whose ancillary data rides with specific BYTES, and
// interleaving those bytes with the framed control stream would make the
// frame reassembler and the descriptor receiver race for the same bytes.
// So the client connects twice to the same listening path - first
// connection is control, second is aux - and the server accepts them in
// that order. One name, no extra configuration, and FdPassing keeps the
// dedicated socket it was written for.
//
// `path` is a filesystem AF_UNIX path. ARCHITECTURE.md §15.1 ruled
// against one for the FORK shape, where the fds were inherited and a
// path would have been a strictly larger attack surface for no gain.
// Independent processes have to name a rendezvous somehow, and a path
// with 0600 permissions in a private directory is the portable answer;
// the abstract namespace is Linux-only and TCP would be reachable off
// the machine.
static MobileGLResult Listen(const std::string& path, int* outListenFd);
// Accepts one client's TWO connections, in order.
static MobileGLResult AcceptPair(int listenFd, std::uint32_t timeoutMs,
std::unique_ptr<SocketTransport>& outServer);
// The client's half: connects twice to `path`.
static MobileGLResult ConnectTo(const std::string& path, std::uint32_t timeoutMs,
std::unique_ptr<SocketTransport>& outClient);
// Adopts an already-connected stream fd - what `sm` uses on each side of
// the fork, where fd 3 is the stream and fd 4 is the aux socket.
// `auxFd` may be -1: the transport then answers MOBILEGL_ERR_UNSUPPORTED
// to ShareFd/ReceiveFd, which is the honest answer for a link that
// cannot pass descriptors (CONTRACT-P6 rule G: a transport declares what
// it supports and may not invent a third answer).
SocketTransport(int streamFd, int auxFd, TransportRole role);
~SocketTransport() override;
MobileGLResult SendFrame(MobileGLByteSpan bytes) override;
MobileGLResult ReceiveFrame(MobileGLMutableByteSpan buffer, std::uint64_t* outSize,
std::uint32_t timeoutMs) override;
std::uint64_t PeekFrameSize() override;
MobileGLResult ShareFd(int fd, MobileGLByteSpan sideband) override;
MobileGLResult ReceiveFd(int* outFd, MobileGLMutableByteSpan sideband,
std::uint64_t* outSidebandSize, std::uint32_t timeoutMs) override;
void Shutdown() override;
TransportRole Role() const override { return m_role; }
// For `sm`'s process discipline and for the arm-proof gate: the fds this
// transport owns, so a test can assert the child inherited exactly these.
int StreamFd() const { return m_streamFd; }
int AuxFd() const { return m_auxFd; }
private:
// Pulls whatever the socket has into the reassembler. Returns
// TRANSPORT_CLOSED on a clean EOF with nothing buffered.
MobileGLResult PumpOnce(std::uint32_t timeoutMs);
int m_streamFd = -1;
int m_auxFd = -1;
TransportRole m_role = TransportRole::Client;
// ITransport's threading rule: callers serialise sends, and receives may
// run on one dedicated reader thread concurrently with those sends. So
// the two directions get one mutex each rather than one shared - a
// single lock would make a blocked receive stall every send, which is
// exactly the wedge the control plane must not have.
std::mutex m_sendMutex;
std::mutex m_recvMutex;
FrameReader m_reader;
bool m_closed = false;
bool m_failed = false; // framing violated: latched, never recovers
};
} // namespace MobileGL::MG_Remote::Transport
+108
View File
@@ -0,0 +1,108 @@
// MobileGL - MobileGL/MG_Remote/Transport/StreamLink.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// ILink's second implementation, DECLARED BY c6 AND IMPLEMENTED BY NOBODY.
// Authority: CONTRACT-P6.md §8.4. Its phase is P6.5.
//
// The link it exists for is TCP across machines (end state re-ruled 2026-09-22,
// CONTRACT-P6.md §10.3, ARCHITECTURE.md §11.9), and it is one axis of two: the
// control plane (ITransport) is chosen independently, so tcp control + shm data
// on one machine is a legal pair and nothing above Transport/ may tell which.
//
// WHY A HEADER FOR SOMETHING THAT DOES NOT EXIST. ILink's adequacy - "can this
// seam name what a byte stream needs?" - is the one claim c6 makes that an
// argument cannot settle and a compile can. If ILink cannot express progress
// transmission, a send window, a flush, span resolution without a mapping, and
// replies that are messages rather than slots, then StreamLink cannot be
// declared against it, and the build says so. That is c6's red-once: delete
// one ILink method this class declares and the build goes red.
//
// It has already earned its keep. Writing it forced THREE methods that the
// original brief's list - progress transmission, send window, flush - did not
// name:
//
// ResolveSpan - a stream has no mapping to do pointer arithmetic over, so
// the eleven ResolveOrFatal sites in the decoder need the
// link to answer, not a segment table. Without it the seam
// was unimplementable for the case it exists for.
// FlushProgress - separate from Flush because the triggers differ: Flush is
// about records the peer has not seen, FlushProgress is
// about watermarks the peer is WAITING on. On a shared page
// a release-store is both; on a stream, conflating them
// either sends too much or hangs a waiter.
// PostReply / - SEG_REPLY carries no message today: the server memcpys
// ReadReply into a slot addressed `seq % slotCount` and the client
// reads it after observing appliedSeq. A stream turns that
// into a real message carrying its own seq, which DELETES
// the slot pool, the modulus addressing and the stamp
// self-check - so the seam has to own the operation rather
// than hand out the pool.
//
// WHAT P6.5 STILL HAS TO SETTLE, recorded here so it is not rediscovered:
// - SEG_STAGE's three ring cursors are DELIBERATELY DEAD (Ring.h's "DEAD IN P5, DELIBERATELY",
// pinned by a test). Staging is an encoder-local linear allocator that
// reclaims on retiredSeq. A send window either revives them COMPLETELY or
// does not use them; the header names the middle state as a guaranteed
// hang rather than a slow path.
// - appliedSeq is excluded BY NAME from lazy publication (Ring.h's "BATCHING MAY ONLY MAKE A WATERMARK LATE").
// P6.5 AMENDS that rule with a flush-on-idle discipline; it does not infer
// around it.
// - one dedicated reader thread per direction per process, or the event-ring
// flow-control deadlock returns as write() blocked against write().
#pragma once
#include "ILink.h"
namespace MobileGL::MG_Remote::Transport {
// Every entry point is a named refusal. There is no partial implementation
// and there may not be one: a half-wired stream link is the shape Ring.h
// warns about, where FreeBytes() falls to zero on the first lap and never
// recovers.
//
// The refusals live in StreamLink.cpp (package P6.5) rather than inline,
// for the reason ILink.h gives: no header under Transport/ pulls the logger
// in, and this one does not start.
class StreamLink final : public ILink {
public:
StreamLink();
~StreamLink() override;
LinkCapabilities Capabilities() const override;
LinkProgress* Progress() override;
LinkEventFlags* EventFlags() override;
LinkArena* RecordArena() override;
LinkCursor* RecordCursor() override;
MobileGLResult StageBytes(std::uint64_t bytes, LinkSpan* outSpan,
void** outWritePtr) override;
MobileGLResult ResolveSpan(LinkSegment segment, LinkSpan span,
const void** outPtr) override;
MobileGLResult PostReply(std::uint64_t seq, std::int32_t status,
const void* payload, std::uint64_t size) override;
MobileGLResult ReadReply(std::uint64_t seq, std::int32_t* outStatus,
const void** outPayload, std::uint64_t* outSize) override;
LinkArena* EventArena() override;
LinkCursor* EventCursor() override;
Doorbell& ConsumerBell() override;
Doorbell& ProducerBell() override;
MobileGLResult Flush() override;
MobileGLResult FlushProgress() override;
bool Attached() const override;
void Detach() override;
TransportRoleTag Role() const override;
};
} // namespace MobileGL::MG_Remote::Transport
+59 -41
View File
@@ -27,6 +27,7 @@
// someone who reads the comment and not this file.
#include "PipeWireCodec.h"
#include <MG_Remote/FatalFunnel.h>
#include <Config.h>
#include <MG_Pipe/MGPipeRenderStateSpans.h>
@@ -37,6 +38,10 @@
#include <MG_Remote/Protocol/generated/protocol_generated.h>
#include <MG_State/GLState/ProgramState/ProgramArtifactsCodec.h>
#include <MG_Util/Debug/Log.h>
// P6 gate 8's two wire counters. MG_Util is BELOW MG_Remote in the build order and the pull build
// has no MG_Remote at all, which is why every counter this file touches is behind
// #if MOBILEGL_PIPE_PUSH - the same guard the header's producer readings live under.
#include <MG_Util/Metrics/PipeStats.h>
#include <cstdlib>
#include <cstring>
@@ -375,14 +380,12 @@ namespace MobileGL::MG_Remote::Wire {
// ---------------------------------------------------------------------------------
void WireProtocolFatal(const char* what, const char* detail) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s\"} %s", what, detail != nullptr ? detail : "");
std::abort();
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s\"} %s", what, detail != nullptr ? detail : "");
}
void WireProtocolFatalAt(const char* what, Uint64 got, Uint64 expected) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s\"} got=%llu expected=%llu", what,
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s\"} got=%llu expected=%llu", what,
static_cast<unsigned long long>(got), static_cast<unsigned long long>(expected));
std::abort();
}
// ---------------------------------------------------------------------------------
@@ -458,20 +461,18 @@ namespace MobileGL::MG_Remote::Wire {
// The monolith shape: Seg = None, Offset = a host address, Size = 0. Legal
// there, and precisely what must not cross (rule A). Reading it as "absent"
// would silently drop the bytes of every record an unconverted emitter sent.
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} a blob with Size 0 "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} a blob with Size 0 "
"declares Seg=%u Offset=%llu; under split a blobref is either fully "
"declared or all three fields zero",
WireOpName(op), static_cast<unsigned>(blob.Seg),
static_cast<unsigned long long>(blob.Offset));
std::abort();
}
return;
}
if (blob.Seg == kSegNone) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} Size=%llu with no segment "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} Size=%llu with no segment "
"(R-2.3): a non-zero Size must name a real SEG_*",
WireOpName(op), static_cast<unsigned long long>(blob.Size));
std::abort();
}
// R-2.3's SECOND HALF: "inside SOME segment" IS NOT THE RULE. Contract table 1 gives
// every client->server content blob - groups A, B and C, all nineteen rows - the ONE
@@ -493,7 +494,7 @@ namespace MobileGL::MG_Remote::Wire {
// seventh name would be a token nothing else in the tree recognises. The SEGMENT is in
// the message, which is what has to be greppable.
if (blob.Seg != kSegStage) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} seg=%u offset=%llu "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} seg=%u offset=%llu "
"size=%llu is not SEG_STAGE(%u); every client->server content blob is "
"staged whole in SEG_STAGE (contract table 1 groups A/B/C, R-10) and no "
"other segment may carry one",
@@ -501,24 +502,21 @@ namespace MobileGL::MG_Remote::Wire {
static_cast<unsigned long long>(blob.Offset),
static_cast<unsigned long long>(blob.Size),
static_cast<unsigned>(kSegStage));
std::abort();
}
if (segments.Resolve(blob.Seg, blob.Offset, blob.Size) == nullptr) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} seg=%u offset=%llu size=%llu "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} seg=%u offset=%llu size=%llu "
"does not lie inside that segment (R-2.3)",
WireOpName(op), static_cast<unsigned>(blob.Seg),
static_cast<unsigned long long>(blob.Offset),
static_cast<unsigned long long>(blob.Size));
std::abort();
}
}
void RequireDeclaredBlob(MGPWireOp op, const MGPBlobRef& blob, const SegmentTable& segments) {
if (blob.Size == 0) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} the record's own fields say "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s.blob\"} the record's own fields say "
"it carries content and its blob declares none (R-2.2 / rule A)",
WireOpName(op));
std::abort();
}
CheckBlobIsHonest(op, blob, segments);
}
@@ -554,12 +552,11 @@ namespace MobileGL::MG_Remote::Wire {
// resolver, reads outside the segment. P5 emits no spans, so this was latent; P8 arms
// it, which is exactly when nobody will be reading this code.
if (segments.Resolve(span.Seg, span.Offset, span.Size) == nullptr) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"host-span\"} seg=%u offset=%llu "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"host-span\"} seg=%u offset=%llu "
"size=%llu does not lie inside that segment (R-2.3 arm 4)",
static_cast<unsigned>(span.Seg),
static_cast<unsigned long long>(span.Offset),
static_cast<unsigned long long>(span.Size));
std::abort();
}
}
@@ -855,14 +852,31 @@ namespace MobileGL::MG_Remote::Wire {
const Uint64 need = Align8(size);
if (need > m_stageCapacity) {
MGLOG_F("MGPipe: Fatal{RingOverrun, \"SEG_STAGE\"} a %llu byte blob cannot fit a "
SessionFail(MGFatalFamily::RingOverrun, "MGPipe: Fatal{RingOverrun, \"SEG_STAGE\"} a %llu byte blob cannot fit a "
"%llu byte staging segment at any occupancy; a blob is staged whole, so a "
"row that cuts its content at MGPipeStageChunkBytes() never reaches this - "
"raise MOBILEGL_IPC_STAGE_MB or report the record type with no cut to the "
"integrator",
static_cast<unsigned long long>(size),
static_cast<unsigned long long>(m_stageCapacity));
std::abort();
}
// P6 GATE 8's FIRST NUMBER (CONTRACT-P6.md §9 item 8): the bytes this producer staged. The
// blob's OWN bytes are recorded, from here - where the request first becomes an allocation
// - because this is the ONE place every writer of SEG_STAGE passes through (StageBytes is
// the only caller, and every buffer walk, texture slab, CSO archive and block name reaches
// them through it), which is what makes the count complete by construction rather than by
// a hand-kept list of callers.
//
// `size`, NOT `need`: the Align8 slack is the allocator's, not content the producer wrote,
// and charging it here would make a workload of 8-byte blobs look like one of 16-byte
// blobs. The allocator's wrap skip is excluded for the same reason.
//
// The sample below the byte add is the same call site for the same reason: the per-blob
// distribution is a property of what the PRODUCER handed over, before the arena rounds it.
if (MG_Util::PipeStats::Enabled()) {
MG_Util::PipeStats::AddBytes(MG_Util::PipeStats::ByteClass::StageSegmentBytes, size);
MG_Util::PipeStats::RecordStagedBlobBytes(size);
}
bool reclaimed = false;
@@ -893,7 +907,7 @@ namespace MobileGL::MG_Remote::Wire {
if (m_stageRetirementBell == nullptr || m_stageMarkFront == m_stageMarks.size()) break;
const Uint64 pending = m_stageMarks[m_stageMarkFront].Seq;
const auto ready = [&] {
return m_control->retiredSeq.load(std::memory_order_acquire) >= pending;
return m_control->Progress.retiredSeq.load(std::memory_order_acquire) >= pending;
};
if (!ready()) {
// The allocation still cannot progress after reclamation. Count this
@@ -907,15 +921,14 @@ namespace MobileGL::MG_Remote::Wire {
// therefore no reverse channel to drain.
if (m_stageWaitHook != nullptr) m_stageWaitHook(m_stageWaitSelf);
if (!ready() && !m_stageRetirementBell->Wait(m_control->producerParked, ready, 0, 5000)) {
MGLOG_F("MGPipe: Fatal{RetirementWaitFailed, \"SEG_STAGE\"} producer wait "
SessionFail(MGFatalFamily::RetirementWaitFailed, "MGPipe: Fatal{RetirementWaitFailed, \"SEG_STAGE\"} producer wait "
"ended before the pending allocation retired (shutdown or timeout)");
std::abort();
}
if (m_stageWaitHook != nullptr) m_stageWaitHook(m_stageWaitSelf);
}
ReclaimStagedBytes();
}
MGLOG_F("MGPipe: Fatal{RingOverrun, \"SEG_STAGE\"} a %llu byte blob does not fit a %llu "
SessionFail(MGFatalFamily::RingOverrun, "MGPipe: Fatal{RingOverrun, \"SEG_STAGE\"} a %llu byte blob does not fit a %llu "
"byte staging segment with %llu bytes still in flight (retiredSeq=%llu); a "
"blob is staged whole and only the rows that cut at the stage chunk budget "
"stay small - raise MOBILEGL_IPC_STAGE_MB or report that row to the integrator",
@@ -923,8 +936,7 @@ namespace MobileGL::MG_Remote::Wire {
static_cast<unsigned long long>(m_stageCapacity),
static_cast<unsigned long long>(m_stageHead - m_stageTail),
static_cast<unsigned long long>(
m_control != nullptr ? m_control->retiredSeq.load(std::memory_order_acquire) : 0));
std::abort();
m_control != nullptr ? m_control->Progress.retiredSeq.load(std::memory_order_acquire) : 0));
}
MGPBlobRef PipeWireEncoder::StageBytes(const void* bytes, Uint64 size) {
@@ -1020,14 +1032,13 @@ namespace MobileGL::MG_Remote::Wire {
if (total > m_cmd->MaxRecordBytes()) {
// R-10's record bound. The content rows cut their BLOBS at the stage chunk budget
// (MGPipeStageChunkBytes); a record's own bytes have no such budget and die here.
MGLOG_F("MGPipe: Fatal{RingOverrun, \"%s\"} a %llu byte record exceeds "
SessionFail(MGFatalFamily::RingOverrun, "MGPipe: Fatal{RingOverrun, \"%s\"} a %llu byte record exceeds "
"RingProducer::MaxRecordBytes() == %llu (half of a %llu byte SEG_CMD); the stage chunk "
"budget cuts blobs, not a record's own bytes - report the row to the "
"integrator",
WireOpName(op), static_cast<unsigned long long>(total),
static_cast<unsigned long long>(m_cmd->MaxRecordBytes()),
static_cast<unsigned long long>(m_cmd->Capacity()));
std::abort();
}
// MGPipeCallFlags -> RingRecordFlags. See the file header: these are two flag spaces
@@ -1131,13 +1142,12 @@ namespace MobileGL::MG_Remote::Wire {
// here and a Fatal on a peer - exactly the asymmetry EncodeRecord's own
// comment says it exists to prevent.
if (op == MGPWireOp::CreateShaderState && i < 6 && blob.Size != 0) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"CreateShaderState.Spirv[%u]\"} "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"CreateShaderState.Spirv[%u]\"} "
"declares %llu bytes at the ENCODER; under split the modules travel "
"inside the Reflection archive and the six per-stage runs stay "
"undeclared",
static_cast<unsigned>(i),
static_cast<unsigned long long>(blob.Size));
std::abort();
}
}
}
@@ -1164,6 +1174,20 @@ namespace MobileGL::MG_Remote::Wire {
// the measured answer on the reduced path is a different row entirely.
m_maxRecordOp = op;
}
// P6 GATE 8's SECOND NUMBER (CONTRACT-P6.md §9 item 8), and it is counted HERE rather than
// at any emitter for the reason the CallClass comment gives: after chunking, the emitter
// no longer knows how many records its one call produced. By this point the record is
// COMMITTED - Reserve succeeded, the body is written and the blob slots have been checked
// honest - so this is exactly "records/frame post-chunking", not "emitter calls/frame".
//
// A kRecPad FILLER CANNOT REACH HERE: Reserve returns the filler's wake-up as a refusal
// (kInvalidSeq) and the caller retries, so no pad is ever counted, which is what keeps
// this number comparable with the seq space R-3 defines. A REFUSED emission is not counted
// either - the early return above is what makes one record cost exactly one.
if (MG_Util::PipeStats::Enabled()) {
MG_Util::PipeStats::AddCalls(MG_Util::PipeStats::CallClass::WireRecords, 1);
}
++m_emitSeq;
// The stage mark: where SEG_STAGE stood once everything this record names had been
// staged. ReclaimStagedBytes releases up to the newest mark the server has retired.
@@ -1201,7 +1225,7 @@ namespace MobileGL::MG_Remote::Wire {
if (m_control == nullptr) {
return;
}
const Uint64 retired = m_control->retiredSeq.load(std::memory_order_acquire);
const Uint64 retired = m_control->Progress.retiredSeq.load(std::memory_order_acquire);
Uint64 upTo = m_stageTail;
while (m_stageMarkFront < m_stageMarks.size() &&
m_stageMarks[m_stageMarkFront].Seq <= retired) {
@@ -1347,11 +1371,10 @@ namespace MobileGL::MG_Remote::Wire {
// then fails for ever: the barrier HANGS rather than returning something wrong, which
// is the harder failure to diagnose of the two.
if ((MGPipeCallFlagsFor(op) & static_cast<Uint32>(kReplySlot)) == 0) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s\"} the decoder tried to answer into "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s\"} the decoder tried to answer into "
"a reply slot for a call the catalogue gives no kReplySlot; s1 sizes "
"ReplyPool from MGPipeCallFlagsFor and reserved none",
WireOpName(op));
std::abort();
}
if (m_replies != nullptr) {
m_replies->PostReply(seq, status, bytes, size);
@@ -1376,23 +1399,21 @@ namespace MobileGL::MG_Remote::Wire {
// the audit has stopped covering the carrier, which is the same failure as no audit at
// all - the reason the run-count overflow just below is a Fatal too.
if (blob.Size == 0 || blob.Seg != kSegStage) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s\"} the audit was asked to record a "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s\"} the audit was asked to record a "
"resolved run with seg=%u size=%llu; only declared SEG_STAGE(%u) runs "
"reach the poison fill (R-2.5)",
WireOpName(op), static_cast<unsigned>(blob.Seg),
static_cast<unsigned long long>(blob.Size),
static_cast<unsigned>(kSegStage));
std::abort();
}
if (m_resolvedCount >= sizeof(m_resolved) / sizeof(m_resolved[0])) {
// LOUD, NOT A SILENT DROP. This array is what the 0xDD fill covers, and a poison
// that quietly stopped covering a run is the same failure as no poison at all -
// rule C's only mechanical control going dark without a line in the log.
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s\"} more than %llu SEG_STAGE runs in "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s\"} more than %llu SEG_STAGE runs in "
"one record; the audit fill would stop covering them",
WireOpName(op),
static_cast<unsigned long long>(sizeof(m_resolved) / sizeof(m_resolved[0])));
std::abort();
}
m_resolved[m_resolvedCount++] = blob;
}
@@ -1508,7 +1529,7 @@ namespace MobileGL::MG_Remote::Wire {
// record type)`; it CANNOT SEE THE TAIL, so this is the first thing that holds a
// record declaring Count = 4000 while carrying 8 bytes to its own arithmetic.
if (size != layout.TotalBytes) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"%s\"} the record declares Size=%llu and "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"%s\"} the record declares Size=%llu and "
"its own count fields describe %llu bytes (fixed payload %llu + tails "
"%llu/%llu/%llu)",
WireOpName(op), static_cast<unsigned long long>(size),
@@ -1517,7 +1538,6 @@ namespace MobileGL::MG_Remote::Wire {
static_cast<unsigned long long>(layout.TailBytes[0]),
static_cast<unsigned long long>(layout.TailBytes[1]),
static_cast<unsigned long long>(layout.TailBytes[2]));
std::abort();
}
// The record's own ordinal, which is its reply-slot id (R-3). 1-based, and m_applySeq
@@ -1791,12 +1811,11 @@ namespace MobileGL::MG_Remote::Wire {
for (Uint32 i = 0; i < 6; ++i) {
CheckBlobIsHonest(op, desc.Spirv[i], *m_segments);
if (desc.Spirv[i].Size != 0) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"CreateShaderState.Spirv[%u]\"} "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"CreateShaderState.Spirv[%u]\"} "
"declares %llu bytes; under split the modules travel inside the "
"Reflection archive and the six per-stage runs stay undeclared",
static_cast<unsigned>(i),
static_cast<unsigned long long>(desc.Spirv[i].Size));
std::abort();
}
}
const void* archiveBytes = ResolveOrFatal(op, desc.Reflection);
@@ -2067,11 +2086,10 @@ namespace MobileGL::MG_Remote::Wire {
const Bool boxIsWhole =
rec.UnionBox.W != 0 && rec.UnionBox.H != 0 && rec.UnionBox.D != 0;
if (!namesABuffer && !boxIsEmpty && !boxIsWhole) {
MGLOG_F("MGPipe: Fatal{ProtocolCorruption, \"ResourceSubData\"} the union box "
SessionFail(MGFatalFamily::ProtocolCorruption, "MGPipe: Fatal{ProtocolCorruption, \"ResourceSubData\"} the union box "
"%ux%ux%u has a zero extent on some axes and not others; a box is "
"either empty or whole",
rec.UnionBox.W, rec.UnionBox.H, rec.UnionBox.D);
std::abort();
}
const Bool carriesContent = namesABuffer ? MGPipeSubDataBufferSize(rec) != 0
: (boxIsWhole || rec.RegionCount != 0);
@@ -30,6 +30,7 @@
// pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <fstream>
@@ -776,6 +777,13 @@ int main(int argc, char** argv) {
#else
setenv("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str(), 1);
#endif
// P6: MOBILEGL_LOG_FILE_PATH is a BASE NAME and the library writes one file per role. These
// cases read the log by OFFSET (a single growing file), and every marker they assert is
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
#if MOBILEGL_PIPE_PUSH
MobileGL::Initialize();
#endif
+39 -8
View File
@@ -27,6 +27,7 @@
// logs.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <cctype>
#include <cstdio>
@@ -65,10 +66,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
long ProcessId() {
@@ -808,7 +809,7 @@ TEST_F(FieldOwnershipTest, SplitCaptureSnapshotSurvivesMakeCurrentUntilObjectRel
}
TEST_F(FieldOwnershipTest, RoleSplitOffFoldsTheFillSideOntoTheSharedBlock) {
EXPECT_FALSE(MGPipeRoleSplitActive());
EXPECT_FALSE(MGPipeRoleSplitRehearsalActive());
EXPECT_EQ(&MGPipeClientInputs(), &gPipeInputs);
}
@@ -819,14 +820,44 @@ TEST_F(FieldOwnershipTest, RoleSplitUnderMonolithTransportIsStillOneBlock) {
RoleSplitArm guard;
MG_Config::Ipc.RoleSplitState = true;
MG_Config::Transport = MG_Config::TransportMode::Monolith;
EXPECT_FALSE(MGPipeRoleSplitActive());
EXPECT_FALSE(MGPipeRoleSplitRehearsalActive());
EXPECT_EQ(&MGPipeClientInputs(), &gPipeInputs);
}
// D1c/D10 (CONTRACT-P6 3.2, 3.4). THE PREDICATE THAT IS TRUE WITHOUT THE KNOB, and the reason
// four guards were compiled in and permanently disarmed in a spawn server.
//
// MGPipeRoleSplitRehearsalActive() answers "is the REHEARSAL armed", which needs
// MOBILEGL_IPC_ROLE_SPLIT_STATE. Under spawn the two roles are in DIFFERENT ADDRESS SPACES, so
// their PipeInputs blocks are distinct whatever that knob says - and every guard that asked the
// rehearsal question was therefore off in the one shape where it matters most. Measured on the
// real lane: the spawn retrace runs with role-split-state=0.
TEST_F(FieldOwnershipTest, SpawnMakesTheBlocksDistinctWithNoRehearsalKnobAtAll) {
RoleSplitArm guard;
MG_Config::Ipc.RoleSplitState = false;
MG_Config::Transport = MG_Config::TransportMode::Spawn;
EXPECT_FALSE(MGPipeRoleSplitRehearsalActive())
<< "the rehearsal must stay OFF; this case is about the shape, not the knob";
EXPECT_TRUE(MGPipeBlocksAreDistinct())
<< "a spawn server shares no storage object with its client, so any guard that asked "
"only the rehearsal question is disarmed exactly where it is needed";
}
// The other direction, so the predicate cannot be a constant: monolith shares one block, and
// neither the knob nor the transport alone makes it two.
TEST_F(FieldOwnershipTest, MonolithKeepsOneBlockAndTheWiderPredicateSaysSo) {
RoleSplitArm guard;
MG_Config::Ipc.RoleSplitState = false;
MG_Config::Transport = MG_Config::TransportMode::Monolith;
EXPECT_FALSE(MGPipeBlocksAreDistinct());
EXPECT_EQ(&MGPipeClientInputs(), &gPipeInputs);
}
TEST_F(FieldOwnershipTest, RoleSplitGivesTheFillSideADistinctBlockTheStampNeverTouches) {
RoleSplitArm guard;
guard.Arm(true);
ASSERT_TRUE(MGPipeRoleSplitActive());
ASSERT_TRUE(MGPipeRoleSplitRehearsalActive());
ASSERT_NE(&MGPipeClientInputs(), &gPipeInputs);
const Uint64 serverSerialBefore = gPipeInputs.FilledState().CurrentVerbSerial;
@@ -1052,7 +1083,7 @@ TEST_F(FieldOwnershipTest, DualBlockDoesNotArmUnderMonolithTransport) {
// A real monolith fill, not a manufactured server stamp on a monolith process.
MGPipeValidateForVerb(MGPipeVerb::DrawArrays);
(void)gPipeInputs.GetBoundVertexArray();
if (MGPipeRoleSplitActive() || MGPipeResidualPullCount() != 0) ::_exit(7);
if (MGPipeRoleSplitRehearsalActive() || MGPipeResidualPullCount() != 0) ::_exit(7);
});
ASSERT_TRUE(ExitedWith(r, 0)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_EQ(r.Log.find("Fatal{"), std::string::npos) << r.Log;
@@ -37,6 +37,7 @@
// stays name-for-name identical between the pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <fstream>
@@ -92,10 +93,10 @@ namespace {
#if MOBILEGL_PIPE_PUSH
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
// A fresh applier per case, BOTH SCOPES, and it takes both because there are two: a reset
+8
View File
@@ -24,6 +24,7 @@
// pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <fstream>
@@ -698,6 +699,13 @@ int main(int argc, char** argv) {
#else
setenv("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str(), 1);
#endif
// P6: MOBILEGL_LOG_FILE_PATH is a BASE NAME and the library writes one file per role. These
// cases read the log by OFFSET (a single growing file), and every marker they assert is
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
#if MOBILEGL_PIPE_PUSH
MobileGL::Initialize();
#endif
+5 -4
View File
@@ -18,6 +18,7 @@
// line land in this process's read. A forked child inherits its parent's path on purpose.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <cstdio>
#include <cstdlib>
@@ -53,10 +54,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
long ProcessId() {
@@ -29,6 +29,7 @@
// pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <fstream>
@@ -1017,6 +1018,13 @@ int main(int argc, char** argv) {
#else
setenv("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str(), 1);
#endif
// P6: MOBILEGL_LOG_FILE_PATH is a BASE NAME and the library writes one file per role. These
// cases read the log by OFFSET (a single growing file), and every marker they assert is
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
#if MOBILEGL_PIPE_PUSH
MobileGL::Initialize();
#endif
@@ -36,6 +36,7 @@
// rather than a vanishing test - and the four names are the SAME four in every build, which
// is what keeps `ctest -N` name-for-name identical between the pull and the push tree.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <cstdio>
#include <cstring>
@@ -79,10 +80,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
long ProcessId() {
+5 -4
View File
@@ -34,6 +34,7 @@
// between the pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <cstring>
#include <filesystem>
@@ -95,10 +96,10 @@ namespace {
}
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
// The op table is INSTALLED BY A BACKEND, at its own bring-up, and uninstalled at its
@@ -33,6 +33,7 @@
// pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <fstream>
@@ -1150,6 +1151,13 @@ int main(int argc, char** argv) {
#else
setenv("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str(), 1);
#endif
// P6: MOBILEGL_LOG_FILE_PATH is a BASE NAME and the library writes one file per role. These
// cases read the log by OFFSET (a single growing file), and every marker they assert is
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
#if MOBILEGL_PIPE_PUSH
// ONE process-wide context for the whole suite, because half these cases need a really
// linked program and glslang lives behind this call. Each case uses GL names of its own.
@@ -29,6 +29,7 @@
// `ctest -N` stays name-for-name identical between the pull and the push trees (G2/G14).
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <fstream>
@@ -498,6 +499,13 @@ int main(int argc, char** argv) {
#else
setenv("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str(), 1);
#endif
// P6: MOBILEGL_LOG_FILE_PATH is a BASE NAME and the library writes one file per role. These
// cases read the log by OFFSET (a single growing file), and every marker they assert is
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
#if MOBILEGL_PIPE_PUSH
MobileGL::Initialize();
#endif
+5 -4
View File
@@ -37,6 +37,7 @@
// stays name-for-name identical between the pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <fstream>
@@ -99,10 +100,10 @@ namespace {
#if MOBILEGL_PIPE_PUSH
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
// A fresh applier per case, BOTH SCOPES, and it takes both because there are two: a reset
@@ -33,6 +33,7 @@
// stays name-for-name identical between the pull and the push trees.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <filesystem>
#include <string>
+22 -1
View File
@@ -2113,7 +2113,16 @@ TEST(LogSanity, UsesEnvOverrideForFilePath) {
UnsetEnvVar("MOBILEGL_LOG_FILE_PATH");
{
std::ifstream logFile(logPath);
// P6: the sink writes ONE FILE PER ROLE, so the base name is not itself a file. This
// process logs on the main thread - the client role - so the line landed in the
// client-derived path. In a pull build there is no split and the base IS the file.
#if MOBILEGL_BUILD_DISAGGREGATED
const fs::path readPath = MobileGL::MG_Util::Debug::RoleLogPath(
logPath.string().c_str(), MobileGL::MG_Util::Debug::LogRole::Client);
#else
const fs::path readPath = logPath;
#endif
std::ifstream logFile(readPath);
ASSERT_TRUE(logFile.good());
const std::string contents((std::istreambuf_iterator<char>(logFile)), std::istreambuf_iterator<char>());
@@ -2121,6 +2130,10 @@ TEST(LogSanity, UsesEnvOverrideForFilePath) {
}
fs::remove(logPath);
#if MOBILEGL_BUILD_DISAGGREGATED
fs::remove(MobileGL::MG_Util::Debug::RoleLogPath(
logPath.string().c_str(), MobileGL::MG_Util::Debug::LogRole::Client));
#endif
}
// ---- Pure-state entry points: glHint / glPointParameter* / glPixelStoref / glGetDoublev -----------
@@ -3549,11 +3562,19 @@ namespace {
ScopedLogFileRedirect& operator=(const ScopedLogFileRedirect&) = delete;
// Everything written so far. Closes the log first so the last line is on disk.
//
// P6: BOTH ROLES, because "everything written" now spans two files - the sink writes one
// per role - and a caller of a general "give me the log" helper cannot know which role
// wrote the line it wants. In a pull build there is no split and m_path is the file.
std::string Contents() const {
MobileGL::MG_Util::Debug::Close();
#if MOBILEGL_BUILD_DISAGGREGATED
return MobileGL::MG_Util::Debug::ReadRoleLogs(m_path.string().c_str());
#else
std::ifstream logFile(m_path);
if (!logFile.good()) return {};
return std::string(std::istreambuf_iterator<char>(logFile), std::istreambuf_iterator<char>());
#endif
}
private:
+7
View File
@@ -198,6 +198,13 @@ int main(int argc, char** argv) {
#else
setenv("MOBILEGL_LOG_FILE_PATH", g_logPath.c_str(), 1);
#endif
// P6: the sink writes one file per role and the env is a BASE NAME. This suite emits on the
// main thread (client role), so the read path is the client-derived one; a pull build has
// no split and keeps the base. The env keeps the base either way.
#if MOBILEGL_BUILD_DISAGGREGATED
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
#endif
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
+232
View File
@@ -13,6 +13,7 @@
#include <gtest/gtest.h>
#include <Config.h>
#include <MG_Util/Debug/Log.h>
#include <MG_Util/Metrics/PipeStats.h>
#include <cstdio>
@@ -93,6 +94,116 @@ namespace {
PS::Init();
}
// THE LATCH IS THE WHOLE CONTRACT, and this case exists because a spawn server got
// it wrong in a way no other test could see. `Init()` is a step of
// MobileGL::Initialize(), and the spawn server process never calls that - it calls
// MG_ConfigLoader::Init + InitServerRoleForSpawn - so `g_pipeStatsEnabled` stayed
// false there and every `if (Enabled())` site in the process was permanently
// false. The observable consequence was not a wrong number but an ABSENT one:
// the server printed no summary line at all, and `wait[srv=0 srvpark=0]` (what a
// reader would have taken for "the server never waited") is in fact what this
// case's "false" arm looks like.
//
// It pins both directions, because only the pair is falsifiable: Init() must TAKE
// the config's value when it is true, and must CLEAR the latch when it is false -
// a version that only ever set the flag true would pass a one-sided test while
// making MOBILEGL_PIPE_STATS=0 mean nothing in a long-lived process.
TEST_F(PipeStatsTest, InitIsTheOnlyLatchAndItTakesTheConfigBothWays) {
const bool saved = MobileGL::MG_Config::Features.PipeStats;
MobileGL::MG_Config::Features.PipeStats = true;
PS::Init();
EXPECT_TRUE(PS::Enabled()) << "a true config must arm the counters";
MobileGL::MG_Config::Features.PipeStats = false;
PS::Init();
EXPECT_FALSE(PS::Enabled()) << "and a false one must disarm them, not leave the old latch";
MobileGL::MG_Config::Features.PipeStats = saved;
PS::Init();
}
// A summary line is emitted by whichever role reaches OnPresent, and this is what makes
// the spawn server's line appear at all: it has no swap of its own, so its cadence
// rides the present records it applies. The assertion is the arithmetic that cadence
// rests on - k presentations produce k windows when the period is 1 - because that is
// the property the lane's per-frame rates divide by.
TEST_F(PipeStatsTest, PresentationsAtTheDefaultPeriodOfOneMakeOneWindowEach) {
const Uint32 saved = MobileGL::MG_Config::Features.PipeStatsPeriod;
MobileGL::MG_Config::Features.PipeStatsPeriod = 1;
PS::Init();
for (Uint32 i = 0; i < 5; ++i) {
PS::PublishGauge(PS::Gauge::ServerWaits, static_cast<Uint64>(100 * (i + 1)));
PS::OnPresent();
}
EXPECT_EQ(PS::FrameCount(), 5u);
// The gauge is a RUN TOTAL: publishing five increasing values leaves the last one,
// never their sum. This is the mistake the report's first aggregation script made.
EXPECT_EQ(PS::GaugeValue(PS::Gauge::ServerWaits), 500u);
MobileGL::MG_Config::Features.PipeStatsPeriod = saved;
PS::Init();
}
// P6 gate 8: THE DUMP PATH IS ROLE-DERIVED AND THE BASE NAME IS NOT A FILE.
//
// The trap this exists for: under `spawn` both roles reach PipeStats::Shutdown() (the client
// through MobileGL::Destroy, the server through ServerMain's own call), and before this both
// opened MOBILEGL_PIPE_STATS_FILE itself with trunc - so the second writer silently replaced
// the first, and a reader held one role's numbers under a name that claimed to be the run's.
//
// ---- WHAT THIS CASE ASSERTS, AND WHAT ITS FIRST VERSION GOT WRONG ----
//
// The first version asserted about MG_Util::Debug::RoleLogPath directly: that the two roles get
// different paths, that neither equals the base name. All of that PASSED WITH THE FIX REVERTED -
// it tested the naming helper, which was never broken. What was broken was that the dump did
// not CALL it. A test that stays green while the defect is present is worse than no test.
//
// So the subject here is RoleDerivedJsonDumpPathForTesting(), the same expression the dump and
// the banner use; and the third assertion is the negative control the design rests on - the
// base name must not exist as a file, so a reader that was not updated gets ENOENT and says so
// rather than a file that looks like a complete run and is half of one.
TEST_F(PipeStatsTest, JsonDumpPathIsRoleDerivedAndTheBaseNameIsNeverOpened) {
#if !MOBILEGL_BUILD_DISAGGREGATED
// RoleDerivedJsonDumpPathForTesting is compiled only with two roles (gate G1: a monolith
// build has one and needs no derivation). The NAME stays registered in every build so
// ctest -N matches between flavours; the body only exists where the collision does.
GTEST_SKIP() << "role-derived dump paths only exist with two roles (MOBILEGL_BUILD_DISAGGREGATED=OFF)";
#else
using MobileGL::MG_Util::Debug::LogRole;
const String saved = MobileGL::MG_Config::Features.PipeStatsFile;
const char* base = "/tmp/mobilegl-pipestats-role-test.json";
// Unset: no path at all, and specifically not the empty string spelled as a file name.
MobileGL::MG_Config::Features.PipeStatsFile = "";
EXPECT_TRUE(PS::RoleDerivedJsonDumpPathForTesting().empty());
MobileGL::MG_Config::Features.PipeStatsFile = base;
const String path = PS::RoleDerivedJsonDumpPathForTesting();
// (1) THE DUMP PATH IS THE DERIVED ONE, spelled out, so a change to the rule is a change
// to this test. A unit process is the client role.
EXPECT_EQ(path, String("/tmp/mobilegl-pipestats-role-test.client.json"));
// (2) THE BASE NAME IS NOT THE PATH. This is the collision itself: if the dump wrote the
// configured name, spawn's second writer would truncate the first.
EXPECT_NE(path, String(base));
// (3) THE NEGATIVE CONTROL. PipeStats writes the derived path, never the base, so nothing
// may have created the base. A fresh base is absent, and this fails if that ever stops
// being true - which is exactly what a revert of the derivation does.
std::remove(base);
std::ifstream baseFile(base);
EXPECT_FALSE(baseFile.good())
<< "the configured base name exists; something opened it directly, and under spawn "
"that is the trunc-versus-trunc collision this derivation exists to prevent";
MobileGL::MG_Config::Features.PipeStatsFile = saved;
#endif
}
TEST_F(PipeStatsTest, GateHitsAndMissesAreSeparateCounters) {
for (Uint32 i = 0; i < 5; ++i) {
PS::CountGate(PS::Gate::MagmaPipelineMemo, /*hit=*/true);
@@ -171,6 +282,15 @@ namespace {
// And the new ByteClass rides the ordinary bytes[] bracket under a short name that is
// NOT "csob": the cso[] bracket above already prints csob= for the CSO bind count.
EXPECT_NE(line.find("csob-blob="), String::npos) << line;
// P6 GATE 8'S TWO NUMBERS (CONTRACT-P6.md §9 item 8), pinned where an operator's grep
// would break. `seg` is the ByteClass that says how many bytes a frame stages into
// SEG_STAGE, and `wrec` / `wrec/f` are the post-chunking record count and its per-frame
// figure. The short name is `seg` and not `stage`, which would read as a prefix of
// `stage-buffer`'s long name and of nothing else in the bracket; it is also not `ssb`,
// because this is a per-frame BYTES field and `ssb` reads like a count.
EXPECT_NE(line.find("seg="), String::npos) << line;
EXPECT_NE(line.find("wrec="), String::npos) << line;
EXPECT_NE(line.find("wrec/f="), String::npos) << line;
// P5d round 3's wait ledger. Four fields on a bracket of their own, and they are
// pinned here for the reason every other short name is: they are what the inproc
// performance work reads out of a run's log, so a rename or a dropped field breaks
@@ -197,6 +317,114 @@ namespace {
EXPECT_NE(line.find("buf=97.14"), String::npos) << line;
}
#if MOBILEGL_PIPE_PUSH
// P6 GATE 8's TWO NUMBERS (CONTRACT-P6.md §9 item 8), and each half is pinned because each
// half is a way the deliverable can be wrong without looking wrong.
//
// `seg` IS THE PRODUCER'S OWN BYTES. The wire encoder adds `size` and not the allocator's
// Align8 of it (PipeWireCodec.cpp's StageAllocate), so a blob of 4096 stages 4096. Checked
// here on the module's own arithmetic because that is the only place the rule can be read
// without a live ring: the encoder's call site is deliberately one line and has no test of
// its own.
TEST_F(PipeStatsTest, StageSegmentBytesIsAWindowedByteClassLikeAnyOther) {
PS::AddBytes(PS::ByteClass::StageSegmentBytes, 4096);
PS::AddBytes(PS::ByteClass::StageSegmentBytes, 2048);
PS::AddCalls(PS::CallClass::Draws, 1);
PS::OnPresent();
EXPECT_EQ(PS::TotalBytes(PS::ByteClass::StageSegmentBytes), 6144u);
EXPECT_EQ(PS::FrameBytes(PS::ByteClass::StageSegmentBytes), 0u) << "a Present clears the frame";
// 6144 over one frame, two decimals, in the ordinary bytes[] bracket.
EXPECT_NE(PS::FormatWindowLine().find("seg=6144.00"), String::npos)
<< PS::FormatWindowLine();
PS::AdvanceSummaryWindow();
// And it obeys the file's LABEL rule, not a rule of its own: the new window has no
// Present in it, so the bracket is relabelled "bytes[" and `seg` carries the window
// TOTAL verbatim rather than a figure divided by a faked frame count. That is the same
// rule the bytes[] bracket follows and the same one the two window-total tests below
// pin; asserting "seg=0.00" here is what the first cut of this case did, and it was
// asserting a per-frame form the line deliberately does not print.
const String empty = PS::FormatWindowLine();
EXPECT_NE(empty.find("bytes["), String::npos) << empty;
EXPECT_EQ(empty.find("bytes/f["), String::npos) << empty;
EXPECT_NE(empty.find("seg=0"), String::npos) << empty;
}
// `wrec` IS A COUNT, SO IT DOES NOT DIVIDE LIKE A BYTE CLASS - and the per-frame form must
// read off the line, which is why the field exists at all rather than the operator doing the
// division by hand. 26 records over 13 frames is 2.00; the window total is printed beside it
// so the pair is self-checking.
TEST_F(PipeStatsTest, WireRecordsCarryBothTheWindowCountAndItsPerFrameForm) {
PS::AddCalls(PS::CallClass::WireRecords, 26);
for (Uint32 i = 0; i < 13; ++i) {
PS::OnPresent();
}
const String line = PS::FormatWindowLine();
EXPECT_NE(line.find("wrec=26"), String::npos) << line;
EXPECT_NE(line.find("wrec/f=2.00"), String::npos) << line;
}
// AND THE LABEL RULE THE FILE ALREADY OWNS APPLIES TO IT: a window with no Present in it has
// no per-frame reading, so `wrec/f` carries the window total rather than a figure divided by
// a faked 1. This is the same 47x overstatement PipeStatsTest pins for the bytes[] bracket,
// one field over, and it is the shape a trace slice with no swap at all would hit.
TEST_F(PipeStatsTest, WireRecordsFallBackToTheWindowTotalWithoutAFrame) {
PS::AddCalls(PS::CallClass::WireRecords, 47);
const String line = PS::FormatWindowLine();
EXPECT_EQ(PS::FrameCount(), 0u);
EXPECT_NE(line.find("wrec=47"), String::npos) << line;
EXPECT_NE(line.find("wrec/f=47"), String::npos) << line;
EXPECT_EQ(line.find("wrec/f=47.00"), String::npos) << line;
}
// THE STAGED-BLOB DISTRIBUTION, which is the optional deliverable MEASUREMENTS.md:342 says
// has never existed. It shares the draw-payload histogram's edges - bucket 0 is "0 bytes",
// bucket n>0 is [2^(n-1), 2^n) - so the two are read the same way, and it is a COUNT per
// bucket rather than a byte sum: the shape is the deliverable and the bytes have their own
// counter in `seg`.
TEST_F(PipeStatsTest, StagedBlobHistogramSharesThePayloadBucketEdges) {
PS::RecordStagedBlobBytes(1); // [1, 2) -> bucket 1
PS::RecordStagedBlobBytes(4096); // [4096,8192)-> bucket 13
PS::RecordStagedBlobBytes(4096); // same bucket
PS::RecordStagedBlobBytes(8192); // [8192,...) -> bucket 14: the edge is exclusive
EXPECT_EQ(PS::TotalStagedBlobBucket(1), 1u);
EXPECT_EQ(PS::TotalStagedBlobBucket(13), 2u);
EXPECT_EQ(PS::TotalStagedBlobBucket(14), 1u);
EXPECT_EQ(PS::TotalStagedBlobBucket(0), 0u);
// Saturation and the out-of-range read, exactly as the draw-payload histogram's.
PS::RecordStagedBlobBytes(~Uint64{0});
EXPECT_EQ(PS::TotalStagedBlobBucket(PS::kStagedBlobHistogramBuckets - 1), 1u);
EXPECT_EQ(PS::TotalStagedBlobBucket(PS::kStagedBlobHistogramBuckets), 0u);
}
// A distribution is a RUN TOTAL and has no business being windowed: it is a shape over the
// whole workload, and a Present that cleared it would report the shape of one frame as if it
// were the run's. It reaches an operator through the JSON dump - the same channel and for the
// same reason the draw-payload histogram uses it - so that is where it is asserted.
TEST_F(PipeStatsTest, StagedBlobHistogramIsARunTotalAndReachesTheJsonDump) {
PS::RecordStagedBlobBytes(1024);
PS::OnPresent();
const String json = PS::FormatJson();
EXPECT_NE(json.find("\"staged-blob-bytes-histogram\""), String::npos) << json;
EXPECT_NE(json.find("\"wire-records\""), String::npos) << json;
EXPECT_NE(json.find("\"stage-segment-bytes\""), String::npos) << json;
// Run total, not a window: the sample above survives the Present.
EXPECT_EQ(PS::TotalStagedBlobBucket(11), 1u);
// The ordering is the JSON document's shape, not decoration: the new array is a SIBLING
// of the draw-payload one, so a reader that walks the object finds both where the two
// comments say they are.
EXPECT_LT(json.find("\"cmd-bytes-per-draw-histogram\""),
json.find("\"staged-blob-bytes-histogram\""))
<< json;
}
#endif
// Successive summaries report WINDOWS, not run totals: a run total over a workload that
// changes shape (load, then steady state) averages away the very number section 2.3.1
// wants. Advancing the window is an explicit call, not a side effect of formatting.
@@ -312,6 +540,10 @@ namespace {
EXPECT_STREQ(PS::NameOf(PS::CallClass::ClientTextureUploadEmissions),
"client-tex-upload-emissions");
EXPECT_STREQ(PS::NameOf(PS::ByteClass::CsoBlobBytes), "cso-blob-bytes");
// P6 gate 8's two, under their long names - the JSON dump keys and the names the
// MEASUREMENTS.md entry will quote.
EXPECT_STREQ(PS::NameOf(PS::ByteClass::StageSegmentBytes), "stage-segment-bytes");
EXPECT_STREQ(PS::NameOf(PS::CallClass::WireRecords), "wire-records");
#endif
EXPECT_STREQ(PS::NameOf(PS::Gate::EsprytRenderState), "espryt-render-state");
EXPECT_STREQ(PS::NameOf(PS::Gate::EsprytTextureSyncList), "espryt-texture-sync-list");
+28 -1
View File
@@ -12,15 +12,29 @@ set(MOBILEGL_WIRE_TESTS
# P5 s1: the ring-owning session pair - four ShmSegment-backed segments, the five
# watermarks with real writers, the reply slot pool and the event ring.
SessionTest
# P6 dl: the Fatal-family table and its total projection onto the wire FatalCode.
FatalFamilyTest
)
if (NOT WIN32)
# SCM_RIGHTS and fork(): POSIX only.
list(APPEND MOBILEGL_WIRE_TESTS FdPassingTest)
# P6 so: the SAME nine ITransport-contract cases InProcessTransportTest runs, over a real
# socketpair with real threads, plus the three a stream has and a message queue does not.
# POSIX for the same reason as FdPassingTest - and because CONTRACT-P6 §2.6 lands POSIX only.
list(APPEND MOBILEGL_WIRE_TESTS SocketTransportTest)
# P6 sm: two MobileGL processes. Needs the real server image beside it, so
# the dependency is declared after the loop rather than assumed.
list(APPEND MOBILEGL_WIRE_TESTS ServerSpawnTest)
endif()
include(GoogleTest)
# ServerSpawnTest execs a real second process, so the image has to exist before
# the test runs and the test has to be told where it landed. Both stated here
# rather than left to a working-directory coincidence.
set(MOBILEGL_SERVER_IMAGE_PATH "${CMAKE_BINARY_DIR}/libMobileGLServer.so")
foreach (test IN LISTS MOBILEGL_WIRE_TESTS)
add_executable(${test} ${test}.cpp)
@@ -35,7 +49,20 @@ foreach (test IN LISTS MOBILEGL_WIRE_TESTS)
${LINK_LIBRARIES}
)
gtest_discover_tests(${test} DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
if (test STREQUAL "ServerSpawnTest")
# It execs the real image, so it must be built first and must be told
# where it is. MOBILEGL_TEST_SERVER_PATH is read by the test's
# ServerImage() helper; without it the test would depend on the working
# directory, which ctest does not promise.
if (TARGET MobileGLServer)
add_dependencies(${test} MobileGLServer)
endif()
gtest_discover_tests(${test} DISCOVERY_TIMEOUT 30
PROPERTIES LABELS unit
ENVIRONMENT "MOBILEGL_TEST_SERVER_PATH=${MOBILEGL_SERVER_IMAGE_PATH}")
else ()
gtest_discover_tests(${test} DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit)
endif ()
endforeach ()
# P5 w1's G3 codec suite. It is registered on its own rather than in the list above because it
+110
View File
@@ -0,0 +1,110 @@
// MobileGL - MobileGL/MG_Test/Wire/FatalFamilyTest.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// P6 `dl` (CONTRACT-P6 5.2). The Fatal-family table and its projection onto the wire FatalCode.
#include <MG_Remote/FatalFamily.h>
#include <MG_Remote/Protocol/generated/protocol_generated.h>
#include <flatbuffers/flatbuffers.h>
#include <gtest/gtest.h>
#include <set>
#include <string>
using namespace MobileGL::MG_Remote;
using MobileGL::Wire::FatalCode;
namespace {
// Every family, walked once, so a new row is covered without editing this list.
const MGFatalFamily kAllFamilies[] = {
#define X(Family, WireCode, Why) MGFatalFamily::Family,
MGL_FATAL_FAMILY_LIST(X)
#undef X
};
} // namespace
TEST(FatalFamily, TheTableAndTheEnumAgreeOnCount) {
EXPECT_EQ(sizeof(kAllFamilies) / sizeof(kAllFamilies[0]), MGFatalFamilyCount());
// a6 censused thirty; the vocabulary has grown since, on purpose. The point of this line is
// that the number is stated, not that it is any particular value - a change to it is a
// deliberate edit here, which is exactly the "grows on purpose" the census gate also asks.
EXPECT_GE(MGFatalFamilyCount(), 30u);
}
TEST(FatalFamily, EveryFamilyProjectsToADefinedWireCode) {
// A total table: every family maps, and never to None (which is "no fatal"). None as a
// projection would say a death was not a death.
for (const MGFatalFamily family : kAllFamilies) {
const FatalCode code = FatalCodeForFamily(family);
EXPECT_NE(code, FatalCode::None)
<< FatalFamilyName(family) << " projects onto FatalCode::None";
}
}
TEST(FatalFamily, NoFamilyProjectsOntoDeviceLost) {
// 5.3: DeviceLost is armed from the doorbell's hangup, never raised as a Fatal. A family that
// projected onto it would let an abort masquerade as a device loss, which is the exact
// confusion the latch/abort split exists to prevent.
for (const MGFatalFamily family : kAllFamilies) {
EXPECT_NE(FatalCodeForFamily(family), FatalCode::DeviceLost)
<< FatalFamilyName(family) << " projects onto DeviceLost, which only the latch may set";
}
}
TEST(FatalFamily, NamesAreDistinctAndNonEmpty) {
std::set<std::string> seen;
for (const MGFatalFamily family : kAllFamilies) {
const std::string name = FatalFamilyName(family);
EXPECT_FALSE(name.empty());
EXPECT_NE(name, "<unknown>") << "a real family resolved to the fallback name";
EXPECT_TRUE(seen.insert(name).second) << name << " is not a distinct family name";
}
}
TEST(FatalFamily, TheAnchorFamiliesProjectWhereTheirMeaningSays) {
// A handful pinned by hand, so a projection that drifted in a bulk edit is caught by meaning
// and not only by "it still maps to something".
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::ProtocolCorruption), FatalCode::ProtocolCorruption);
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::RingOverrun), FatalCode::RingOverrun);
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::EventRingOverflow), FatalCode::RingOverrun);
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::AbiMismatch), FatalCode::AbiMismatch);
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::StageSnapshotTooNarrow), FatalCode::SegmentMismatch);
// The liveness families are what a WAITING peer attributes to the other side being gone.
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::BarrierTimeout), FatalCode::ServerCrashed);
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::ApplyThreadNotRunning), FatalCode::ServerCrashed);
// An unmigrated verb is a protocol-level "cannot honour this", not a crash.
EXPECT_EQ(FatalCodeForFamily(MGFatalFamily::UnmigratedVerb), FatalCode::ProtocolCorruption);
}
TEST(FatalFamily, TheSessionFaultFrameCarriesTheFamilyAndItsCode) {
// `dl` step three (5.2): the Fatal frame a dying session publishes carries the full family
// WORD beside the coarse code, so a peer names which family ended the session instead of
// reading a bare EOF. This is the wire round-trip that proves the field is there and that the
// code the frame carries is the family's own projection.
for (const MGFatalFamily family : kAllFamilies) {
::flatbuffers::FlatBufferBuilder builder(256);
const auto fatal = ::MobileGL::Wire::CreateFatalDirect(
builder, FatalCodeForFamily(family), "detail line", FatalFamilyName(family));
const auto root = ::MobileGL::Wire::CreateCtrlEnvelope(
builder, ::MobileGL::Wire::CtrlMsg::Fatal, fatal.Union());
::MobileGL::Wire::FinishCtrlEnvelopeBuffer(builder, root);
::flatbuffers::Verifier verifier(builder.GetBufferPointer(), builder.GetSize());
ASSERT_TRUE(::MobileGL::Wire::VerifyCtrlEnvelopeBuffer(verifier));
const auto* envelope = ::MobileGL::Wire::GetCtrlEnvelope(builder.GetBufferPointer());
ASSERT_EQ(envelope->msg_type(), ::MobileGL::Wire::CtrlMsg::Fatal);
const auto* decoded = envelope->msg_as_Fatal();
ASSERT_NE(decoded, nullptr);
ASSERT_NE(decoded->family(), nullptr) << "the family field did not survive the wire";
EXPECT_STREQ(decoded->family()->c_str(), FatalFamilyName(family));
EXPECT_EQ(decoded->code(), FatalCodeForFamily(family));
}
}
+18 -15
View File
@@ -22,6 +22,7 @@
// comes back through the recording ReplySink on the record's own seq (R-3/R-5).
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <cstdio>
#include <cstdlib>
@@ -75,10 +76,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
long ProcessId() {
@@ -143,10 +144,10 @@ namespace {
}
const bool result = m_decoder.DecodeAndApply(view);
++m_sessionApplied;
m_control.appliedSeq.store(m_sessionApplied, std::memory_order_release);
m_control.Progress.appliedSeq.store(m_sessionApplied, std::memory_order_release);
// Nothing in P5 borrows a ring slot into the GPU timeline, so a record's SEG_STAGE
// runs retire as soon as it is applied (table 1's "retires: apply").
m_control.retiredSeq.store(m_sessionApplied, std::memory_order_release);
m_control.Progress.retiredSeq.store(m_sessionApplied, std::memory_order_release);
m_consumer.PublishRetired();
if (applied != nullptr) {
*applied = result;
@@ -561,8 +562,8 @@ TEST_F(PipeWireCodecTest, KNoneRoundTripsAndReachesItsApplier) {
ASSERT_TRUE(wire.PumpOne(&applied));
EXPECT_TRUE(applied);
EXPECT_EQ(wire.Decoder().AppliedSeq(), 1u);
EXPECT_EQ(wire.Control().appliedSeq.load(), 1u);
EXPECT_EQ(wire.Control().retiredSeq.load(), 1u);
EXPECT_EQ(wire.Control().Progress.appliedSeq.load(), 1u);
EXPECT_EQ(wire.Control().Progress.retiredSeq.load(), 1u);
}
TEST_F(PipeWireCodecTest, KHasBlobRoundTripsWithARealChunkBlob) {
@@ -1742,7 +1743,7 @@ TEST_F(PipeWireCodecTest, AppliedSeqAdvancesByExactlyOnePerRecordAndIsNeverBatch
bool applied = false;
ASSERT_TRUE(wire.PumpOne(&applied));
EXPECT_EQ(wire.Decoder().AppliedSeq(), i);
EXPECT_EQ(wire.Control().appliedSeq.load(), i);
EXPECT_EQ(wire.Control().Progress.appliedSeq.load(), i);
EXPECT_EQ(wire.SessionAppliedSeq(), wire.Decoder().AppliedSeq());
}
EXPECT_EQ(wire.Encoder().EmitSeq(), 5u);
@@ -1763,13 +1764,13 @@ TEST_F(PipeWireCodecTest, TheDecoderWritesNoRingControlFieldOfItsOwn) {
bool corrupt = false;
ASSERT_TRUE(wire.Consumer().Pop(view, &corrupt));
ASSERT_FALSE(corrupt);
const std::uint64_t appliedBefore = wire.Control().appliedSeq.load();
const std::uint64_t retiredBefore = wire.Control().retiredSeq.load();
const std::uint64_t appliedBefore = wire.Control().Progress.appliedSeq.load();
const std::uint64_t retiredBefore = wire.Control().Progress.retiredSeq.load();
(void)wire.Decoder().DecodeAndApply(view);
EXPECT_EQ(wire.Control().appliedSeq.load(), appliedBefore);
EXPECT_EQ(wire.Control().retiredSeq.load(), retiredBefore);
EXPECT_EQ(wire.Control().Progress.appliedSeq.load(), appliedBefore);
EXPECT_EQ(wire.Control().Progress.retiredSeq.load(), retiredBefore);
EXPECT_EQ(wire.Decoder().AppliedSeq(), 1u); // the decoder's own tally did move
}
@@ -2839,7 +2840,8 @@ TEST_F(PipeWireCodecTest, AdoptTierZeroIsFatalOnTheWirePathAndNamesP11) {
(void)wire.PumpOne(&applied);
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("MOBILEGL_IPC_ADOPT_TIER=0 names adoption tier T0, which P11 implements"),
EXPECT_NE(r.Log.find("Fatal{UnimplementedAdoptTier, \"T0\"} - MOBILEGL_IPC_ADOPT_TIER=0 "
"names an adoption tier P11 implements"),
std::string::npos)
<< r.Log;
}
@@ -2855,7 +2857,8 @@ TEST_F(PipeWireCodecTest, AdoptTierOneIsFatalOnTheWirePathAndNamesP11) {
(void)wire.PumpOne(&applied);
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("MOBILEGL_IPC_ADOPT_TIER=1 names adoption tier T1, which P11 implements"),
EXPECT_NE(r.Log.find("Fatal{UnimplementedAdoptTier, \"T1\"} - MOBILEGL_IPC_ADOPT_TIER=1 "
"names an adoption tier P11 implements"),
std::string::npos)
<< r.Log;
}
@@ -644,7 +644,7 @@ TEST(RemoteClientControls, CommandWrapWaitsForRetirementAfterThePriorRecordAppli
peer.Install(); // A mailbox round trip also lets the previous drain retire.
Srv::ServerLoopInstance().SetBeforeRetireHookForTesting(&HoldRetirementUntilProducerWaits);
const auto prior = emit(32768);
if (ClientSessionInstance().Control()->retiredSeq.load() >= prior) ::_exit(111);
if (ClientSessionInstance().Control()->Progress.retiredSeq.load() >= prior) ::_exit(111);
retirementRetryStarted.store(true);
const auto next = emit(32768);
if (next != prior + 1 || !retirementWaitObserved.load()) ::_exit(112);
@@ -664,7 +664,7 @@ TEST(RemoteClientControls, StagingWaitsForRetirementAfterThePriorRecordApplied)
MGPBindRenderState bind{};
const auto prior = session.EmitAndWait(MGPWireOp::BindRenderState, &bind, sizeof(bind),
nullptr, 0, nullptr, 0, nullptr);
if (session.Control()->retiredSeq.load() >= prior) ::_exit(113);
if (session.Control()->Progress.retiredSeq.load() >= prior) ::_exit(113);
retirementRetryStarted.store(true);
session.Encoder().StageBytes(bytes.data(), bytes.size());
if (!retirementWaitObserved.load() || session.Encoder().StageReclaimWaits() != 1) ::_exit(114);
@@ -56,11 +56,11 @@ void CheckE1Boundary(Bool serverCap, MGPWireOp op, Bool expectWait, const char*
: session.EmitAndWait(op, &clear, sizeof(clear), nullptr, 0, nullptr, 0, nullptr);
// Observe BEFORE allowing the peer to complete a non-waiting emission.
const Bool parked = bell.entered.load();
const Bool appliedBeforeReturn = session.Control()->appliedSeq.load() >= seq;
const Bool appliedBeforeReturn = session.Control()->Progress.appliedSeq.load() >= seq;
peer.clientReturned.store(true);
producer.*PeerMember(ProducerBellTag{}) = bell.original;
if (session.WaitForApplied(seq, 2000) != Transport::SessionWait::Reached) ::_exit(85);
if (seq <= before || peer.seen.load() != 1 || session.Control()->appliedSeq.load() < seq) ::_exit(86);
if (seq <= before || peer.seen.load() != 1 || session.Control()->Progress.appliedSeq.load() < seq) ::_exit(86);
const Bool correct = expectWait ? parked && appliedBeforeReturn : !parked && !appliedBeforeReturn;
std::printf("E1 observation: op=%s cap=%u barrier=%u parked=%u applied_before_return=%u emitted=1 peer_seen=1\n",
op == MGPWireOp::GenerateMipmap ? "GenerateMipmap" : "Clear",
+13 -7
View File
@@ -18,6 +18,7 @@
// assert ITS OWN failure string (R-16) instead of asserting that something, somewhere, died.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <cstdio>
#include <cstdlib>
@@ -78,12 +79,17 @@ namespace {
std::string g_logPath;
// BOTH ROLES' LOGS. P6 gives the client and the server role a file each, and a death test
// asserts that the CHILD said something - which role's thread said it is not what these
// cases are about. The refusals raised on the apply thread (RefuseFromApplyThread and every
// guard that rides it) are written under the SERVER role by construction, so a reader that
// took only g_logPath would report "the child aborted, but said nothing" for the very
// diagnostics it exists to check.
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
if (!in) return {};
std::ostringstream out;
out << in.rdbuf();
return out.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
int ProcessId() {
@@ -146,7 +152,7 @@ namespace {
// child's output. That is how the second death case in this file came to see the first
// one's slot name and assert on it: a control reading another control's message, which
// is one of the three shapes R-16 was written after.
{ std::ofstream truncate(g_logPath, std::ios::trunc | std::ios::binary); }
MobileGL::MG_Util::Debug::TruncateRoleLogs(g_logPath.c_str());
std::fflush(nullptr);
const pid_t pid = ::fork();
if (pid < 0) return result;
@@ -2444,7 +2450,7 @@ TEST(RemoteRunAhead, ACreditOneClientPaysTheCreditAtEveryPresentAfterTheFirst) {
// ONE CREDIT PER SWAP, in the client's own 1-based space: the server returned the
// second present's credit, so the watermark is at least 2.
if (session.Control() == nullptr ||
session.Control()->presentAckSerial.load() < 2u) {
session.Control()->Progress.presentAckSerial.load() < 2u) {
::_exit(104);
}
session.Stop();
+28 -12
View File
@@ -109,11 +109,27 @@ TEST(RingTest, ControlPageLayoutIsTheSharedContract) {
EXPECT_EQ(offset(&control.cmdAppliedTail) % 64, 0);
EXPECT_EQ(offset(&control.stageHead) % 64, 0);
EXPECT_EQ(offset(&control.stageAppliedTail) % 64, 0);
EXPECT_EQ(offset(&control.appliedSeq) % 64, 0);
EXPECT_EQ(offset(&control.Progress.appliedSeq) % 64, 0);
EXPECT_EQ(offset(&control.serverEpoch) % 64, 0);
// cmdHead and cmdAppliedTail are written by different processes: they must
// not share a line.
EXPECT_NE(offset(&control.cmdHead) / 64, offset(&control.cmdAppliedTail) / 64);
// lk (CONTRACT-P6 §8.3) regrouped this page BY WRITER, and submittedSeq is the field
// it moved. Assert that here rather than borrowing the claim from Ring.h's
// static_asserts: this test is named for the layout being a shared contract, and it
// said nothing about the one field the regroup touched.
EXPECT_EQ(offset(&control.submittedSeq) / 64, offset(&control.cmdHead) / 64)
<< "submittedSeq is producer-written and belongs on the producer's line";
EXPECT_NE(offset(&control.submittedSeq) / 64, offset(&control.Progress.appliedSeq) / 64)
<< "a producer-written field on the consumer's watermark line is what lk removed";
// The two event flags stay OUT of Progress on purpose: the client clears eventRingFull
// with an RMW on every drain, and Progress's line is the one the client spins on.
EXPECT_NE(offset(&control.eventRingFull) / 64, offset(&control.Progress.appliedSeq) / 64)
<< "eventRingFull's per-drain RMW may not land on the spin line";
EXPECT_EQ(offset(&control.eventRingFull) / 64, offset(&control.serverEpoch) / 64)
<< "the event flags live in the doorbell group, where mixed writers already are";
}
TEST(RingTest, RejectsANonPowerOfTwoCapacity) {
@@ -538,10 +554,10 @@ TEST(RingTest, WatermarksAreAllZeroUntilSomeoneAdvancesThem) {
alignas(4096) RingControl control{};
InitRingControl(control);
EXPECT_EQ(control.submittedSeq.load(), 0u);
EXPECT_EQ(control.appliedSeq.load(), 0u);
EXPECT_EQ(control.retiredSeq.load(), 0u);
EXPECT_EQ(control.completedFrameSerial.load(), 0u);
EXPECT_EQ(control.presentAckSerial.load(), 0u);
EXPECT_EQ(control.Progress.appliedSeq.load(), 0u);
EXPECT_EQ(control.Progress.retiredSeq.load(), 0u);
EXPECT_EQ(control.Progress.completedFrameSerial.load(), 0u);
EXPECT_EQ(control.Progress.presentAckSerial.load(), 0u);
// ... while the two GENERATIONS start at one, because for them zero means
// "uninitialized" and must never be a legal value. The two conventions are
// opposite on purpose and are next to each other in the same struct.
@@ -559,9 +575,9 @@ TEST(RingTest, AWatermarkWaiterMustTestGreaterOrEqualRatherThanEqual) {
const std::uint64_t mySeq = 7;
// The peer jumps straight past the value this waiter cares about.
control.appliedSeq.store(mySeq + 1, std::memory_order_release);
control.Progress.appliedSeq.store(mySeq + 1, std::memory_order_release);
const std::uint64_t seen = control.appliedSeq.load(std::memory_order_acquire);
const std::uint64_t seen = control.Progress.appliedSeq.load(std::memory_order_acquire);
EXPECT_FALSE(seen == mySeq) << "an equality waiter is still asleep at this point";
EXPECT_TRUE(seen >= mySeq) << "the >= waiter this contract mandates has been released";
}
@@ -582,11 +598,11 @@ TEST(RingTest, AppliedSeqAdvancesOncePerRecordAndIsNeverBatchedInP5) {
RingRecordView view{};
while (ring.Consumer().Pop(view)) {
++applied;
ring.Control().appliedSeq.store(applied, std::memory_order_release);
ring.Control().Progress.appliedSeq.store(applied, std::memory_order_release);
// The reader's guarantee, checked at EVERY record rather than at the end:
// a batched watermark would sit at 0 here for 63 of every 64 iterations,
// and a client barrier reading it would block on work that already ran.
EXPECT_EQ(ring.Control().appliedSeq.load(std::memory_order_acquire), applied);
EXPECT_EQ(ring.Control().Progress.appliedSeq.load(std::memory_order_acquire), applied);
}
EXPECT_EQ(applied, static_cast<std::uint64_t>(kRecords));
EXPECT_TRUE(ring.Invariants());
@@ -610,13 +626,13 @@ TEST(RingTest, ALazyWatermarkMayTrailTheWorkButMustNeverLeadIt) {
++drained;
// A deliberately lazy publisher: only every third record. This is legal.
if (drained % 3 == 0) {
ring.Control().retiredSeq.store(drained, std::memory_order_release);
ring.Control().Progress.retiredSeq.store(drained, std::memory_order_release);
}
EXPECT_LE(ring.Control().retiredSeq.load(std::memory_order_acquire), drained)
EXPECT_LE(ring.Control().Progress.retiredSeq.load(std::memory_order_acquire), drained)
<< "retiredSeq ran ahead of the drain; those staged bytes are still live";
}
// Trailing at the end is fine and is what "late" means.
EXPECT_LE(ring.Control().retiredSeq.load(), static_cast<std::uint64_t>(kRecords));
EXPECT_LE(ring.Control().Progress.retiredSeq.load(), static_cast<std::uint64_t>(kRecords));
EXPECT_TRUE(ring.Invariants());
}
+7 -5
View File
@@ -29,6 +29,7 @@
// exists to test: bytes that were copied survive the source being overwritten with 0xDD.
#include <Config.h>
#include <MG_Util/Debug/Log.h>
#include <MG_Backend/BackendObject.h>
#include <MG_Backend/BackendObjects.h>
#include <MG_Backend/DirectGLES/BackendObject_DirectGLES.h>
@@ -102,9 +103,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
if (!in) return {};
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
unsigned ProcessId() {
@@ -693,11 +695,11 @@ TEST(ServerLoopTest, TheSessionWatermarkAndTheDecoderTallyAgreeAfterEveryRecord)
// instantly would be asserting a promise R-9 deliberately does not make. The BOUND is what
// keeps this a check: a loop that never retires times out here instead of passing.
const auto retireDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
while (fixture.clientSegments.CmdControl()->retiredSeq.load() < 8u &&
while (fixture.clientSegments.CmdControl()->Progress.retiredSeq.load() < 8u &&
std::chrono::steady_clock::now() < retireDeadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
EXPECT_GE(fixture.clientSegments.CmdControl()->retiredSeq.load(), 8u)
EXPECT_GE(fixture.clientSegments.CmdControl()->Progress.retiredSeq.load(), 8u)
<< "the apply loop advanced appliedSeq but never retired within 2 s, so SEG_STAGE would "
"never be reclaimed and the first MOBILEGL_IPC_STAGE_MB would end in "
"Fatal{RingOverrun}";
+423
View File
@@ -0,0 +1,423 @@
// MobileGL - MobileGL/MG_Test/Wire/ServerSpawnTest.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// Two MobileGL processes, started INDEPENDENTLY and joined by a name.
// Package `sm`.
//
// THE SHAPE IS THE POINT. The server is launched with an endpoint and nothing
// else - no inherited descriptor, no shared memory, no handshake from its
// parent - and the client finds it by connecting to that name. Everything these
// cases prove therefore transfers unchanged to a server somebody started by
// hand, or that an Android Service started minutes earlier, which is the only
// arrangement the end state can use.
//
// Each assertion exists because something would otherwise pass silently:
//
// the image links - a6 found mobilegl_server_main existed NOWHERE in
// the tree, only in ARCHITECTURE.md:488-496. A
// target that failed to link would make every case
// below read as "did not run".
// the bytes crossed a - the echo carries the SERVER's own getpid(), so a
// PROCESS test that accidentally talked to itself cannot
// pass. ID-124's lesson at the smallest scale.
// the process tree is clean- §9.4: exactly one child while running, zero
// after. Counted, not promised.
// the server dies on EOF - and on EOF ONLY. §5.4 forbids a timeout from ever
// standing in for the death fact, so the client
// closes and the server must go by itself.
// SCM_RIGHTS works across - the mechanism the four segments ride on, proven
// the boundary before the data plane needs it.
#include <MG_Remote/Client/ClientSession.h>
#include <MG_Remote/Server/ServerLoop.h>
#include <MG_Remote/Server/ServerSpawn.h>
#include <MG_Remote/Transport/Doorbell.h>
#include <MG_Remote/Transport/FdPassing.h>
#include <MG_Remote/Transport/SocketTransport.h>
#include <gtest/gtest.h>
#include <chrono>
#include <csignal>
#include <cstdlib>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#if !defined(_WIN32)
#include <sys/socket.h>
#include <unistd.h>
#endif
using namespace MobileGL::MG_Remote;
#if !defined(_WIN32)
namespace {
// A private rendezvous per case. Independent processes need a NAME, and a
// per-case one is what stops two runs colliding the way a default endpoint
// would.
std::string Endpoint(const char* label) {
return std::string("/tmp/mgl-sm-") + label + "-" + std::to_string(::getpid()) + ".sock";
}
std::string ServerImage() {
if (const char* explicitPath = std::getenv("MOBILEGL_TEST_SERVER_PATH")) {
return explicitPath;
}
return "libMobileGLServer.so";
}
struct Session {
Server::LaunchedServer server;
std::unique_ptr<Transport::SocketTransport> client;
};
// The two halves a real deployment does separately: start a process, then
// connect to it. The bounded connect retry is the CLIENT's, not the
// launcher's - a launcher that waited for the server to be ready would be
// coupling the two processes again by the back door.
bool Bring(const char* label, Session* out) {
const std::string endpoint = Endpoint(label);
if (Server::LaunchServer(ServerImage(), endpoint, &out->server) != MOBILEGL_OK) {
return false;
}
return Transport::SocketTransport::ConnectTo(endpoint, 10000, out->client) == MOBILEGL_OK;
}
// Closing the connection is what the server sees as EOF, and EOF is the whole
// exit condition. The launcher holds nothing to close.
void CloseAndReap(Session& session, int* outExitCode) {
if (session.client) {
session.client->Shutdown();
}
ASSERT_EQ(Server::ReapServer(session.server, 5000, outExitCode), MOBILEGL_OK);
}
// The REAL handshake, not an echo. ServerMain runs ServerSession::Accept,
// which wants a Hello and answers Welcome plus six SCM_RIGHTS offers - so a
// test that spoke anything else would only ever prove the socket works.
// Driving ClientSession is what proves the SEGMENTS crossed.
MobileGLResult Handshake(Session& session) {
return Client::ClientSessionInstance().StartOverSocket(std::move(session.client));
}
std::string Exchange(Transport::ITransport& transport, const std::string& message,
std::uint32_t timeoutMs = 4000) {
const MobileGLResult sent =
transport.SendFrame(MobileGLByteSpan{message.data(), message.size()});
if (sent != MOBILEGL_OK) {
return "<send-failed>";
}
std::vector<std::uint8_t> buffer(64 * 1024);
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
const MobileGLResult got = transport.ReceiveFrame(span, &size, timeoutMs);
if (got != MOBILEGL_OK) {
return std::string("<result=") + std::to_string(static_cast<int>(got)) + ">";
}
return std::string(reinterpret_cast<const char*>(buffer.data()),
static_cast<std::size_t>(size));
}
} // namespace
TEST(ServerSpawnTest, StartsAServerProcessAndHandshakesAcrossIt) {
const int before = Server::CountOwnChildren();
ASSERT_GE(before, 0) << "/proc unreadable; the process-tree gate cannot run here";
Session session;
ASSERT_TRUE(Bring("handshake", &session));
ASSERT_GT(session.server.pid, 0);
EXPECT_NE(session.server.pid, static_cast<int>(::getpid()))
<< "that is this process, not a separate one";
EXPECT_EQ(Server::CountOwnChildren(), before + 1);
// THE WHOLE POINT. Hello crosses, Welcome comes back with four SegmentRefs,
// six descriptors arrive over SCM_RIGHTS, and this process maps memory that
// another process created. Nothing here was inherited.
ASSERT_EQ(Handshake(session), MOBILEGL_OK);
EXPECT_TRUE(Client::ClientSession::Active() != nullptr)
<< "a handshake that returned OK must leave the session emit-armed";
Client::ClientSessionInstance().Stop();
int exitCode = -1;
ASSERT_EQ(Server::ReapServer(session.server, 5000, &exitCode), MOBILEGL_OK);
EXPECT_EQ(exitCode, 0) << "the server must exit cleanly on EOF, not be killed";
EXPECT_EQ(Server::CountOwnChildren(), before) << "a zombie would still be counted here";
}
TEST(ServerSpawnTest, AnEglControlOpCrossesToTheOtherProcessAndAnswers) {
// `cp`. All twelve Server* EGL forwarders funnel through
// ServerLoop::RunSurfaceControlFrame, so this exercises the ONE seam that
// sends them: encode -> control socket -> the server's pump ->
// ServerApplyWireSurfaceOp -> its one-slot mailbox -> the apply thread ->
// SurfaceReply -> back here.
//
// Under inproc this same call posts into a mailbox in THIS process. The
// assertion that it is not doing that here is the server's pid in the
// handshake plus the fact that ServerLoopInstance() in this process was
// never started - a local post would find no apply thread and time out.
Session session;
ASSERT_TRUE(Bring("eglop", &session));
ASSERT_EQ(Handshake(session), MOBILEGL_OK);
// eglInitialize's forwarder: the simplest op that has a real answer.
EGLint major = -1;
EGLint minor = -1;
const bool ok = Server::ServerInitializeEGLDisplay(EGL_NO_DISPLAY, &major, &minor);
// WHAT IS ASSERTED IS THE ROUND TRIP, not the EGL result. A headless CI
// machine has no display to initialise, so `ok` is expected to be false -
// and that is fine, because `cp` is done when the op reaches the other
// process and an answer comes back.
//
// THE OUT-PARAMETERS ARE THE PROOF. ServerInitializeEGLDisplay writes them
// "whenever the dispatch ran, success or not" (ServerLoop.cpp's own comment
// at the forwarder), so they move off -1 if and only if a SurfaceReply came
// back from the other process. A transport failure returns before the
// write-back and leaves both at -1; that is the difference this asserts.
EXPECT_NE(major, -1) << "no SurfaceReply came back: the op never reached the other process";
EXPECT_NE(minor, -1) << "no SurfaceReply came back: the op never reached the other process";
(void)ok;
Client::ClientSessionInstance().Stop();
int exitCode = -1;
ASSERT_EQ(Server::ReapServer(session.server, 5000, &exitCode), MOBILEGL_OK);
}
TEST(ServerSpawnTest, TheHandshakeCarriesTwoDifferentProcessIdsAndNotTwoZeroes) {
// CONTRACT-P6 4.3. Hello::pid was hard-coded 0 and Welcome::serverPid ECHOED it back, so the
// handshake carried 0 and 0 and named nothing at all. Both now carry real ids, which makes
// the pair the cheapest arm proof in the protocol: under spawn they MUST differ, and a
// same-process session cannot produce two different values.
//
// ServerSession records the pid it welcomed; ClientSession knows the child it launched. The
// assertion is that those two agree AND that neither is this process.
Session session;
ASSERT_TRUE(Bring("pids", &session));
ASSERT_EQ(Handshake(session), MOBILEGL_OK);
const std::uint32_t self = static_cast<std::uint32_t>(::getpid());
const std::uint32_t server = static_cast<std::uint32_t>(session.server.pid);
EXPECT_NE(server, 0u) << "the launcher did not record a child pid";
EXPECT_NE(server, self) << "that is this process, so there is nothing to prove";
// THE VALUE THAT CROSSED THE WIRE, not the one the launcher happens to remember. Welcome
// carries the server's own getpid(), so this equality says the handshake reached the process
// we started - rather than some other listener that answered on the name - and it says it
// from the server's own mouth.
EXPECT_EQ(Client::ClientSessionInstance().PeerServerPid(), server)
<< "Welcome::serverPid does not name the process we launched";
EXPECT_NE(Client::ClientSessionInstance().PeerServerPid(), self)
<< "the peer stated OUR pid; serverPid is echoing the client again (4.3)";
Client::ClientSessionInstance().Stop();
int exitCode = -1;
ASSERT_EQ(Server::ReapServer(session.server, 5000, &exitCode), MOBILEGL_OK);
}
TEST(ServerSpawnTest, AKilledServerLatchesDeviceLostFromTheHangupAndNotFromADeadline) {
// `dl`, and exit gate S2: kill -9 the server mid-session and the client must find out FROM A
// DESCRIPTOR. This is the red-once for CONTRACT-P6 D5c, whose whole content is that the
// client's own bell CANNOT witness the death - it holds both ends of that socketpair, so the
// fact has to come from somewhere else.
//
// WHAT MAKES THIS FALSIFIABLE IS THE CLOCK, not the boolean. A timeout would eventually
// report "gone" too, and 5.4 forbids that: under P5e run-ahead a server one frame behind is
// the INTENDED steady state, so anything armed by a deadline fires on a healthy session under
// load. The bound below is therefore deliberately far under every wait in the system - the
// verb barrier is 120000 ms and the control reply 5000 ms - so a pass here cannot be a
// timeout wearing the right answer.
Session session;
ASSERT_TRUE(Bring("devicelost", &session));
ASSERT_EQ(Handshake(session), MOBILEGL_OK);
EXPECT_FALSE(Client::ClientSession::DeviceLost())
<< "a healthy session must not read as a lost device";
Transport::Doorbell* bell = Client::ClientSessionInstance().SelfDoorbellForTest();
ASSERT_NE(bell, nullptr);
EXPECT_FALSE(bell->PeerHungUp()) << "nothing has hung up yet";
ASSERT_EQ(::kill(session.server.pid, SIGKILL), 0);
// Park with a SHORT budget, repeatedly, until the hangup lands. Each Park is what a real
// waiter does; the loop exists because the kill is asynchronous and the first poll may win
// the race. 200 x 10 ms is two seconds of patience against waits measured in minutes.
const auto start = std::chrono::steady_clock::now();
for (int attempt = 0; attempt < 200 && !bell->PeerHungUp(); ++attempt) {
(void)bell->Park(10);
}
const auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start).count();
EXPECT_TRUE(bell->PeerHungUp())
<< "the witness never reported the hangup; the bell is watching a descriptor this side "
"also holds, which is the exact defect D5c names";
EXPECT_TRUE(bell->Dead()) << "a peer that hung up is a dead bell";
EXPECT_LT(elapsedMs, 3000)
<< "took " << elapsedMs << " ms: too slow to be a hangup and fast enough only for a "
"descriptor, so this assertion is what separates the two mechanisms";
// AND THE LATCH ITSELF. PeerHungUp is the cause; DeviceLost is the session-scoped
// consequence, and it is what glGetGraphicsResetStatus reports.
Client::ClientSessionInstance().LatchDeviceLost("the test killed the server");
EXPECT_TRUE(Client::ClientSession::DeviceLost());
Client::ClientSessionInstance().Stop();
int exitCode = -1;
(void)Server::ReapServer(session.server, 5000, &exitCode);
}
TEST(ServerSpawnTest, AnOrderlyStopIsNotADeviceLoss) {
// The session-level control: a clean shutdown must leave the latch disarmed, or every exit
// would report a context reset and the status would mean nothing.
//
// NOTE WHAT THIS DOES *NOT* PROVE, because the first draft of this comment claimed it did
// and the R-16 falsification caught the lie. Collapsing PeerHungUp() into Dead() leaves this
// test green: Stop() kills the bell through CondVarDoorbell::Kill(), and under SPAWN the
// self bell is a SocketDoorbell, which has no Kill at all - so Dead() is false here either
// way. ADeadBellIsNotAlwaysAHungUpPeer below is the case that separates them.
Session session;
ASSERT_TRUE(Bring("orderly", &session));
ASSERT_EQ(Handshake(session), MOBILEGL_OK);
Transport::Doorbell* bell = Client::ClientSessionInstance().SelfDoorbellForTest();
ASSERT_NE(bell, nullptr);
Client::ClientSessionInstance().Stop();
int exitCode = -1;
ASSERT_EQ(Server::ReapServer(session.server, 5000, &exitCode), MOBILEGL_OK);
EXPECT_EQ(exitCode, 0) << "the server must have exited cleanly, not been killed";
EXPECT_FALSE(bell->PeerHungUp())
<< "an orderly Stop() must not look like a peer that died";
EXPECT_FALSE(Client::ClientSession::DeviceLost())
<< "a clean teardown armed the device-lost latch; every exit would report a reset";
}
TEST(ServerSpawnTest, ADeadBellIsNotAlwaysAHungUpPeer) {
// THE ASSERTION THAT MAKES `dl`'s CAUSE/FACT SPLIT LOAD-BEARING, and it exists because the
// session-level control above turned out not to. Park() latches m_dead for several reasons
// that are NOT a peer death - POLLERR, POLLNVAL, an unrecognised revents - and each of them
// is a fault in THIS process's descriptor. A latch armed from Dead() would report a lost
// GPU for a bug in our own fd handling.
//
// Falsified by construction: make PeerHungUp() return Dead() and this goes red, which is
// exactly what the contract's D5c distinction has to be able to do.
int pair[2] = {-1, -1};
ASSERT_EQ(::socketpair(AF_UNIX, SOCK_STREAM, 0, pair), 0);
// ownsFds=false: the bell must not close what this test is about to invalidate underneath
// it, or the destructor closes a descriptor number somebody else has since been given.
Transport::SocketDoorbell bell(pair[0], pair[1], /*code=*/1, /*ownsFds=*/false);
bell.SetDeathWitness(-1); // no witness: nothing here can legitimately report a hangup
EXPECT_FALSE(bell.Dead());
EXPECT_FALSE(bell.PeerHungUp());
// Close the park end UNDER the bell. poll() then answers POLLNVAL, which Park treats as a
// descriptor it must never poll again - dead, but not bereaved.
ASSERT_EQ(::close(pair[0]), 0);
(void)bell.Park(50);
EXPECT_TRUE(bell.Dead()) << "a bell polling a closed fd cannot be anything but dead";
EXPECT_FALSE(bell.PeerHungUp())
<< "our own descriptor went bad and the bell called it a peer death; a device-lost latch "
"taken from this would report a lost GPU for a local fd bug";
::close(pair[1]);
}
TEST(ServerSpawnTest, AnAbstractEndpointNeedsNoWritableDirectoryAndLeavesNoFile) {
// THE ONLY RENDEZVOUS THAT WORKS ON ANDROID, and the reason is not a preference.
// An app has no writable /tmp; the first device run of the spawn retrace launched
// its server, bind() had nowhere to put the node, and the client refused by name
// 20 s later. ClientSession::StartSpawned mints '@' names now, so this pins the
// shape that path depends on.
//
// TWO FACTS, and the second is what a filesystem endpoint cannot give: the
// handshake works over it, and NOTHING IS LEFT BEHIND - no node to go stale, no
// directory to be writable, no unlink to forget after a crash.
const std::string endpoint = std::string("@mgl-abstract-") + std::to_string(::getpid());
Session session;
ASSERT_EQ(Server::LaunchServer(ServerImage(), endpoint, &session.server), MOBILEGL_OK);
ASSERT_EQ(Transport::SocketTransport::ConnectTo(endpoint, 10000, session.client), MOBILEGL_OK);
ASSERT_EQ(Handshake(session), MOBILEGL_OK)
<< "an abstract endpoint carried the connection but not the session";
// A leading '@' is a NAME, not a path. If FillAddress had treated it as one, the
// bind would have created a file literally called "@mgl-..." in the working
// directory - which would still have worked here, and would have failed on the
// one platform this exists for.
EXPECT_NE(::access(endpoint.c_str(), F_OK), 0)
<< "an abstract name must leave no filesystem node: " << endpoint;
Client::ClientSessionInstance().Stop();
int exitCode = -1;
ASSERT_EQ(Server::ReapServer(session.server, 5000, &exitCode), MOBILEGL_OK);
EXPECT_EQ(exitCode, 0);
}
TEST(ServerSpawnTest, AnUnresolvableImageIsANamedRefusalAndStartsNothing) {
const int before = Server::CountOwnChildren();
// S1 (CONTRACT-P6 §9). The accident this prevents is the one
// ConfigLoader.cpp names in its own comment: a lane that asked for spawn,
// silently got monolith, and went green on the wrong arm.
Server::LaunchedServer server;
EXPECT_EQ(Server::LaunchServer("/nonexistent/libMobileGLServer.so", Endpoint("missing"),
&server),
MOBILEGL_ERR_INVALID_ARGUMENT);
EXPECT_EQ(server.pid, -1);
EXPECT_EQ(Server::CountOwnChildren(), before) << "a refused launch must leave no process";
}
TEST(ServerSpawnTest, ConnectingToNothingIsANamedRefusalNotAHang) {
// The other half of S1: the client's side. A rendezvous nobody is listening
// on must be a bounded, named failure - never an unbounded wait, which is
// what a caller would experience as the whole application freezing.
std::unique_ptr<Transport::SocketTransport> client;
const auto start = std::chrono::steady_clock::now();
EXPECT_NE(Transport::SocketTransport::ConnectTo(Endpoint("nobody"), 300, client), MOBILEGL_OK);
EXPECT_FALSE(client);
EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start)
.count(),
4000);
}
TEST(ServerSpawnTest, ADescriptorCrossesBetweenTheTwoProcesses) {
// The mechanism the four shared segments ride on. Proving it now, on a pipe,
// is what stops it being first exercised on the day the data plane needs it -
// the same argument SessionRings.h makes about the attach half.
//
// NOTE it crosses the AUX connection, which is the second of the two the
// client made. An fd offer is a sendmsg whose ancillary data rides with
// specific bytes, so it may not share a socket with the framed control
// stream: the frame reassembler and the descriptor receiver would race for
// the same bytes.
Session session;
ASSERT_TRUE(Bring("scm", &session));
int pipeFds[2] = {-1, -1};
ASSERT_EQ(::pipe(pipeFds), 0);
const std::string sideband = "SegmentRef{id=1,kind=Cmd}";
EXPECT_EQ(session.client->ShareFd(pipeFds[0],
MobileGLByteSpan{sideband.data(), sideband.size()}),
MOBILEGL_OK);
::close(pipeFds[0]);
::close(pipeFds[1]);
int exitCode = -1;
CloseAndReap(session, &exitCode);
}
#endif // !_WIN32
+33 -6
View File
@@ -23,6 +23,7 @@
// EVERY CASE BELOW CARRIES ITS RED-ONCE LINE, and each of those perturbations was run.
#include <gtest/gtest.h>
#include <MG_Util/Debug/Log.h>
#include <cstdint>
#include <cstdlib>
@@ -66,10 +67,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
long ProcessId() {
@@ -136,10 +137,25 @@ TEST(SessionHandshakeTest, TheAbiFingerprintChangesWhenAnyOfItsInputsDoes) {
EXPECT_EQ(inputs.OpCount, static_cast<Uint64>(MG_Pipe::MGPWireOp::kOpCount));
EXPECT_EQ(inputs.AbiVersion, static_cast<Uint32>(MOBILEGL_ABI_VERSION(
MOBILEGL_PROTOCOL_ABI_MAJOR, MOBILEGL_PROTOCOL_ABI_MINOR)));
// CONTRACT-P6 4.2. THE ASSERTION SPLITS WITH THE MACRO PAIR, and it has to: this used to
// demand a non-empty stamp unconditionally and was RED in every build whose git could not be
// read - a real signal, but one that told the reader nothing about WHICH of the two states
// the build was in. Now the build system states it, and both states are asserted.
ASSERT_NE(inputs.BuildStamp, nullptr);
EXPECT_NE(inputs.BuildStamp[0], '\0');
EXPECT_EQ(inputs.BuildStampPresent, static_cast<Uint32>(MOBILEGL_BUILD_STAMP_PRESENT))
<< "the fingerprint disagrees with the build system about whether this build has a stamp";
#if MGL_HANDSHAKE_TEST_HAS_GIT_HASH
EXPECT_STREQ(inputs.BuildStamp, GIT_COMMIT_HASH_SHORT);
EXPECT_STREQ(inputs.BuildStamp, MOBILEGL_BUILD_STAMP_VALUE);
#endif
#if MOBILEGL_BUILD_STAMP_PRESENT
EXPECT_NE(inputs.BuildStamp[0], '\0')
<< "the build claims a stamp and the fingerprint mixed an empty one";
#else
// A stampless build is a KNOWN, DECLARED state - CMake warns at configure time - but it must
// not be a silent one here either. What still has to hold is that the ABSENCE is mixed, which
// the BuildStampPresent perturbation below proves.
EXPECT_STREQ(inputs.BuildStamp, "")
<< "PRESENT is 0 but a value came through; the two halves of the pair disagree";
#endif
// Every input moves the answer. Each lambda changes exactly one field of a copy of the
@@ -176,8 +192,19 @@ TEST(SessionHandshakeTest, TheAbiFingerprintChangesWhenAnyOfItsInputsDoes) {
perturbed([](Transport::AbiFingerprintInputs& i) { i.BuildStamp = "not-this-build"; }))
<< "the git stamp is not mixed";
// A missing stamp is not the same as an empty one, and neither is the same as a real build.
// THE PRESENCE FLAG IS ITSELF AN INPUT (4.2), and this is the assertion that makes a
// stampless build safe to reason about: a peer that says "I could not name my commit" must
// not produce the same fingerprint as one whose commit genuinely is "". It has to move the
// answer in EITHER build state, which is why it sits outside the #if below.
EXPECT_NE(production, perturbed([](Transport::AbiFingerprintInputs& i) { ++i.BuildStampPresent; }))
<< "BuildStampPresent is not mixed; 'no stamp' and 'empty stamp' are one input again";
EXPECT_NE(production, perturbed([](Transport::AbiFingerprintInputs& i) { i.BuildStamp = nullptr; }));
#if MOBILEGL_BUILD_STAMP_PRESENT
// Vacuous without a stamp: production's value already IS "", so this perturbation would be
// the identity and the assertion would pass while proving nothing.
EXPECT_NE(production, perturbed([](Transport::AbiFingerprintInputs& i) { i.BuildStamp = ""; }));
#endif
EXPECT_NE(perturbed([](Transport::AbiFingerprintInputs& i) { i.BuildStamp = nullptr; }),
perturbed([](Transport::AbiFingerprintInputs& i) { i.BuildStamp = ""; }))
<< "\"no stamp\" and \"an empty stamp\" collapsed into one input";
+25 -25
View File
@@ -146,7 +146,7 @@ TEST(SessionTest, SessionSegmentsAreRealSharedMemoryAndNotAHeapAllocation) {
ASSERT_NE(segments.EventControl(), nullptr);
EXPECT_EQ(segments.CmdControl()->ringGeneration.load(), 1u);
EXPECT_EQ(segments.EventControl()->ringGeneration.load(), 1u);
EXPECT_EQ(segments.CmdControl()->appliedSeq.load(), 0u);
EXPECT_EQ(segments.CmdControl()->Progress.appliedSeq.load(), 0u);
segments.Close();
EXPECT_FALSE(segments.Valid());
}
@@ -415,7 +415,7 @@ TEST(SessionTest, TwoThreadsMoveTwentyThousandRecordsAndAgreeOnEveryOne) {
EXPECT_EQ(session.Control().submittedSeq.load(), static_cast<std::uint64_t>(kRecords));
// The whole point: the two sides' sequence spaces are identical after ten wraps' worth of
// fillers. A side that counted a kRecPad would land here off by the number of wraps.
EXPECT_EQ(session.Control().appliedSeq.load(), static_cast<std::uint64_t>(kRecords));
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), static_cast<std::uint64_t>(kRecords));
EXPECT_EQ(session.consumer.AppliedSeq(), static_cast<std::uint64_t>(kRecords));
EXPECT_TRUE(RingCursorsValid(session.Control(), RingCursorSet::Cmd,
session.serverSegments.CmdRingCapacity()));
@@ -440,7 +440,7 @@ TEST(SessionTest, SubmittedSeqIsThePublishersAndIsPurelyDiagnostic) {
EXPECT_EQ(session.Control().submittedSeq.load(), seq);
// It says nothing about what has been APPLIED, which is the distinction a waiter that
// picked the wrong watermark would lose.
EXPECT_EQ(session.Control().appliedSeq.load(), 0u);
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), 0u);
}
}
@@ -462,7 +462,7 @@ TEST(SessionTest, AppliedSeqAdvancesExactlyOncePerRecordAndIsNeverBatched) {
std::uint64_t applied = 0;
while (session.consumer.ApplyOne([&](const RingRecordView&) { ++applied; })) {
EXPECT_EQ(session.Control().appliedSeq.load(), applied)
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), applied)
<< "appliedSeq did not move with the record; a barrier waiter would be blocked on "
"work that already ran";
EXPECT_EQ(session.consumer.AppliedSeq(), applied);
@@ -483,14 +483,14 @@ TEST(SessionTest, RetiredSeqMayTrailTheApplyButCanNeverOvertakeIt) {
session.producer.PublishAndNotify(3);
while (session.consumer.ApplyOne([](const RingRecordView&) {})) {
}
ASSERT_EQ(session.Control().appliedSeq.load(), 3u);
ASSERT_EQ(session.Control().Progress.appliedSeq.load(), 3u);
// Trailing is legal and is what "late" means.
Watermark::AdvanceRetired(session.Control(), 1);
EXPECT_EQ(session.Control().retiredSeq.load(), 1u);
EXPECT_EQ(session.Control().Progress.retiredSeq.load(), 1u);
// Running ahead is not: clamped to what has actually been applied.
Watermark::AdvanceRetired(session.Control(), 99);
EXPECT_EQ(session.Control().retiredSeq.load(), 3u);
EXPECT_EQ(session.Control().Progress.retiredSeq.load(), 3u);
// Going BACKWARDS is Fatal, not clamped - see AWatermarkThatMovesBackwardsIsFatal below.
}
@@ -507,16 +507,16 @@ TEST(SessionTest, CompletedFrameSerialIsTheServersAndIsIndependentOfAppliedSeq)
session.producer.PublishAndNotify(5);
while (session.consumer.ApplyOne([](const RingRecordView&) {})) {
}
EXPECT_EQ(session.Control().appliedSeq.load(), 5u);
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), 5u);
// Five records applied, no frame completed: the two are not the same number and nothing
// may derive one from the other.
EXPECT_EQ(session.Control().completedFrameSerial.load(), 0u);
EXPECT_EQ(session.Control().Progress.completedFrameSerial.load(), 0u);
Watermark::AdvanceCompletedFrame(session.Control(), 2);
EXPECT_EQ(session.Control().completedFrameSerial.load(), 2u);
EXPECT_EQ(session.Control().Progress.completedFrameSerial.load(), 2u);
// Republishing the SAME serial is legal and is what a lazy publisher does.
Watermark::AdvanceCompletedFrame(session.Control(), 2);
EXPECT_EQ(session.Control().completedFrameSerial.load(), 2u);
EXPECT_EQ(session.Control().Progress.completedFrameSerial.load(), 2u);
}
// presentAckSerial: the only back-pressure that bounds LATENCY rather than bytes. A client
@@ -546,7 +546,7 @@ TEST(SessionTest, PresentAckSerialIsWaitedOnWithGreaterOrEqualAndWakesThroughThe
throttled.join();
EXPECT_TRUE(released.load());
EXPECT_EQ(result.load(), SessionWait::Reached);
EXPECT_EQ(session->Control().presentAckSerial.load(), 7u);
EXPECT_EQ(session->Control().Progress.presentAckSerial.load(), 7u);
EXPECT_EQ(session->Control().producerParked.load(), 0u);
}
@@ -587,7 +587,7 @@ TEST(SessionTest, AFullEventRingWakesAClientParkedOnAppliedSeq) {
// AND THE WATERMARK IS UNTOUCHED, which is what makes the caller's re-read the right way
// to tell the two wakeups apart: a third SessionWait value would have turned every
// existing `== Reached` site into a bug.
EXPECT_EQ(session->Control().appliedSeq.load(), 0u);
EXPECT_EQ(session->Control().Progress.appliedSeq.load(), 0u);
EXPECT_TRUE(session->producer.EventRingIsFull());
}
@@ -613,7 +613,7 @@ TEST(SessionTest, AFullEventRingWakesAClientParkedOnThePresentCredit) {
parked.join();
EXPECT_TRUE(released.load());
EXPECT_EQ(result.load(), SessionWait::Reached);
EXPECT_EQ(session->Control().presentAckSerial.load(), 0u);
EXPECT_EQ(session->Control().Progress.presentAckSerial.load(), 0u);
}
// THE SECOND HALF: the drain that empties the ring must RING, not merely clear. A cleared flag
@@ -727,7 +727,7 @@ TEST(SessionTest, AWrapFillerDoesNotAdvanceTheSessionsAppliedSeq) {
EXPECT_EQ(applied, emitted);
// The session's watermark - the number the barrier's waiter and every reply read use - has
// to be the record count, with the fillers' bytes invisible to it.
EXPECT_EQ(session.Control().appliedSeq.load(), emitted);
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), emitted);
}
// ---------------------------------------------------------------------------
@@ -1114,7 +1114,7 @@ TEST(SessionTestDeath, AWatermarkThatMovesBackwardsIsFatalRatherThanIgnored) {
alignas(4096) RingControl control{};
InitRingControl(control);
Watermark::AdvanceApplied(control, 10);
ASSERT_EQ(control.appliedSeq.load(), 10u);
ASSERT_EQ(control.Progress.appliedSeq.load(), 10u);
EXPECT_DEATH(Watermark::AdvanceApplied(control, 9),
"Fatal\\{ProtocolCorruption, \"watermark\"\\} appliedSeq moved backwards, 10 -> 9");
}
@@ -1143,16 +1143,16 @@ TEST(SessionTest, TheInprocPeerGetsItsOwnMappingOfTheSameSharedMemory) {
// visible through the other, exactly as it is across two processes under spawn.
EXPECT_EQ(peer.AnnouncedSize(SessionSegmentSlot::Cmd),
owner.AnnouncedSize(SessionSegmentSlot::Cmd));
owner.CmdControl()->appliedSeq.store(4242, std::memory_order_release);
EXPECT_EQ(peer.CmdControl()->appliedSeq.load(std::memory_order_acquire), 4242u);
peer.CmdControl()->presentAckSerial.store(77, std::memory_order_release);
EXPECT_EQ(owner.CmdControl()->presentAckSerial.load(std::memory_order_acquire), 77u);
owner.CmdControl()->Progress.appliedSeq.store(4242, std::memory_order_release);
EXPECT_EQ(peer.CmdControl()->Progress.appliedSeq.load(std::memory_order_acquire), 4242u);
peer.CmdControl()->Progress.presentAckSerial.store(77, std::memory_order_release);
EXPECT_EQ(owner.CmdControl()->Progress.presentAckSerial.load(std::memory_order_acquire), 77u);
peer.Close();
// The owner is untouched by the peer's teardown - there is no shared ownership left whose
// Close order has to be got right by hand.
EXPECT_TRUE(owner.Valid());
EXPECT_EQ(owner.CmdControl()->appliedSeq.load(), 4242u);
EXPECT_EQ(owner.CmdControl()->Progress.appliedSeq.load(), 4242u);
owner.Close();
}
@@ -1189,7 +1189,7 @@ TEST(SessionTest, ABorrowedSlotIsNotHandedBackUntilItIsReleased) {
ASSERT_EQ(seen, 3);
ASSERT_TRUE(sawBorrow) << "the producer dropped kRecBorrowSlot, so this case proved nothing";
EXPECT_EQ(session.Control().appliedSeq.load(), 3u);
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), 3u);
session.consumer.RetireThrough(session.consumer.AppliedSeq());
// The reclaim point stops AT the borrowed record: only the first record's bytes came back.
@@ -1378,7 +1378,7 @@ TEST(SessionTest, TheStageCursorTripleStaysDeadAcrossAWholeSession) {
EXPECT_EQ(session.Control().stageRetiredTail.load(), 0u);
// retiredSeq is the watermark w1's allocator reclaims behind, and it is a SEQUENCE - not one
// of the three byte cursors above.
EXPECT_GT(session.Control().retiredSeq.load(), 0u);
EXPECT_GT(session.Control().Progress.retiredSeq.load(), 0u);
}
// The kVarTail/kRecPad collision, made harmless. Those two are bit 2 of two different flag spaces,
@@ -1432,7 +1432,7 @@ TEST(SessionTest, ARecordWearingThePadBitIsDeliveredRatherThanEatenAsAFiller) {
EXPECT_EQ(seenKind, 7);
EXPECT_NE(seenFlags & kRecPad, 0u)
<< "the bit arrives intact: the kind check narrows the SKIP, it does not scrub the bit";
EXPECT_EQ(session.Control().appliedSeq.load(), 1u);
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), 1u);
// The opposite control, so that "delivered" cannot be satisfied by not skipping anything:
// a header wearing kRecPad whose kind IS kRingPadRecordKind is a genuine wrap filler, still
@@ -1448,7 +1448,7 @@ TEST(SessionTest, ARecordWearingThePadBitIsDeliveredRatherThanEatenAsAFiller) {
}
EXPECT_EQ(seen, 1) << "a genuine filler was delivered as a record: Pop's skip was removed, "
"not narrowed";
EXPECT_EQ(session.Control().appliedSeq.load(), 1u) << "a filler advanced appliedSeq (R-9)";
EXPECT_EQ(session.Control().Progress.appliedSeq.load(), 1u) << "a filler advanced appliedSeq (R-9)";
}
// The kHostSpan/kRecBorrowSlot collision, made loud. P5 implements no borrowed slots and is ruled
@@ -0,0 +1,390 @@
// MobileGL - MobileGL/MG_Test/Wire/SocketTransportTest.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// The SAME nine ITransport-contract cases InProcessTransportTest runs, driven
// over a real socketpair() with real threads. Package `so`.
//
// THIS FILE IS THE PACKAGE'S WHOLE POINT. CONTRACT-P6.md §8 and the spawn plan
// both require SocketTransport green over a plain socketpair BEFORE a second
// process exists, for the reason SessionRings.h gives about the attach half:
// a transport first exercised on the day the child appears is a transport
// whose bugs all arrive at once, on the hardest day to debug them.
//
// WHY THE BODIES ARE COPIED RATHER THAN SHARED. The two suites assert the same
// contract but not through the same handle: InProcessTransport hands out
// condvar doorbells its tests reach into, SocketTransport does not have them
// (the spawn design pairs it with SocketDoorbell, which FdPassingTest already
// covers). Folding both into one parameterised fixture would rename the
// sixteen existing cases, and G14 says test names only ever grow. Nine new
// names, zero removed.
//
// The seven Doorbell* cases in InProcessTransportTest are deliberately NOT
// here: they exercise CondVarDoorbell through a transport that happens to own
// one, not ITransport. SocketDoorbell's equivalents live in FdPassingTest.
//
// WHAT A SOCKET MAKES REAL THAT A MESSAGE QUEUE DID NOT. InProcessTransport
// hands the peer whole messages by construction; a stream hands you arbitrary
// fragments, so every one of these cases now also exercises Framing.h's
// reassembler - which is why `PreservesOrder` sends 64 messages without
// reading, forcing coalescing in the socket buffer, and why
// `BufferTooSmallKeepsTheMessage` matters more here: the message it must keep
// is one this side already reassembled out of bytes nobody else can re-deliver.
#include <MG_Remote/Transport/Doorbell.h> // kWaitForever
#include <MG_Remote/Transport/FdPassing.h>
#include <MG_Remote/Transport/SocketTransport.h>
#include <gtest/gtest.h>
#include <atomic>
#include <chrono>
#include <cstring>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#if !defined(_WIN32)
#include <sys/socket.h>
#include <unistd.h>
#endif
using namespace MobileGL::MG_Remote::Transport;
#if !defined(_WIN32)
namespace {
MobileGLByteSpan Span(const std::string& text) {
return MobileGLByteSpan{text.data(), text.size()};
}
std::string Receive(ITransport& transport, std::uint32_t timeoutMs = 1000) {
std::vector<std::uint8_t> buffer(4096);
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
const MobileGLResult result = transport.ReceiveFrame(span, &size, timeoutMs);
if (result != MOBILEGL_OK) {
return std::string("<result=") + std::to_string(static_cast<int>(result)) + ">";
}
return std::string(reinterpret_cast<const char*>(buffer.data()),
static_cast<std::size_t>(size));
}
struct Pair {
std::unique_ptr<SocketTransport> client;
std::unique_ptr<SocketTransport> server;
};
Pair MakePair() {
Pair pair;
const MobileGLResult result = SocketTransport::CreatePair(pair.client, pair.server);
EXPECT_EQ(result, MOBILEGL_OK);
return pair;
}
} // namespace
TEST(SocketTransportTest, CarriesFramesInBothDirections) {
Pair pair = MakePair();
ASSERT_TRUE(pair.client && pair.server);
EXPECT_EQ(pair.client->Role(), TransportRole::Client);
EXPECT_EQ(pair.server->Role(), TransportRole::Server);
const std::string hello = "Hello{abiMajor=1}";
const std::string welcome = "Welcome{serverPid=42}";
ASSERT_EQ(pair.client->SendFrame(Span(hello)), MOBILEGL_OK);
// PeekFrameSize pumps, so it is allowed to need the bytes to have arrived;
// on a socketpair a completed send is already in the peer's buffer.
EXPECT_EQ(pair.server->PeekFrameSize(), hello.size());
// A message goes to the PEER, never back to the sender.
EXPECT_EQ(pair.client->PeekFrameSize(), 0u);
EXPECT_EQ(Receive(*pair.server), hello);
ASSERT_EQ(pair.server->SendFrame(Span(welcome)), MOBILEGL_OK);
EXPECT_EQ(Receive(*pair.client), welcome);
}
TEST(SocketTransportTest, PreservesOrder) {
Pair pair = MakePair();
// 64 unread messages coalesce in the socket buffer, so the reassembler has
// to find every boundary itself. That is the case InProcessTransport could
// not have: its queue kept the boundaries for it.
for (int i = 0; i < 64; ++i) {
const std::string message = "msg-" + std::to_string(i);
ASSERT_EQ(pair.client->SendFrame(Span(message)), MOBILEGL_OK);
}
for (int i = 0; i < 64; ++i) {
EXPECT_EQ(Receive(*pair.server), "msg-" + std::to_string(i));
}
}
TEST(SocketTransportTest, BufferTooSmallKeepsTheMessage) {
Pair pair = MakePair();
const std::string message(300, 'x');
ASSERT_EQ(pair.client->SendFrame(Span(message)), MOBILEGL_OK);
std::vector<std::uint8_t> small(16);
std::uint64_t required = 0;
MobileGLMutableByteSpan smallSpan{small.data(), small.size()};
// Zero timeout: the bytes may still be in flight, so give the reassembler a
// real chance first. PeekFrameSize is the documented way to do that.
while (pair.server->PeekFrameSize() == 0) {
std::this_thread::yield();
}
EXPECT_EQ(pair.server->ReceiveFrame(smallSpan, &required, 0), MOBILEGL_ERR_BUFFER_TOO_SMALL);
EXPECT_EQ(required, message.size());
// Still there. On a stream this is the load-bearing half: the bytes have
// already been consumed from the socket, so if the reassembler dropped the
// message nothing could re-deliver it and the stream would be wedged.
EXPECT_EQ(pair.server->PeekFrameSize(), message.size());
EXPECT_EQ(Receive(*pair.server), message);
}
TEST(SocketTransportTest, PollAndTimeoutDoNotBlockForever) {
Pair pair = MakePair();
std::vector<std::uint8_t> buffer(64);
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
EXPECT_EQ(pair.server->ReceiveFrame(span, &size, 0), MOBILEGL_ERR_TIMEOUT);
const auto start = std::chrono::steady_clock::now();
EXPECT_EQ(pair.server->ReceiveFrame(span, &size, 30), MOBILEGL_ERR_TIMEOUT);
EXPECT_GE(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start)
.count(),
20);
}
TEST(SocketTransportTest, ShutdownDrainsBeforeItCloses) {
Pair pair = MakePair();
const std::string last = "Fatal{code=DeviceLost}";
ASSERT_EQ(pair.client->SendFrame(Span(last)), MOBILEGL_OK);
pair.client->Shutdown();
// A peer that shuts down right after sending must not lose its last
// message - that is usually the one that says why it is going away. On a
// socket the bytes are already in the peer's receive buffer when close()
// runs, and the peer must reassemble them before it reports EOF.
EXPECT_EQ(Receive(*pair.server), last);
std::vector<std::uint8_t> buffer(64);
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
EXPECT_EQ(pair.server->ReceiveFrame(span, &size, 100), MOBILEGL_ERR_TRANSPORT_CLOSED);
EXPECT_EQ(pair.server->SendFrame(Span(last)), MOBILEGL_ERR_TRANSPORT_CLOSED);
}
TEST(SocketTransportTest, BlockedReceiverWakesOnSendAndOnShutdown) {
Pair pair = MakePair();
std::atomic<bool> got{false};
std::thread reader([&] { got.store(Receive(*pair.server, kWaitForever) == "wake"); });
std::this_thread::sleep_for(std::chrono::milliseconds(20));
ASSERT_EQ(pair.client->SendFrame(Span(std::string("wake"))), MOBILEGL_OK);
reader.join();
EXPECT_TRUE(got.load());
std::thread closer([&] {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
pair.client->Shutdown();
});
std::vector<std::uint8_t> buffer(64);
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
// The wake is a real POLLHUP here, not a condvar notify: this is the
// mechanism Doorbell.h:390-398 chose a stream socket for, and the reason
// death is an event rather than a hang.
EXPECT_EQ(pair.server->ReceiveFrame(span, &size, kWaitForever), MOBILEGL_ERR_TRANSPORT_CLOSED);
closer.join();
}
TEST(SocketTransportTest, RefusesAPayloadOverTheFrameCap) {
Pair pair = MakePair();
// Not allocated: the cap is checked before the bytes are touched, and it is
// the SAME cap InProcessTransport enforces, so nothing passes CI on inproc
// and then fails after the switch to spawn.
const std::uint8_t dummy = 0;
MobileGLByteSpan huge{&dummy, 64ull * 1024 * 1024 + 1};
EXPECT_EQ(pair.client->SendFrame(huge), MOBILEGL_ERR_INVALID_ARGUMENT);
}
TEST(SocketTransportTest, HandsOverADescriptorAndItsSideband) {
Pair pair = MakePair();
int pipeFds[2] = {-1, -1};
ASSERT_EQ(::pipe(pipeFds), 0);
const std::string sideband = "SegmentRef{id=1,kind=Cmd}";
ASSERT_EQ(pair.client->ShareFd(pipeFds[0], Span(sideband)), MOBILEGL_OK);
// A short sideband buffer is refused before anything is consumed, so the
// descriptor is never dropped. This is the real SCM_RIGHTS path, not an
// in-process hand-off: the fd the peer gets is renumbered by the kernel.
std::vector<std::uint8_t> small(8);
int fd = -1;
std::uint64_t required = 0;
MobileGLMutableByteSpan smallSpan{small.data(), small.size()};
EXPECT_EQ(pair.server->ReceiveFd(&fd, smallSpan, &required, 0), MOBILEGL_ERR_BUFFER_TOO_SMALL);
EXPECT_EQ(required, FdPassing::kMaxSidebandBytes);
EXPECT_EQ(fd, -1);
std::vector<std::uint8_t> big(FdPassing::kMaxSidebandBytes);
std::uint64_t sidebandSize = 0;
MobileGLMutableByteSpan bigSpan{big.data(), big.size()};
ASSERT_EQ(pair.server->ReceiveFd(&fd, bigSpan, &sidebandSize, 100), MOBILEGL_OK);
ASSERT_GE(fd, 0);
EXPECT_EQ(std::string(reinterpret_cast<const char*>(big.data()),
static_cast<std::size_t>(sidebandSize)),
sideband);
// Same open file description, independent descriptor - which is exactly
// what the four segments will ride on in `sm`.
const char payload[] = "bytes";
ASSERT_EQ(::write(pipeFds[1], payload, sizeof(payload)), static_cast<ssize_t>(sizeof(payload)));
char readBack[sizeof(payload)] = {};
ASSERT_EQ(::read(fd, readBack, sizeof(readBack)), static_cast<ssize_t>(sizeof(payload)));
EXPECT_STREQ(readBack, payload);
::close(fd);
::close(pipeFds[0]);
::close(pipeFds[1]);
}
TEST(SocketTransportTest, AFrameWakeupIsNotEatenByAWaiterOnDescriptors) {
Pair pair = MakePair();
// Two readers on the SAME endpoint, blocked on two different predicates.
// The socket transport keeps them on two different descriptors - the stream
// and the aux - so neither can eat the other's wakeup by construction. That
// is a stronger property than the inproc transport's, and asserting it here
// is what would catch a future version that folded them onto one fd.
std::atomic<bool> fdWaiterStarted{false};
std::thread fdWaiter([&] {
std::vector<std::uint8_t> sideband(FdPassing::kMaxSidebandBytes);
MobileGLMutableByteSpan span{sideband.data(), sideband.size()};
int fd = -1;
std::uint64_t size = 0;
fdWaiterStarted.store(true);
// Never offered a descriptor: this one ends on its own deadline. NOT on
// Shutdown, the way the inproc suite's does - closing an fd out from
// under a thread already blocked in poll() does not reliably wake it,
// and a test that depended on that would be asserting a platform
// accident. The deadline is short because all this waiter has to do is
// BE BLOCKED while the frame below arrives.
const MobileGLResult result = pair.client->ReceiveFd(&fd, span, &size, 600);
EXPECT_NE(result, MOBILEGL_OK);
EXPECT_EQ(fd, -1);
});
while (!fdWaiterStarted.load()) {
std::this_thread::yield();
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::atomic<bool> frameWaiterStarted{false};
std::string got;
std::thread frameWaiter([&] {
frameWaiterStarted.store(true);
got = Receive(*pair.client, 4000);
});
while (!frameWaiterStarted.load()) {
std::this_thread::yield();
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
const std::string message = "wake the right waiter";
const auto start = std::chrono::steady_clock::now();
ASSERT_EQ(pair.server->SendFrame(Span(message)), MOBILEGL_OK);
frameWaiter.join();
const auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start)
.count();
EXPECT_EQ(got, message);
// Not "eventually, when the receive timed out and re-checked".
EXPECT_LT(elapsedMs, 2000);
fdWaiter.join();
}
// ---- cases a socket has and a message queue does not ------------------------
TEST(SocketTransportTest, ReassemblesAMessageSplitAcrossReads) {
Pair pair = MakePair();
// 256 KiB is comfortably past a default socketpair buffer, so the sender
// blocks and the payload provably crosses in several reads. If PumpOnce
// returned a partial frame as a whole one, or if it dropped the tail, this
// is where it shows.
const std::string big(256 * 1024, 'q');
std::thread sender([&] { EXPECT_EQ(pair.client->SendFrame(Span(big)), MOBILEGL_OK); });
std::vector<std::uint8_t> buffer(big.size());
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
ASSERT_EQ(pair.server->ReceiveFrame(span, &size, kWaitForever), MOBILEGL_OK);
sender.join();
EXPECT_EQ(size, big.size());
EXPECT_EQ(std::string(reinterpret_cast<const char*>(buffer.data()),
static_cast<std::size_t>(size)),
big);
}
TEST(SocketTransportTest, AGarbageStreamIsLatchedFailedAndNeverRecovers) {
Pair pair = MakePair();
// Write bytes that are not a frame directly onto the peer's stream fd,
// bypassing SendFrame. A corrupt control stream must latch, by name, and
// must not be retry-able past: the alternative is a reader that resyncs
// onto a byte boundary it invented, which is how one bad frame becomes a
// silently misparsed session.
const std::uint8_t garbage[16] = {0xDE, 0xAD, 0xBE, 0xEF, 0, 0, 0, 0,
0xFF, 0xFF, 0xFF, 0xFF, 1, 2, 3, 4};
ASSERT_EQ(::write(pair.client->StreamFd(), garbage, sizeof(garbage)),
static_cast<ssize_t>(sizeof(garbage)));
std::vector<std::uint8_t> buffer(64);
std::uint64_t size = 0;
MobileGLMutableByteSpan span{buffer.data(), buffer.size()};
EXPECT_EQ(pair.server->ReceiveFrame(span, &size, 200), MOBILEGL_ERR_PROTOCOL_MISMATCH);
// Latched: a second call says the same thing rather than resyncing.
EXPECT_EQ(pair.server->ReceiveFrame(span, &size, 200), MOBILEGL_ERR_PROTOCOL_MISMATCH);
EXPECT_EQ(pair.server->PeekFrameSize(), 0u);
}
TEST(SocketTransportTest, AdoptsAnAlreadyConnectedFdAndRefusesFdPassingWithoutAnAux) {
// What `sm` does on each side of the fork: adopt fd 3, and - for a link
// that has no descriptor channel - answer UNSUPPORTED to ShareFd rather
// than pretending. Rule G: a transport declares what it supports.
int fds[2] = {-1, -1};
ASSERT_EQ(::socketpair(AF_UNIX, SOCK_STREAM, 0, fds), 0);
SocketTransport a(fds[0], -1, TransportRole::Client);
SocketTransport b(fds[1], -1, TransportRole::Server);
const std::string message = "Hello{adopted}";
ASSERT_EQ(a.SendFrame(Span(message)), MOBILEGL_OK);
EXPECT_EQ(Receive(b), message);
const std::uint8_t dummy = 0;
EXPECT_EQ(a.ShareFd(1, MobileGLByteSpan{&dummy, 1}), MOBILEGL_ERR_UNSUPPORTED);
int fd = -1;
std::uint64_t size = 0;
std::vector<std::uint8_t> sideband(FdPassing::kMaxSidebandBytes);
MobileGLMutableByteSpan span{sideband.data(), sideband.size()};
EXPECT_EQ(b.ReceiveFd(&fd, span, &size, 0), MOBILEGL_ERR_UNSUPPORTED);
EXPECT_EQ(fd, -1);
}
#endif // !_WIN32
@@ -22,6 +22,7 @@
// staged bytes" a checked fact rather than a design intention.
#include <Config.h>
#include <MG_Util/Debug/Log.h>
#include <MG_Backend/DirectGLES/Managers.h>
#include <MG_Pipe/PipeApply.h>
#include <MG_Remote/Server/StagedTextureStore.h>
@@ -51,9 +52,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
if (!in) return {};
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
unsigned ProcessId() {
@@ -24,6 +24,7 @@
// ServerLoopEglTest fixture, which now drives every forwarder through the frame channel).
#include <MG_Remote/Protocol/SurfaceOpCodec.h>
#include <MG_Util/Debug/Log.h>
#include <MG_Remote/Protocol/generated/protocol_generated.h>
#include <MG_Remote/Server/ServerLoop.h>
#include <MG_Remote/Server/SurfaceControlFrame.h>
@@ -63,9 +64,10 @@ namespace {
std::string g_logPath;
std::string ReadLog() {
std::ifstream in(g_logPath, std::ios::binary);
if (!in) return {};
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
// BOTH ROLES' LOGS (P6). A death test asserts that the CHILD said something; which
// role's thread said it is not what these cases are about, and refusals raised on the
// apply thread are written under the SERVER role by construction.
return MobileGL::MG_Util::Debug::ReadRoleLogs(g_logPath.c_str());
}
unsigned ProcessId() {
@@ -137,8 +139,11 @@ TEST(SurfaceControlFrameTest, ExactlyTheTenFramedOpsHaveWireKindsAndTheValuesAre
EXPECT_EQ(static_cast<unsigned>(::MobileGL::Wire::SurfaceOpKind::SetWindowHandle), 10u);
// The inproc-only kinds refuse the wire by name, both directions.
// InitCapabilities WAS in this list and cp took it out; the eleventh op has a
// test of its own below rather than a line here, because this test's name is
// a statement about ten and G14 does not let a name be traded for another.
const SurfaceControlOp inprocOnly[] = {
SurfaceControlOp::None, SurfaceControlOp::InitCapabilitiesInprocOnly,
SurfaceControlOp::None,
SurfaceControlOp::SwapBuffersInprocOnly, SurfaceControlOp::InitWindowSurfaceInprocOnly,
SurfaceControlOp::ProbeForTesting,
};
@@ -153,6 +158,37 @@ TEST(SurfaceControlFrameTest, ExactlyTheTenFramedOpsHaveWireKindsAndTheValuesAre
<< "a wire kind the schema does not define must not decode into an op";
}
TEST(SurfaceControlFrameTest, TheEleventhFramedOpIsInitCapabilitiesAndItCrossesTheWire) {
// cp. The op above this one in the enum, SetWindowHandle, was fc's last
// append; this is P6's. It gets a test rather than a row in the ten-op table
// because the failure it guards is specific and was REAL: with no wire kind
// the codec answered InprocOnlyOpOnTheWire, BackendObject_Remote's
// InitCapabilities call failed, MakeEGLCurrent reported "InitCapabilities
// failed", and the OpenRA spawn retrace died one call after the server's
// backend had come up green. Nothing about that read as a missing enum row.
::MobileGL::Wire::SurfaceOpKind kind;
ASSERT_TRUE(WireKindForSurfaceControlOp(SurfaceControlOp::InitCapabilities, &kind))
<< "InitCapabilities lost its wire kind; a spawn client cannot ask for caps";
EXPECT_EQ(static_cast<unsigned>(kind), 11u) << "wire ABI: append-only, and 11 is taken";
EXPECT_EQ(static_cast<unsigned>(SurfaceControlOp::InitCapabilities), 11u);
SurfaceControlOp back;
ASSERT_TRUE(SurfaceControlOpForWireKind(kind, &back))
<< "the decode range's upper bound did not move with the append, so the new tag "
"reads as out-of-range - which surfaces as Fatal{ProtocolCorruption}, not as the "
"missing row it is";
EXPECT_EQ(back, SurfaceControlOp::InitCapabilities);
// And it really encodes. WireKindForSurfaceControlOp answering yes is not the
// same fact as the encoder accepting the frame: the refusal the client hit
// came out of EncodeSurfaceOpFrame.
flatbuffers::FlatBufferBuilder builder(256);
SurfaceControlFrame frame;
frame.kind = SurfaceControlOp::InitCapabilities;
frame.seq = 7;
EXPECT_EQ(EncodeSurfaceOpFrame(frame, &builder), SurfaceWireError::None);
}
TEST(SurfaceControlFrameTest, WindowBackendAndWireWindowKindMapExplicitlyBothWays) {
using MG_Backend::WindowBackend;
const struct {
@@ -269,8 +305,6 @@ TEST(SurfaceControlFrameTest, MalformedAndInprocOnlyFramesRefuseToEncode) {
EXPECT_EQ(EncodeSurfaceOpFrame(frame, &builder), SurfaceWireError::InprocOnlyOpOnTheWire);
frame.kind = SurfaceControlOp::SwapBuffersInprocOnly;
EXPECT_EQ(EncodeSurfaceOpFrame(frame, &builder), SurfaceWireError::InprocOnlyOpOnTheWire);
frame.kind = SurfaceControlOp::InitCapabilitiesInprocOnly;
EXPECT_EQ(EncodeSurfaceOpFrame(frame, &builder), SurfaceWireError::InprocOnlyOpOnTheWire);
frame.kind = SurfaceControlOp::InitWindowSurfaceInprocOnly;
EXPECT_EQ(EncodeSurfaceOpFrame(frame, &builder), SurfaceWireError::InprocOnlyOpOnTheWire);
+147 -10
View File
@@ -8,10 +8,105 @@
#include "../../Includes.h"
#include <cstring> // std::strcmp, for the spawned-server role check in InitFile
namespace MobileGL {
namespace MG_Util::Debug {
static FILE* s_logFile = nullptr;
#if MOBILEGL_BUILD_DISAGGREGATED
// The server role's own sink. Opened lazily, on the first line a server-role thread
// writes, so a process that never plays the role never creates the file.
static FILE* s_serverLogFile = nullptr;
// THE PROCESS DEFAULT, read once. A spawned server image is the server on every thread -
// there is no other role in it - and MOBILEGL_IPC_ROLE is set by the launcher before
// exec, so this is answerable before any MobileGL code runs. Under inproc it is false
// and the apply thread opts in per-thread.
static bool ProcessIsSpawnedServer() {
static const bool value = [] {
const char* role = std::getenv("MOBILEGL_IPC_ROLE");
return role != nullptr && std::strcmp(role, "server") == 0;
}();
return value;
}
// Per THREAD, not per process: under inproc the server role is the mgl-srv-apply thread
// and the GL thread is the client, in one address space. -1 means "not asked yet", which
// is resolved from the process default on first use.
static thread_local int t_logRole = -1;
static bool ThreadIsServerRole() {
if (t_logRole < 0) {
t_logRole = ProcessIsSpawnedServer() ? 1 : 0;
}
return t_logRole == 1;
}
void SetThreadLogRole(LogRole role) { t_logRole = role == LogRole::Server ? 1 : 0; }
std::string ReadRoleLogs(const char* basePath) {
std::string all;
for (const LogRole role : {LogRole::Client, LogRole::Server}) {
const std::string path = RoleLogPath(basePath, role);
if (FILE* file = std::fopen(path.c_str(), "rb")) {
char chunk[4096];
std::size_t got = 0;
while ((got = std::fread(chunk, 1, sizeof(chunk), file)) > 0) {
all.append(chunk, got);
}
std::fclose(file);
}
}
return all;
}
void TruncateRoleLogs(const char* basePath) {
// BOTH, because a reader that concatenates them would otherwise fold a previous
// run's server lines into this one's - which is the stale-tail failure R-16 was
// written after, one file over.
for (const LogRole role : {LogRole::Client, LogRole::Server}) {
if (FILE* file = std::fopen(RoleLogPath(basePath, role).c_str(), "w")) {
std::fclose(file);
}
}
}
// MOBILEGL_LOG_FILE_PATH IS A BASE NAME NOW, AND NEITHER ROLE KEEPS IT.
//
// `foo.log` becomes `foo.client.log` and `foo.server.log`; a path with no extension gets
// the suffix appended. The suffix goes BEFORE the extension so the pair sorts together
// and a `*.log` glob still finds both.
//
// THE CLIENT IS RENAMED TOO, ON PURPOSE. Leaving it at the unsuffixed path would have
// been the compatible choice and the wrong one: every reader that was not updated would
// go on finding a file, go on passing, and go on seeing only half the session - and a
// refusal census that reports a confident zero for the half it cannot see is worse than
// one that fails. With both names moved, an un-updated reader gets ENOENT and says so.
// There were fourteen such readers in this tree when the split landed.
std::string RoleLogPath(const char* basePath, LogRole role) {
const char* roleSuffix = role == LogRole::Server ? "server" : "client";
std::string path(basePath);
const std::string::size_type slash = path.find_last_of("/\\");
const std::string::size_type dot = path.find_last_of('.');
if (dot == std::string::npos || (slash != std::string::npos && dot < slash)) {
return path + "." + roleSuffix;
}
return path.substr(0, dot) + "." + roleSuffix + path.substr(dot);
}
// P6 gate 8: the role, in the two forms a caller can hold it in. Both are thin readers of
// state this file already keeps; neither adds a second source of truth.
LogRole CurrentThreadRole() {
if (t_logRole < 0) {
t_logRole = ProcessIsSpawnedServer() ? 1 : 0;
}
return t_logRole == 1 ? LogRole::Server : LogRole::Client;
}
bool CurrentProcessIsSpawnedServer() { return ProcessIsSpawnedServer(); }
#endif
std::mutex& LogMutex() {
static auto* mutex = new std::mutex();
return *mutex;
@@ -62,27 +157,63 @@ namespace MobileGL {
void InitFile() {
#if MOBILEGL_LOG_ENABLE_FILE
if (!s_logFile) {
// MOBILEGL_LOG_FILE_PATH must stay a raw getenv (not MG_Config::Features):
// InitFile() runs before MG_ConfigLoader::Init() in MobileGL::Initialize().
const char* logPath = std::getenv("MOBILEGL_LOG_FILE_PATH");
if (!logPath || !*logPath) {
logPath = MOBILEGL_LOG_FILE_PATH;
}
if (logPath && *logPath) {
s_logFile = std::fopen(logPath, "w");
}
// MOBILEGL_LOG_FILE_PATH must stay a raw getenv (not MG_Config::Features):
// InitFile() runs before MG_ConfigLoader::Init() in MobileGL::Initialize().
const char* logPath = std::getenv("MOBILEGL_LOG_FILE_PATH");
if (!logPath || !*logPath) {
logPath = MOBILEGL_LOG_FILE_PATH;
}
if (!logPath || !*logPath) {
return;
}
#if MOBILEGL_BUILD_DISAGGREGATED
// ONE FILE PER ROLE, OPENED LAZILY BY WHOEVER FIRST WRITES ONE.
//
// Each role truncates ITS OWN file exactly once, which is what the previous
// single-file design could not do: there the client truncated and the server was
// forbidden to, because a truncate from the far side would have deleted the very
// startup lines a failed session needs. With separate files that asymmetry is gone -
// nobody else writes the file being truncated.
//
// "w" IS SAFE AGAIN HERE, and the O_APPEND this replaces was never about ordering:
// it was about two PROCESSES holding two handles to one path at two offsets, each
// overwriting the other's bytes. Two paths, two writers, no sharing.
if (ThreadIsServerRole()) {
if (!s_serverLogFile) {
s_serverLogFile = std::fopen(RoleLogPath(logPath, LogRole::Server).c_str(), "w");
}
return;
}
if (!s_logFile) {
s_logFile = std::fopen(RoleLogPath(logPath, LogRole::Client).c_str(), "w");
}
#else
if (!s_logFile) {
s_logFile = std::fopen(logPath, "w");
}
#endif
#endif
}
void WriteToFile(const char* msg) {
#if MOBILEGL_LOG_ENABLE_FILE
#if MOBILEGL_BUILD_DISAGGREGATED
// The sink is chosen by the CALLING THREAD's role, which is the only choice that is
// correct under inproc: there both roles are threads of one process, so anything
// process-scoped would file the apply thread's lines under the client.
FILE** sink = ThreadIsServerRole() ? &s_serverLogFile : &s_logFile;
if (!*sink) InitFile();
if (*sink) {
std::fputs(msg, *sink);
std::fflush(*sink);
}
#else
if (!s_logFile) InitFile();
if (s_logFile) {
std::fputs(msg, s_logFile);
std::fflush(s_logFile);
}
#endif
#endif
}
@@ -131,6 +262,12 @@ namespace MobileGL {
void Close() {
#if MOBILEGL_LOG_ENABLE_FILE
#if MOBILEGL_BUILD_DISAGGREGATED
if (s_serverLogFile) {
std::fclose(s_serverLogFile);
s_serverLogFile = nullptr;
}
#endif
if (s_logFile) {
std::fclose(s_logFile);
s_logFile = nullptr;
+112
View File
@@ -122,6 +122,9 @@
{}
#endif
#include <cstdio>
#include <string>
namespace MobileGL {
namespace MG_Util {
namespace Debug {
@@ -131,6 +134,115 @@ namespace MobileGL {
constexpr char* GetOSName();
std::string GetThreadName();
void Close();
#if MOBILEGL_BUILD_DISAGGREGATED
// P6: ONE LOG PER ROLE, and the role is a per-THREAD fact because under inproc both
// roles live in one process. The client keeps MOBILEGL_LOG_FILE_PATH unchanged so
// every existing reader keeps its path; the server's lines go to the same path with
// `.server` inserted before the extension.
//
// WHY NOT ONE SHARED FILE. It worked - O_APPEND made the spawn case correct - but it
// put two sessions' lines in one place and made every per-side assertion a search
// rather than a read. The `--require-spawn` gate had to accept "ANY Config: IPC line
// matches" because the server's own line is scrubbed of the client's knobs by
// construction; with the two separated it can demand that THE client's line matches.
//
// THREAD-SCOPED, NOT PROCESS-SCOPED, for the case that is easy to miss: under inproc
// the server role is the mgl-srv-apply THREAD, so a process-wide flag would file its
// lines under whichever role set it last.
enum class LogRole { Client, Server };
// Called by the apply thread when it starts (inproc), and once by ServerMain for a
// whole spawned server process. Without it a thread defaults to the process role,
// which MOBILEGL_IPC_ROLE=server sets for the spawned image.
void SetThreadLogRole(LogRole role);
// THE NAMING RULE, EXPORTED, so that no reader has to reimplement it. Every consumer
// of a lane's log - the unit mains, the integration harness, the retrace runner -
// needs the same `<stem>.<role><ext>` derivation, and a second copy is a copy that
// can fall behind: the one that does opens a file that does not exist and reports
// "the library never logged", which reads as a product failure.
std::string RoleLogPath(const char* basePath, LogRole role);
// WHICH ROLE IS THE CALLING THREAD, exported for the same reason the naming rule is:
// a second answer to "am I the server" is a second answer that can disagree, and this
// one already exists twice inside this file (ThreadIsServerRole, ProcessIsSpawnedServer)
// in a form nothing outside can read.
//
// P6 GATE 8 NEEDS IT, and that is the caller that made it worth exporting. The MGPipe
// counters' JSON dump is written by whichever role reaches PipeStats::Shutdown(), and
// under `spawn` both roles do - in two processes, onto the same configured path. The
// fix is the log sink's own split (each role gets its own file), and the role is the
// only input that split needs.
LogRole CurrentThreadRole();
// The same question about a whole PROCESS rather than a thread: true only for a
// spawned server image, which is the server on every thread. Exported because the
// distinction matters to callers that are deciding a FILE NAME before any role has
// been stamped on a thread. `bool` rather than `Bool`: this header is included from
// translation units that do not pull MobileGL/Defines.h (Log.cpp is one of them).
bool CurrentProcessIsSpawnedServer();
// THE TWO OPERATIONS EVERY READER ACTUALLY WANTS, so that no caller has to know how
// many roles there are or how they are spelled.
//
// A test asserts that THE RUN said something; which role's thread said it is not
// what the assertion is about, and guessing wrong turns a real diagnostic into "the
// child aborted and said nothing". Refusals raised on the apply thread are written
// under the SERVER role by construction, which is exactly the class of diagnostic
// these readers exist to check.
std::string ReadRoleLogs(const char* basePath);
void TruncateRoleLogs(const char* basePath);
#else
// THE SAME VOCABULARY IN THE PULL BUILD, where there is exactly one log because there
// is exactly one role. A reader that asks for "what this run logged" has to compile
// and mean the right thing in BOTH flavours; the alternative is an `#if` at every
// call site, and the call site that forgets one is the one that silently reads
// nothing. (It was not hypothetical: PipeInputsTest built only in the verify flavour
// and took the whole `build-linux-verify` job down with it.)
//
// HEADER-ONLY ON PURPOSE, FOR G1. The pull library's symbol set and `.text` must stay
// byte-identical to the baseline, so these may not become library symbols. Nothing
// inside the library calls them - only tests and harnesses do - so an inline
// definition emits code into those readers and nothing at all into libMobileGL.so.
enum class LogRole { Client, Server };
// No roles to separate, so nothing to record. Present so that a harness may say which
// role a thread is without asking which build it is in.
inline void SetThreadLogRole(LogRole) {}
// One role, one file: the pull build writes MOBILEGL_LOG_FILE_PATH unchanged.
inline std::string RoleLogPath(const char* basePath, LogRole) {
return basePath == nullptr ? std::string() : std::string(basePath);
}
// INLINE, like everything else in this pull arm, and for the same G1 reason. There is
// one role in this build, so "which role is this thread" has exactly one true answer
// and no state to read - but a caller must still compile and mean the right thing in
// both flavours rather than wrapping these in an `#if` it might get wrong once.
inline LogRole CurrentThreadRole() { return LogRole::Client; }
inline bool CurrentProcessIsSpawnedServer() { return false; }
inline std::string ReadRoleLogs(const char* basePath) {
std::string all;
if (basePath == nullptr) return all;
if (FILE* file = std::fopen(basePath, "rb")) {
char chunk[4096];
std::size_t got = 0;
while ((got = std::fread(chunk, 1, sizeof(chunk), file)) > 0) {
all.append(chunk, got);
}
std::fclose(file);
}
return all;
}
inline void TruncateRoleLogs(const char* basePath) {
if (basePath == nullptr) return;
if (FILE* file = std::fopen(basePath, "w")) {
std::fclose(file);
}
}
#endif
} // namespace Debug
} // namespace MG_Util
} // namespace MobileGL
+158 -4
View File
@@ -9,6 +9,7 @@
#include "PipeStats.h"
#include <Config.h>
#include <MG_Util/Debug/Log.h>
#include <fstream>
@@ -93,10 +94,29 @@
// above. The two are different questions about the same bytes under
// split, and adding them is wrong.
// residual-value-block Placeholder, always 0 until P2 (plan section 6.3).
// stage-segment-bytes P6 gate 8, and the only class in this list that is neither a backend's
// copy nor a client's blob declaration: it counts what the WIRE put into
// SEG_STAGE. One site, PipeWireEncoder::StageAllocate, which is the single
// allocation call behind PipeWireEncoder::StageBytes - so every writer
// (the buffer content walks, the texture slabs, the CSO archives, the
// storage-block names) is covered by construction rather than by being on
// a list. Align8 slack and the allocator's wrap skip are real occupancy
// and are deliberately NOT counted; see the ByteClass comment. It is a
// per-frame average by construction, so the per-blob SHAPE - the thing
// that says whether the chunk budget is cutting where it should - is the
// staged-blob histogram in the JSON dump, not this number.
//
// Call classes
// draws DirectGLES PrepareForDraw and DirectVulkan SetupDraw's entry. A
// dispatch is not a draw and is not counted.
// wire-records P6 gate 8: one per record the wire encoder COMMITTED, on
// PipeWireEncoder::EncodeRecord's successful path. Post-chunking by
// construction - an application call whose content is cut at
// MGPipeStageChunkBytes() produces several. A kRecPad ring filler is not a
// record and is not counted; an emission Reserve refused is counted once,
// when the retry succeeds. The emitter-side Client*Emissions counters
// answer a different question and the two together are what show what the
// suppressors absorbed.
// accessor-calls STATIC TALLIES at the instrumented entry points, NOT a wrapper
// around all 293 pGLContext-> sites. Each instrumented function adds
// the number of GLContext accessor calls that its OWN body executed
@@ -144,6 +164,11 @@ namespace MobileGL::MG_Util::PipeStats {
Counter g_totalGateMiss[kGateCount];
Counter g_totalPayloadBuckets[kPayloadHistogramBuckets];
Counter g_frameCount{0};
#if MOBILEGL_PIPE_PUSH
// P6 gate 8's second histogram, and push-only for the same reason its accessor is: its
// only sampler is the wire encoder, which a pull build does not compile.
Counter g_totalStagedBlobBuckets[kStagedBlobHistogramBuckets];
#endif
// Window bases: the run totals as of the previous summary line. Only ever touched
// from OnPresent()/Shutdown() (the present thread), so plain integers.
@@ -201,7 +226,7 @@ namespace MobileGL::MG_Util::PipeStats {
"stage-ubo-named", "stage-vertex-client", "stage-index-client",
"stage-indirect-cmd", "persistent-map-push", "residual-value-block",
#if MOBILEGL_PIPE_PUSH
"cso-blob-bytes",
"cso-blob-bytes", "stage-segment-bytes",
#endif
};
const char* const kCallClassNames[kCallClassCount] = {
@@ -211,7 +236,7 @@ namespace MobileGL::MG_Util::PipeStats {
"render-state-cso-mints", "render-state-cso-binds", "map-persistent-roundtrips",
"framebuffer-emissions", "sampler-view-emissions", "sampler-state-emissions",
"shader-image-emissions", "client-tex-upload-emissions", "tex-remint-pulls",
"residual-pulls", "server-verb-boundaries",
"residual-pulls", "server-verb-boundaries", "wire-records",
#endif
};
const char* const kGateNames[kGateCount] = {
@@ -236,7 +261,7 @@ namespace MobileGL::MG_Util::PipeStats {
const char* const kByteClassShort[kByteClassCount] = {"buf", "tex", "ubog", "ubon", "vtxc",
"idxc", "icmd", "pmap", "resid",
#if MOBILEGL_PIPE_PUSH
"csob-blob",
"csob-blob", "seg",
#endif
};
const char* const kGateShort[kGateCount] = {"ers", "etl", "eub", "mfp", "mpm", "mdt"};
@@ -265,6 +290,11 @@ namespace MobileGL::MG_Util::PipeStats {
}
g_frameCount.store(0, std::memory_order_relaxed);
g_windowBaseFrames = 0;
#if MOBILEGL_PIPE_PUSH
for (Uint32 i = 0; i < kStagedBlobHistogramBuckets; ++i) {
g_totalStagedBlobBuckets[i].store(0, std::memory_order_relaxed);
}
#endif
#if MOBILEGL_PIPE_PUSH
for (Uint32 i = 0; i < kGaugeCount; ++i) {
g_gauges[i].store(0, std::memory_order_relaxed);
@@ -284,13 +314,57 @@ namespace MobileGL::MG_Util::PipeStats {
}
void WriteJsonDump() {
#if MOBILEGL_BUILD_DISAGGREGATED
// ---- THE DUMP PATH IS ROLE-DERIVED, AND THIS BLOCK IS WHY IT IS INSIDE A GUARD ----
//
// Same reason as the log path it mirrors: under `spawn` there are two processes with
// two independent sets of counters, each reaching PipeStats::Shutdown(), and one
// configured path would have the second truncate and overwrite the first. A reader
// would then hold one role's numbers under a name that claims to be the run's, which is
// worse than a missing file because nothing about it looks wrong.
//
// THE BASE NAME RESOLVES TO NO FILE, deliberately. `<base>.client.json` and
// `<base>.server.json` are what exist; opening the bare configured name fails loudly.
// That is the log sink's own design ("with both names moved, an un-updated reader gets
// ENOENT and says so") and it is the right trade here too: a caller that has not been
// updated gets an error it must look at, rather than a file that is silently half a run.
//
// THE RULE IS NOT COPIED. MG_Util/Debug/Log.cpp owns `<stem>.<role><ext>` and exports
// it; a second implementation is a second thing to keep in step, and the one that falls
// behind opens a path nothing writes and reads as "the counters never dumped".
//
// ---- AND G1 IS WHY THE PULL ARM BELOW IS THE ORIGINAL, STATEMENT FOR STATEMENT ----
//
// A monolith build has exactly ONE role, so deriving the path there is a no-op - but
// "a no-op" is not "no bytes", and the gate caught three separate leaks as this was
// written. They are worth recording because none is guessable from the code:
//
// 1. deriving UNCONDITIONALLY put a std::string temporary and a call into the
// monolith body: .text +24 bytes.
// 2. guarding it but keeping ONE shared `String` local in both arms still reds: the
// two arms are different code even when they compute the same value, and
// `Shutdown()` came out one byte different.
// 3. rewriting the two MGLOG_W format strings to name both the base and the derived
// path moved .rodata by 64 bytes, because a literal is a literal in whichever
// branch it sits and .rodata is measured too.
//
// So the rule for this file is stronger than "guard the new code": the OLD code must be
// left alone, character for character, and every addition lives inside the `#if`.
const String path = RoleDerivedJsonDumpPathForTesting();
if (path.empty()) {
return;
}
#else
// The monolith arm, byte for byte as it was. Do not "tidy" this into the arm above.
const String& path = MG_Config::Features.PipeStatsFile;
if (path.empty()) {
return;
}
#endif
std::ofstream out(path, std::ios::out | std::ios::trunc);
if (!out) {
MGLOG_W("PipeStats: could not open MOBILEGL_PIPE_STATS_FILE='%s' for writing", path.c_str());
MGLOG_W("PipeStats: could not open MOBILEGL_PIPE_STATS_FILE='%s' for writing",
path.c_str());
return;
}
out << FormatJson();
@@ -311,10 +385,27 @@ namespace MobileGL::MG_Util::PipeStats {
? kDefaultSummaryFramePeriod
: static_cast<Uint64>(MG_Config::Features.PipeStatsPeriod);
if (g_pipeStatsEnabled) {
#if MOBILEGL_BUILD_DISAGGREGATED
// THE ROLE-DERIVED PATH IS WHAT IS PRINTED, not the base name. An operator reading
// this banner wants to know which file the run will write, and under split the base
// name is not it - printing the base would send them to a path that is deliberately
// never opened (see WriteJsonDump).
//
// THE PULL ARM OF THIS `#if` IS THE ORIGINAL LINE, and the split arm repeats the same
// format literal rather than sharing one, for the reason WriteJsonDump's header spells
// out: a shared literal or a shared temporary is a byte the monolith build gains for a
// branch it can never take. Two copies of one format string in two arms of one `#if` is
// the price G1 charges for adding anything to this file at all.
const String dumpPath = RoleDerivedJsonDumpPathForTesting();
MGLOG_I("MGPipe stats: counters ON (MOBILEGL_PIPE_STATS), summary every %llu frames%s%s",
static_cast<unsigned long long>(g_summaryPeriod),
dumpPath.empty() ? "" : ", JSON dump to ", dumpPath.c_str());
#else
MGLOG_I("MGPipe stats: counters ON (MOBILEGL_PIPE_STATS), summary every %llu frames%s%s",
static_cast<unsigned long long>(g_summaryPeriod),
MG_Config::Features.PipeStatsFile.empty() ? "" : ", JSON dump to ",
MG_Config::Features.PipeStatsFile.c_str());
#endif
}
}
@@ -367,6 +458,15 @@ namespace MobileGL::MG_Util::PipeStats {
void RecordDrawPayloadBytes(Uint64 bytes) { Bump(g_totalPayloadBuckets[PayloadBucketOf(bytes)], 1); }
#if MOBILEGL_PIPE_PUSH
// P6 gate 8's staged-blob distribution. A count, not a sum: the bytes already have a home
// in stage-segment-bytes, and what this exists to answer is the SHAPE (how many blobs there
// were and how big each one was), which a total cannot express.
void RecordStagedBlobBytes(Uint64 bytes) {
Bump(g_totalStagedBlobBuckets[PayloadBucketOf(bytes)], 1);
}
#endif
void OnPresent() {
// Every frame accumulator is EXCHANGED for zero, and the exchanged value is what gets
// plotted. A read followed by a store(0) would lose any Bump that lands in between -
@@ -422,6 +522,11 @@ namespace MobileGL::MG_Util::PipeStats {
Uint64 TotalPayloadBucket(Uint32 bucket) {
return bucket < kPayloadHistogramBuckets ? Read(g_totalPayloadBuckets[bucket]) : 0;
}
#if MOBILEGL_PIPE_PUSH
Uint64 TotalStagedBlobBucket(Uint32 bucket) {
return bucket < kStagedBlobHistogramBuckets ? Read(g_totalStagedBlobBuckets[bucket]) : 0;
}
#endif
Uint64 FrameCount() { return Read(g_frameCount); }
const char* NameOf(ByteClass byteClass) { return kByteClassNames[static_cast<Uint32>(byteClass)]; }
@@ -522,6 +627,24 @@ namespace MobileGL::MG_Util::PipeStats {
// positive control built on it would fail on the day the debt is paid.
line += " vbs=" +
std::to_string(calls[static_cast<Uint32>(CallClass::ServerVerbBoundaries)]);
// P6 GATE 8's SECOND NUMBER (CONTRACT-P6.md §9 item 8): records/frame AFTER chunking, i.e.
// the count of records the wire encoder actually committed this window rather than the
// number of times an emitter was asked for one. The gap between the two is the whole
// point of the counter: once the stage chunk budget landed, one application call can
// produce several records, so `wrec` is what a frame really costs SEG_CMD and the
// emitter-side counts can no longer answer it. It follows the line's ordinary
// per-frame/window rule - the run total when the window held no Present - like every
// field that is not one of the gauges, and the label says which it is.
//
// `wrec/f` AND NOT `wrec` ALONE, so the deliverable reads off the line directly. Both are
// printed because the pair is self-checking: a per-frame figure whose window total is not
// its numerator times the frame count is a formatting bug, and a per-frame figure over a
// window with no Present in it is the 47x overstatement PipeStatsTest already pins.
line += " wrec=" + std::to_string(calls[static_cast<Uint32>(CallClass::WireRecords)]);
line += " wrec/f=" + (perFrame
? FormatFixed2(calls[static_cast<Uint32>(CallClass::WireRecords)],
windowFrames)
: std::to_string(calls[static_cast<Uint32>(CallClass::WireRecords)]));
// P5's three wire gauges, and THEY ARE RUN TOTALS on a line whose every other field is
// a window - see the Gauge enum for the argument. `maxrec` is R-10's proof obligation
// (BRIEF 8 item 3): the largest single record this run wrote, in BYTES, beside the cap
@@ -635,6 +758,23 @@ namespace MobileGL::MG_Util::PipeStats {
}
json += std::to_string(Read(g_totalPayloadBuckets[i]));
}
#if MOBILEGL_PIPE_PUSH
// P6 gate 8's two per-frame numbers have their JSON homes where every other ByteClass and
// CallClass already does - the `bytes` and `calls` blocks above, under their long names
// (stage-segment-bytes, wire-records) - so there is nothing to add for them here. The
// staged-blob DISTRIBUTION does need one: it is the deliverable MEASUREMENTS.md:342 says
// has never been measured, and like the draw-payload histogram above it is a run-total
// distribution, which is exactly what Tracy cannot plot and this dump exists to carry.
// Bucket 0 is "0 bytes" and bucket n>0 is [2^(n-1), 2^n): the same edges PayloadBucketOf
// gives both histograms, so the two are read the same way.
json += "],\n \"staged-blob-bytes-histogram\": [";
for (Uint32 i = 0; i < kStagedBlobHistogramBuckets; ++i) {
if (i != 0) {
json += ", ";
}
json += std::to_string(Read(g_totalStagedBlobBuckets[i]));
}
#endif
json += "]\n}\n";
return json;
}
@@ -643,4 +783,18 @@ namespace MobileGL::MG_Util::PipeStats {
void ResetForTesting() { ResetCounters(); }
#if MOBILEGL_BUILD_DISAGGREGATED
String RoleDerivedJsonDumpPathForTesting() {
// The SAME expression WriteJsonDump and the Init banner use, reached through the same
// helper - so a change that stopped deriving at either site has to change this too, and the
// test reds. That is the whole point: see the header for why asserting on RoleLogPath
// directly was not a control.
if (MG_Config::Features.PipeStatsFile.empty()) {
return String();
}
return MG_Util::Debug::RoleLogPath(MG_Config::Features.PipeStatsFile.c_str(),
MG_Util::Debug::CurrentThreadRole());
}
#endif
} // namespace MobileGL::MG_Util::PipeStats
+94
View File
@@ -87,6 +87,32 @@ namespace MobileGL::MG_Util::PipeStats {
// transport would actually have to move for the CSO families, as opposed to what the
// records themselves cost.
CsoBlobBytes,
// P6 GATE 8's FIRST NUMBER (CONTRACT-P6.md §9 item 8), and the reason it is a ByteClass
// rather than one more Gauge: the deliverable is BYTES PER FRAME, and a byte class IS
// the windowed sum this module already divides by the window's frame count. A gauge is
// a run total deliberately (see the Gauge enum) and windowing one is not a thing this
// module does.
//
// WHAT IT MEASURES, AND WHY IT IS NOT ANY OF THE stage-* CLASSES ABOVE. Those count what
// a BACKEND moves into its own driver, on the apply thread, from bytes the wire already
// delivered. This counts what the WIRE put into SEG_STAGE - the client-side staging
// arena a record's blobs are copied into - and it is read as "staged content per frame".
//
// COUNTED AT THE ALLOCATOR, WHICH IS THE ONE CHOKE POINT. Every writer that puts bytes
// into SEG_STAGE reaches them through PipeWireEncoder::StageBytes and that function's
// only allocation call is StageAllocate (PipeWireCodec.h:376), so a single site here
// covers the buffer content walks, the texture slabs, the CSO archives and the
// storage-block names alike. Summing at the CALLERS instead would be a hand-kept list of
// the paths that happen to exist today, and the next producer added would be missing
// from it with nothing to notice - which is the failure mode the site inventory at the
// top of PipeStats.cpp exists to forbid.
//
// IT IS THE PAYLOAD, NOT THE ARENA OCCUPANCY. Align8 slack and the allocator's wrap skip
// (a run that would straddle the segment's end skips the remainder) are real bytes of
// the segment and are NOT counted: neither is content the producer wrote, and neither
// is what MOBILEGL_IPC_STAGE_MB has to hold for one record. The per-blob distribution
// this average hides is the staged-blob histogram below.
StageSegmentBytes,
#endif
Count
};
@@ -195,6 +221,34 @@ namespace MobileGL::MG_Util::PipeStats {
// would start failing on the day the debt is paid. `vbs` is non-zero whenever the
// server applied a verb at all, before and after retirement alike.
ServerVerbBoundaries,
// P6 GATE 8's SECOND NUMBER (CONTRACT-P6.md §9 item 8): "records/frame post-chunking".
//
// ONE PER RECORD THE WIRE ENCODER ACTUALLY WROTE, which is what makes it the
// post-chunking count rather than a restatement of the emitter's call count. Before the
// stage chunk budget landed, one application call produced one record and the question
// could be answered from the emitter's side; now a call whose content is wider than
// MGPipeStageChunkBytes() produces SEVERAL - the buffer content walks cut themselves at
// the budget and one texture level is emitted as whole-width slabs - and only the
// encoder knows how many. So this is counted where the record is committed
// (PipeWireCodec.cpp's EncodeRecord, on the successful path), not where a caller asked
// for one.
//
// A kRecPad RING FILLER IS NOT A RECORD AND IS NOT COUNTED. Those are the bytes Reserve
// lays down when a record would have straddled the ring's boundary; they carry no
// opcode, both sides skip them, and they are already visible in the gauges as ringpads.
// An emission the ring REFUSED is not counted either: EncodeRecord returns kInvalidSeq
// and the caller publishes and retries, so the record is counted once, when it goes.
//
// Read it against the Client*Emission counters above: a sampler/framebuffer/texture set
// that is resolved and then suppressed does not reach this number, so records-per-frame
// is wire traffic while those are emission calls, and the difference between them is
// exactly what the suppressors absorbed.
//
// NOT SetBytes(), and that is the whole reason it is a CallClass rather than a Gauge: the
// deliverable is records PER FRAME, so it needs the windowed division and the label rule
// that goes with it (FormatWindowLine prints the run total instead when the window holds
// no Present).
WireRecords,
#endif
Count
};
@@ -308,6 +362,30 @@ namespace MobileGL::MG_Util::PipeStats {
// emit records only has to add the one call.
inline constexpr Uint32 kPayloadHistogramBuckets = 24;
#if MOBILEGL_PIPE_PUSH
// Per-STAGED-BLOB size histogram, and it is a SECOND histogram rather than a wider
// kPayloadHistogramBuckets because the two answer different questions about different
// populations: the one above is the command payload of a draw (plan section 4.5.7, sizing
// SEG_CMD), this one is how big the blobs a workload stages into SEG_STAGE actually are.
//
// IT EXISTS FOR CONTRACT-P6.md §9 item 8, and MEASUREMENTS.md:342 says in as many words why:
// the chunking work landed (1e7c372e buffer walks, 9469d48e texture slabs) and every
// `maxrec` number the file carries predates it, so "the per-blob byte distribution after
// chunking" had no measurement at all. A per-frame AVERAGE cannot answer it either: an
// average of 8 MiB is the same number whether one blob of 8 MiB was staged or two of 4 MiB
// that the budget should have cut to one. The bucket edges are PayloadBucketOf's, shared so
// the two distributions are read the same way.
//
// PUSH-ONLY like every counter added since P2: its only sampler is the wire encoder, which a
// pull build does not compile, so the array, the reset, the JSON row and the accessor would
// all exist there for a population that could never be sampled (gate G1).
inline constexpr Uint32 kStagedBlobHistogramBuckets = kPayloadHistogramBuckets;
Uint64 TotalStagedBlobBucket(Uint32 bucket);
// Sample one staged blob. Called by the wire encoder where a blob is staged, behind the
// usual Enabled() predicate.
void RecordStagedBlobBytes(Uint64 bytes);
#endif
// Frames between two summary lines when MOBILEGL_PIPE_STATS=1.
inline constexpr Uint64 kDefaultSummaryFramePeriod = 120;
// The period Init() latched from MOBILEGL_PIPE_STATS_PERIOD (kDefaultSummaryFramePeriod
@@ -369,4 +447,20 @@ namespace MobileGL::MG_Util::PipeStats {
void SetEnabledForTesting(Bool enabled);
void ResetForTesting();
#if MOBILEGL_BUILD_DISAGGREGATED
// The role-derived path the JSON dump will actually write, or empty when
// MOBILEGL_PIPE_STATS_FILE is unset. Empty when unset; never the bare configured name.
//
// IT EXISTS BECAUSE THE OBVIOUS TEST IS NOT A CONTROL. The first version of this case asserted
// things about MG_Util::Debug::RoleLogPath directly - that the two roles get different paths,
// that neither equals the base name. Every one of those assertions passes with the fix REVERTED,
// because they test the naming helper, which was never broken; what was broken was that
// WriteJsonDump did not CALL it. A test that stays green while the defect is present is worse
// than no test, so this accessor exists to make the call site itself observable.
//
// Guarded on the DISAGGREGATED option rather than PIPE_PUSH, because the collision it describes
// only exists with two roles - a monolith build has one and needs no derivation (gate G1).
String RoleDerivedJsonDumpPathForTesting();
#endif
} // namespace MobileGL::MG_Util::PipeStats
@@ -2,3 +2,12 @@
#define GIT_COMMIT_HASH_SHORT "@GIT_COMMIT_HASH_SHORT@"
#define GIT_COMMIT_HASH_FULL "@GIT_COMMIT_HASH_FULL@"
// CONTRACT-P6 4.2. A SECOND PAIR, because the two above are application-visible through
// glGetString(GL_VERSION) and may not move. These are consumed by the ABI fingerprint alone.
//
// PRESENT is not "VALUE is non-empty": it is the build system's own answer to whether it could
// determine a commit at all. A build that cannot say so reports 0 and the handshake treats that
// as a distinct input rather than agreeing with every other stampless build in the world.
#define MOBILEGL_BUILD_STAMP_VALUE "@MOBILEGL_BUILD_STAMP_VALUE@"
#define MOBILEGL_BUILD_STAMP_PRESENT @MOBILEGL_BUILD_STAMP_PRESENT@
@@ -170,9 +170,21 @@ Java_top_mobilegl_plugin_trace_TraceReplayActivity_nativeRunTraceReplay(JNIEnv*
request.benchmarkResultPath = ToString(env, benchmarkResultPath);
request.envOverrides = SplitSemicolonList(ToString(env, envOverrides));
const bool needsNativeWindow =
request.backend == "DirectVulkan" ||
(request.backend == "DirectGLES" && !request.usePbuffer);
// THE SURFACE SHAPE DECIDES THIS, NOT THE BACKEND. DirectVulkan used to demand a native
// window unconditionally, which made `use_pbuffer` a DirectGLES-only knob in practice: the
// Android GLWS creates a window surface whenever gNativeWindow is non-null
// (apitrace_glws_android.cpp's createSurface), so handing Magma a window was the same as
// asking for one.
//
// P6 needs the pbuffer path on BOTH backends. Until P12 a spawned server cannot be given a
// window at all - an ANativeWindow* is a pointer into the CLIENT's process, and
// SetWindowHandle is refused on the way across with Fatal{UnmigratedSurface,
// "AndroidNativeWindow@P12"} (Rule H). Measured: the DirectVulkan spawn arm died on exactly
// that, one op after the server had come up green, while DirectGLES with the same flag passed.
//
// Every existing caller is unaffected: nobody asks for a Vulkan pbuffer today, and
// !usePbuffer reproduces the old answer for both backends in every other combination.
const bool needsNativeWindow = !request.usePbuffer;
ANativeWindow *window = needsNativeWindow && surface != nullptr ? ANativeWindow_fromSurface(env, surface) : nullptr;
if (needsNativeWindow && window == nullptr) {
auto result = MakeFailureResult(request, mobilegl_trace::STATUS_RETRACE_FAILED,

Some files were not shown because too many files have changed in this diff Show More