Files

272 lines
62 KiB
Markdown

# State ownership: session / context / share group / thread current (P14 design)
> Written for the unified server built into anland. The motivation and the rejected alternatives are in git history: "fork one render process per application" must not be used to paper over global state ownership. The line numbers here refer to `2f64ede8` (+ the `4156ca6e` documentation commit); after code moves, search by symbol name.
## Conclusion
Today the correctness of the whole stack rests on one equation: **one process = one server = one session = one context = one share group**. `ServerLoopInstance`/`ServerSessionInstance`/`g_applyThreadKey`/`pGLContext`/`pEGLContext`/`g_Display`/`g_Context`/`g_Surface`/`g_applier`/`gMGPipeContext` are all single-instance. `2f64ede8`'s `--serve --max-sessions` moves the equation into each worker process with fork, bypassing ownership instead of solving it; anland's unified server requires multiple sessions in one process, so the equation must actually be split apart in the code.
Split into four ownership layers:
| Layer | What it owns | Where it is wrong today |
|---|---|---|
| **Session** | SHM rings/segments, staged stores, reply/event routing, failure, the object handle space, PipeApplier, apply thread, backend runtime binding | The `ServerSessionInstance()`/`ServerLoopInstance()`/`g_applier` singletons (`ServerSession.cpp:535`, `ServerLoop.cpp:1191`, `PipeApply.cpp:484`) |
| **Context** | An independent GLContext: bindings/render state/errors, VAO/FBO/TF/pipeline/query (container objects are not shared), cache/scratch/owner/generation, native EGLContext | The single `pGLContext` (`MG_State/GLState/Core.cpp:1565`); `eglCreateContext` creates no GL state (`MG_State/EGLState/Core.cpp:625-700`); the backend's single `g_Context` (`DirectGLES.cpp:16184`) |
| **Share group** | The object registry and name allocation for buffer/texture/renderbuffer/sampler/shader/program/sync; the backend's twin/native object mapping | Mixed into the single `pGLContext`'s State members (`MG_State/GLState/Core.h:610-692`); `shareCtx` is stored but never used (`MG_State/EGLState/Core.cpp:650`) |
| **Thread current** | TLS points at (session, context); the owner relation does not go into TLS, a context can be handed over across threads; apply sets the runtime scope explicitly | `m_threadCurrents`/`m_contextOwners` already have a prototype but are tied to single-instance tables (`MG_State/EGLState/Core.h:283-284`); `g_applyThreadKey` is process-level (`ServerLoop.h:129`) |
Closing one session must not break another; the same handle name in different sessions/share groups must not interfere; shared contexts see the same shared objects.
## Wire changes
1. **Per-record context identity**. `MGPWireRecHeader` 8 B (`generated/PipeWire.inc:35-65`) carries no identity; `MGPApplierReset::ContextSerial` only asserts (`MGPipeTypes.h:1953-1960`). Design: context-family records (the 71 in `PipeTables.inc:32-45`) insert `Uint32 ContextSlot` between the header and the payload (the flags gain a `kRecHasContext` bit; the generator adds it once at the family declaration in `PipeCalls.def`, not per verb by hand). `ContextSlot=0` is reserved for "the session's default context", compatible with the old shape that has only one context. For screen-family records the object handle they operate on itself belongs to the share group; the server resolves it through "the record's context → share group" and adds no separate field.
- Why not one ring per context: a ring is the session's resource/credit unit; one per context would duplicate swap pacing, reverse events and segment lifetime in full; per-record identity solves the same problem with 4 B.
- Interleaving correctness: records from a multi-threaded client interleave on one ring; apply follows the record's own context and must not rely on "the last MakeCurrent". An indivisible batch (several records from one emit) may be merged only if the records share a context; the generator asserts this at batch boundaries.
2. **EGL lifetime on the wire**. `eglCreateContext`/`eglDestroyContext` are pure frontend today (`EGLImpl.cpp:327-333`, `:428-434`). `SurfaceOpKind` (`protocol.fbs:240-267`) gains `CreateContext{contextSlot, shareWithSlot, api, version, flags}` and `DestroyContext{contextSlot}`; `MakeCurrent`'s `context` field goes from "always 0/ignored" to a real slot. The frontend still builds EGL metadata locally; the wire is only responsible for making the server create the corresponding native context and share group.
3. **Reverse events carry a context**. `EventFenceSignaledHead` (`ServerSession.cpp:1324-1338`), the GL error and surface-changed event headers gain `ContextSlot` (surface events already carry a surface handle; the context lets the client dispatch directly). A fence handle belongs to the context's share group; the client checks it verbatim by (slot, gen).
4. **wireFingerprint is bumped with the changes above**; both ends rebuild from the same commit + an explicit `-DMOBILEGL_BUILD_STAMP=<commit>`, and drift is not accepted (the "Build artifacts" section of the handover document).
## S1 landed shape (context identity on the wire)
Items 1 and 2 above are P14a's target shape; S1 landed only the layer "identity can cross the wire and the server can attribute it", with the actual shape below, and later slices continue from it.
**data plane: `bind_context`, opcode 84** (`MG_Pipe/PipeCalls.def`, the `kScreen` family).
| Item | Value |
|---|---|
| payload | `MGPBindContext{ Uint64 ClientContextToken }` (8 B, `MGP_ASSERT_POD`) |
| flags / wait | `kNone` / `kWaitNone` (apply reads no client memory; the record's ring position is its entire ordering) |
| apply entry | no `MGPipeApply*`; like `applier_reset`/`object_death` it is a control record and reaches only `WireVerbSink` |
| monolith producer | none (G1 unchanged) |
| sink | `ServerVerbSink::OnBindContext` (`MG_Remote/Server/PipeApplier.cpp`) |
**token width: `Uint64` on both ends.** In the record it is `ClientContextToken`, in the control frame it is `SurfaceOp.context`; the equal width is deliberate, otherwise one end would have to truncate. `0` means "no context" (release) in both places, which is also the answer a session that has never bound already has. The token is minted by `EGLState::CreateContext` (`m_nextClientContextToken` starts at 1, dense, never reused), stored with `ContextObject`, and read out by `EGLState::CurrentContextClientToken()` / `GetContextClientToken()`.
**control plane: `SurfaceOpKind.CreateContext = 12` / `DestroyContext = 13`** (`protocol.fbs`), not two new CtrlMsgs—creating, destroying and make-current of a context have the same caller, the same thread and the same blocking frame channel as a surface, and opening another one would only add another place where ordering fights. `SurfaceOp` appends `shareGroupToken: ulong` and `contextFlags: uint` (reserved for extension, always 0 today). `MOBILEGL_PROTOCOL_CONTROL_REVISION` 5 → 6, with the line added to `scripts/ci/protocol_revision_pins.json` in sync.
- `CreateContext`: `context` = the new context's token, `shareGroupToken` = the share group it joins (`shareCtx`'s family, or a new one), `contextFlags` = reserved bits. `display`/`surface` are 0 (the server's display is the session's own).
- `DestroyContext`: `context` = the token to destroy; the server removes the entry and unbinds it if it is currently bound.
- Both are answered with the existing `SurfaceReply` (ok + refusal); S1 builds a placeholder runtime and has nothing else to reply with.
**Relationship between `bind_context` and the MakeCurrent control frame: not merged, each handles one thing.**
- The `MakeCurrent` control frame is still an **op on the native tuple**: it lets the server's apply thread decide whether to actually `eglMakeCurrent`, and takes part in `m_haveCurrentTuple` deduplication (the ID-54/ID-67 wording is untouched by a single character). Its `context` field is the same value as `bind_context`'s token, but that is "the same identity", not "the same path".
- `bind_context` is an **ownership record on the ring**: it tells the server "the records from now on, on this ring, belong to which context". It must be on the ring because GL records are on the ring, and there is no global order between a control frame and the ring to rely on.
- There is exactly one emission point: `EGLImpl::MakeCurrent` calls `EmitContextBinding` (`MG_Impl/EGLImpl/EGLImpl.cpp`) after the switch succeeds and before returning. That gives the constructive guarantee "before any later GL record"—the app thread cannot emit any record for the new context before `eglMakeCurrent` returns, and the ring is FIFO. If the token is unchanged nothing is emitted (an identical make-current is a legal EGL no-op).
- The `DestroyContext` frame is sent only after the client's `EGLState::DestroyContext` accepts, so a destroy that EGL itself refuses (the context is still current on some thread) never reaches the server, and the two ends cannot disagree through "the token quietly vanished".
**Difference in trade-off from item 1 (recorded explicitly)**: S1 takes "announce the identity at the edge" instead of "insert `Uint32 ContextSlot` between the header and payload of the 71 context-family records". The cost is one record per make-current (instead of 4 B per record); the benefit is that the payload layout and every `MGPWireRec_*` size stay unchanged, and the `kRecHasContext` bit and the batch-boundary generator changes are all unnecessary; the existing single-context shape (token 0 / never bound) is compatible with zero changes. If per-record identity under multi-thread interleaving really is needed later, add the slot per item 1 then—the two can coexist, and slot 0 still reads the current token.
**Server side** (`MG_Remote/Server/ServerSession.{h,cpp}`): each session gets a `{token → ContextRuntime}` table (`ContextRuntime{ Token, ShareGroupToken, Flags }`, a placeholder in S1, S4 gives it a native context) plus a current token (atomic, 0 = none). The `CreateContext`/`DestroyContext` control frames create/destroy the table through the `CreateContext`/`DestroyContext` arms of `ServerLoop::ApplySurfaceControlFrame`; `bind_context` goes through the codec to `ServerVerbSink::OnBindContext` to switch the current token. All writes happen on the apply thread, so the table needs no lock. A `bind_context` pointing at a token this session never created is `Fatal{ProtocolCorruption, "BindContext.ClientContextToken"}` (0 excepted, always legal); the table exists precisely so that this ruling has a basis.
**S1's token has a writer but no readers**: no apply branch on the server reads `CurrentContextToken()` today (provable by `grep`: nothing outside `ServerSession`'s own accessor calls it), so the whole rendering path behaves character for character as before S1—this layer records ownership first; reading it to act is S4's job (native context) and P14b/c's. A session without `bind_context` behaves identically too: the `ServerLoopTest` MakeCurrent/epoch/liveness cases (`MG_Test/Wire/ServerLoopTest.cpp:1780-1941`) all still pass, and they go through exactly this path.
**S1's acceptance evidence** (the tests of this commit): `PipeCatalog.LateArrivalsAreAppendedWithoutRenumbering` pins opcode 84 and `kNone`/`kScreen`/`kWaitNone`; `SurfaceControlFrameTest.TheContextLifecycleFramedOpsAreCreateContextAndDestroyContext` pins the values 12/13 and the `shareGroupToken`/`contextFlags` round trip; `SessionHandshakeTest.ARevisionFivePeerIsRefusedByNameAtRevisionSix` pins the revision bump; `FuzzArm2/PeerLatchSite/.../BindContextUnknownToken` is the data-plane end-to-end control—on a real `--serve` supervisor, a forged `bind_context` that points at a token this session never created makes the session latch by name (`exit=75`), and the next session of the same supervisor renders normally.
## Frontend (MG_State / MG_Impl)
1. **Split GLContext**. `MG_State/GLState/Core.h:77-698`'s `GLContext` splits into `ShareGroupState` (the object store + name allocation for buffer/texture/renderbuffer/sampler/shader/program/sync) and `GLContext` (bindings, error, viewport/scissor, render state, VAO/FBO/TF/pipeline/query store, texture unit bindings, current program). Container objects (VAO/FBO/TF/pipeline/query) are **not shared** and stay per-context; that is the GL 4.6 §5 wording—do not put FBO into the share group for convenience.
2. **Per-EGLContext instantiation**. `EGLState::CreateContext` creates a `GLContext`; when `shareCtx != EGL_NO_CONTEXT` it attaches to the other side's `ShareGroupState` (at the first share, migrate the other side's object store into the new share group, both pointing at it). `eglMakeCurrent` switches the TLS (session→) GLContext pointer; `eglDestroyContext` is allowed only when no owner exists (following `MG_State/EGLState/Core.cpp:714-718`); destroying a context does not destroy the share group, and when the last context leaves all share group objects are deleted.
3. **The tracker criterion becomes explicit identity**. The pointer comparison in `Pipe/Tracker.h:306-309` becomes (session, contextSlot); the semantics of re-pushing the full state on the first verb after a context switch are unchanged. `MGPipeTrackerInstance()` (`Tracker.h:956-963`) goes from a singleton to per-context (the tracker caches the per-context push shutter).
4. **eglMakeCurrent flow**: besides calling `backendObject->MakeEGLCurrent`, `EGLImpl::MakeCurrent` first switches the TLS GLContext and then sends `SurfaceOp::MakeCurrent{contextSlot}`; later context-family records from the client thread all carry this slot.
## S3 landed shape (frontend per-context / share group)
The "Frontend" section above is the target shape; S3 landed items 1 and 2 (the tracker/slot parts of items 3 and 4 are not done), and the actual shape is below.
**`ShareGroupState` (`MG_State/GLState/ShareGroupState.{h,cpp}`, new)** holds all object registries and name generators of one share group:
| Shared (ShareGroupState) | Per context (GLContext) |
|---|---|
| The object tables and `IndexGenerator` for buffer / texture / renderbuffer; the sampler object table (all of `SamplerState`); the program+shader tables and the shared name generator (all of `ProgramState`); `token` (S1's `ShareGroupToken`) | The error list; buffer binding slots and indexed binding points, touched high-water marks, the per-aggregate generations; texture unit / image unit arrays, the active unit, bind/sampling generation, the per-target default texture (name 0); renderbuffer binding slots; VAO/FBO/TF/pipeline/query; `current program` |
`BufferState`/`TextureState`/`RenderbufferState` therefore keep only the binding side: deletion goes "first look up the share group's object, then unbind this context, finally free the name", i.e. deleting an object is global and unbinding is per-context (GL 4.6 core 6.1/8.1). `ProgramState`'s `UseProgram`/`glDeleteProgram`/`ReleaseShaderNameIfOrphaned` now take the caller's current program as a parameter, and the current program itself lives in `GLContext`. `GLContext` is constructed from `GLContext(SharedPtr<ShareGroupState>)`; `GLContext()` creates a share group that belongs only to it (used by tests and the process default context).
**`pGLContext` becomes TLS**: `extern thread_local SharedPtr<GLState::GLContext> pGLContext` (`GLState/Core.h`). After `EGLState::MakeCurrent` succeeds it points at that context's `GLContext`; `ReleaseThread`/`eglTerminate`/the release path restore the value the thread had before entering EGL (`ThreadCurrentState::RestoreThreadGLState`)—so the existing semantics "one context is owned by one thread at a time" (`m_contextOwners`, EGL_BAD_ACCESS) are untouched by a single character, and the owner does not go into TLS either: after a context is handed over across threads its state is still in its own `GLContext`.
A thread without an EGL context falls to the **process default context** (`ProcessDefaultGLContext()`, created by `MG_State::Init()`; `pGLContext` is initialized to it at construction)—this is exactly the pre-split "one global context" semantics, so single-context applications and all existing tests that operate on `pGLContext` directly behave unchanged.
**Every `eglCreateContext` creates an independent `GLContext`** (`ContextObject::GLStateObject`); when `shareCtx != EGL_NO_CONTEXT`, the `GLContext` attaches to the other side's `ShareGroupState`, otherwise it creates a new one and records the `ShareGroupToken` minted in S1 in it. There is no need here to "migrate the other side's store": the group exists when the first context is born, and later ones simply join. `eglDestroyContext` drops the `ContextObject`; `GLContext` / `ShareGroupState` are destroyed when the shared pointer reaches zero.
**The default framebuffer (an explicit deviation)**: GL framebuffer 0 is still **one object per process** today (`MG_Impl::GLImpl::FramebufferImpl::pDefaultFramebufferInfo`; the backend uses it to decide "this is the default FBO"). It is handed to MG_State through `MG_State::SetDefaultFramebuffer` after `MG_Impl::Init()` creates it; after that every newly constructed `GLContext` installs it as its own name 0 and binds it to Draw/Read (`GLContext::InstallDefaultFramebuffer`). That is: every context has **its own FramebufferState entry and binding** (`glBindFramebuffer` calls do not affect each other), but the object is shared for now. A real per-context default framebuffer belongs to the "backend per-context native tuple" phase (see "Backend" §1); until then, if each context created its own, the backend's `pDefaultFramebufferInfo` identity test would fail for the second context.
**Monolith and split use the same structure**: both ends share one `MG_State`; `eglCreateContext`/`eglMakeCurrent`/`eglDestroyContext` all write this frontend state first, and the only difference between `MOBILEGL_PIPE_PUSH=0` and `=1` is where the backend reads state from (`MGB_CTX` is either `pGLContext` or `gPipeInputs`). `MGB_CTX_IDENTITY` therefore naturally varies per context, and the post-S3 tracker only has to compare as before (turning it into an explicit slot is a later slice).
**Acceptance evidence** (this commit): six cases in `MG_Test/State/ContextStateOwnershipTest.cpp`—two nonshared contexts have independent name spaces (same name, different objects, bindings not visible to each other); a shared pair sees the same object while each holds its own bindings; after an `eglMakeCurrent` switch, error/viewport/FBO binding are independent and still there when switching back; after `eglDestroyContext` the other context's objects and bindings are unaffected; after release the thread returns to the GL state it had before entering EGL; a thread without a current context falls to the process default context.
## Server (MG_Remote/Server)
1. **Session registry replaces the singletons**. `ServerSessionInstance`/`ServerLoopInstance` become a session table held by `ServerProcess` (slot → {transport, ServerSession, ServerLoop, PipeApplier, apply thread}). The in-process server (`ServerMain.cpp:1593-1651`'s `mobilegl_server_serve_inprocess`) goes from "single active + RefuseBusy" to accepting up to a limit (default 8, configurable); the unix path of `--serve` likewise becomes multiple sessions in the same process, **removing fork-worker dispatch** (`ServerMain.cpp:1566-1584`), and `--max-sessions` becomes the same-process limit. TCP's single-active `TcpSupervisor` (`:1220-1223`) gives way as well.
2. **One apply thread per session**. `g_applyThreadKey` (`ServerLoop.h:129`) becomes a per-session member; `OnApplyThread()` semantics unchanged (same-thread comparison). Ordering between sessions is naturally done by the threads, with no global lock; the native driver already supports multiple threads each current with a different context.
3. **`g_applier` per session**. The process-level `MGPipeApplierState` in `PipeApply.cpp:484` becomes session-owned; `MGPipeApplierReset`'s role guard (`PipeApply.cpp:1474-1481`) judges by this session's apply thread. The existing share-group object records / working-state split in `PipeApply.h:558-617` is the foundation: object record tables are bucketed by share group, working state by context, and reset clears only this context's working state. **(S5 has landed; for the shape see "S5 landed shape" below: this item ultimately is not "one applier per session" but one applier per {session, context}, whose object records hang on the {session, shareGroup} group.)**
4. **Reverse routing by session + context**. `ReverseCallbackOwner`'s (`ServerSession.cpp:408-418`) single-activity `Active()` becomes "resolve by the originating thread / an explicit session parameter"; event headers gain `ContextSlot` (see wire 3). `gMGPipeCallbacks` (`MGPipeCallbacks.h:77`) goes from a process-level variable to a per-session table, attached to the session at Accept rather than globally.
5. **The session mode latch stays at the session layer**. `SessionSurfaceMode`/`SurfaceModeMismatch` (`ServerLoop.h:199-206`, `ServerLoop.cpp:1539-1544`) keep their wording: a compositor session latches OnScreen, an app session latches Offscreen; a unified server holding both kinds of session at once is a legal shape, and the latch must not be raised to process level.
### S2 landed shape (multiple sessions in one process)
Items 1, 2, 4 and 5 above are P14c's target shape; this slice landed the layer "ownership split, routing by thread", and the actual shape is below.
**One runtime per session, the singleton becomes a fallback** (`MG_Remote/Server/SessionRuntime.h`). `SessionRuntime` holds the session's `ServerSession`, `ServerLoop` and `PipeInputs` block, plus a latch domain and a segment resolver binding; `ThreadSessionScope` attaches it to **the session's two threads**—the control thread (`ServerMain::RunSession`'s own thread, one `std::thread` per session in the supervisor) and the apply thread (`mgl-srv-apply`, whose first act in `ApplyThreadMain` is to open the same scope). `ServerSessionInstance()` / `ServerLoopInstance()` / `ServerSession::Active()` therefore first ask "which session does this thread belong to", and only **a thread that belongs to no session** gets the process-level singleton. This item gives ~900 `gPipeInputs` / `MGB_CTX` / `ServerSession::Active()` call sites correct attribution without changing a line. The inproc "client+server in one process" shape deliberately does not open a scope (`ClientSession` calls the singleton directly), so that shape's verb barrier, single PipeInputs block and character-for-character behavior are completely unchanged.
**`gPipeInputs` is a per-thread resolved reference** (`MG_Backend/MGPipe/PipeInputs.h`). `gPipeInputs` goes from "one process-level object" to a `thread_local` reference, resolved through `g_pipeInputsThreadResolver`, a probe the server layer installs once, to this thread's session's block, falling back to `gPipeInputsDefault` (the original object) when there is no session. **Why this shape**: `MGB_CTX` is `(&gPipeInputs)`; to leave ~380 sites unchanged while making the target vary by thread, only "a reference whose target varies by thread" works. The cost is one TLS address computation per access site (not per field, and with no guard: bound once on first use per thread), which is this slice's known cost.
**The apply-thread identity becomes one TLS bit; the process-level word becomes a counter.** `OnApplyThread()`'s answer can now only be "is this thread an apply thread", so it is a `thread_local Bool` (zero-initialized, no guard, no atomic); `Detail::g_applyThreadKey` keeps its name and type but holds **the number of live apply threads in this process**—`MG_Backend/DirectGLES/Managers.cpp` (outside this slice's file set) reads `!= 0` to ask "is any apply thread running", and the count answers exactly that; no hot path reads it anymore.
**The latch is one domain per session** (`MG_Remote/FatalFunnel.*`). The original four process-level statics become per-domain `LatchState`; a thread binds to a domain (`ThreadSessionScope`), and without a binding it is domain 0 (the process default = the old behavior). The reason is correctness, not tidiness: all three readers of `SessionLatched()` are on the session's own threads (the apply loop, `DrainRing`, `RunSession`'s control loop), and when one latch is shared by the process a bad byte in session A can stop B's apply thread; `ResetSessionLatch()` has the mirror problem (one session's reap clearing the live one's latch). Now A's close/fault cannot reach B.
**The segment resolver is a per-thread table plus a process-level hook** (`MG_Remote/Wire/PipeWireCodec.*`). `gMGPipeSegmentResolver` remains a process-level function pointer (installed once, never cleared again), but the thunk first checks **the calling thread's bound table**, and only then the process-level fallback. A second table on the same thread is still `Fatal{...already installed...}` (the wording of the existing `APartiallyZeroUploadBoxIsFatalRatherThanASilentRace` and `ASecondProcessResolverIsFatalRatherThanASilentRace` is unchanged); a second session on a different thread is no longer an error.
**The global callback table: installed once, routed by thread, removed only when the last session closes.** The five entries of `gMGPipeCallbacks` remain process-level function pointers (every session installs the same set); `Close()` clears them only when `ServerSessionCount()` reaches zero; `g_sessionOwner`'s CAS claim **no longer applies to sessions with a runtime** (a shared table is legal), and keeps the original `Fatal{RoleViolation,"callback-double-install"}` only for shapes where "the process is one session" (the inproc client+server roles, `ServerLoopTest`'s `FvSession` and its peers).
**The surface mode is still D4's per-session latch** (`ServerLoop::m_surfaceMode`). This slice once introduced `SetDeclaredSurfaceMode`, letting `RunSession` declare a mode for the session from the **process's own** `MOBILEGL_IPC_SURFACE`—**it has been withdrawn**, for two reasons: (a) a process-level environment variable cannot speak for the multiple sessions a unified server holds at once (§4 item 5 asks for unchanged wording and a latch that must not be raised to process level), and (b) it is wrong for a client that dials in—a pre-started server does not inherit the client's env (the TCP shape of `ServerOwnedSurfaceTest`), so the session is declared offscreen, ServerOwned's surface creation hits `SurfaceModeMismatch` first, and it never reaches the named refusal "this server has no display". **And it is not needed**: `m_surfaceMode` is a member of `ServerLoop`, each session has its own loop, and the two sessions latch their own modes—"an independent surface mode per session" is exactly this shape and needs no declaration at all. A shape that really wants to declare the mode before the first surface (P14d's KWin on-screen + Konsole offscreen on the same server) must **put the mode on the wire** (in Hello or a SurfaceOp); that is P14d's debt; until then, whoever creates the first surface latches it, and that is each session's own answer. **`ServerDisplay`'s lease is naturally multiplexed**: the holder is a loop pointer, `AcquireFor` leases the window to only one session, and a second on-screen session gets the **named refusal** `NoServerWindow` (naming LeasedElsewhere in the log), no longer the comment's "sessions are sequential: a bug if seen"; offscreen sessions take no lease at all and can be arbitrarily many.
**The access layer**: `UnixInProcessSupervisor` (the unix branch of `mobilegl_server_serve_inprocess`) goes from "one at a time + a second gets Refuse{Busy} one session is already active" to **concurrent up to `MOBILEGL_IPC_INPROC_MAX_SESSIONS` (default 16)**, one control thread per session, and over the limit it uses the same sentence as the fork path, `Refuse{Busy} the session limit is reached`; the embedded ABI signature is unchanged. **Three places untouched**: the `--serve --max-sessions` fork worker path (process isolation remains an optional shape; `UnixSupervisor.ConcurrentSharedMemoryClientsHaveSeparateWorkersAndAnExitedSlotIsReused` and `...RequiresAnExplicitLimit` stay as they are), the in-process TCP shape (still one session at a time; `InProcessServer.AnAuthenticatedSecondHelloWhileASessionIsLiveIsRefusedBusy` stays), and the fork shape of `TcpSupervisor`. One number differs from "default 8" written in §4 item 1 of this document: this slice takes 16, and the limit is an environment variable rather than a new ABI parameter.
**Acceptance evidence** (added by this slice): three cases in `MG_Test/Wire/MultiSessionTest.cpp`—`MultiSessionFixture.TwoShmSessionsInOneProcessAreServedAtOnce` (two SHM sessions concurrently in one process: two Welcomes with the same pid, two `in-process unix session #N started` lines in the log, each clears and reads back its own color), `MultiSessionFixture.SameNamesInTwoSessionsDoNotCollide` (the same client context token and the same render state handle are both accepted in two sessions—names are names within a session), `MultiSessionFixture.ClosingOneSessionLeavesTheOtherServing` (after A is closed and reaped, B keeps applying three records; the process-level resolver/callback table was not removed by A). The existing suites do not regress: `InProcessServerTest`, `ServerDisplayTest`, `UnixSupervisor`, `SupervisorChildren`, `ServerLoopTest`/`ServerLoopEglTest`/`ServerLoopLatchTest`, `EmbeddedServerTest`, `PeerLatchTest` (including `PeerLatch.SiteMap`, whose FatalFunnel check regex was updated with the domain rewrite), `ServerOwnedSurfaceTest`, `SessionHandshakeTest`, `SurfaceControlFrameTest` are all green (the only remaining failures in host ctest are the compile/link-time baseline failures caused by the dirty `3rdparty/glslang` submodule, unrelated to this slice).
**Correction (the color unpacking of `HealthySessionWithColor`)**: when this slice parameterized the green clear in `P12ServerRig.h`, it once unpacked `rgba` in the reversed order `A<<24|B<<16|G<<8|R` (treating the top byte as R), so `0xFF00FF00` (green) was cleared to `0x00FF00FF` (magenta), and `InProcessServer.SequentialSessions...`'s readback assertion failed. The correct unpacking is simply readback's own byte order—`PeerReport::pixel` is a little-endian `Uint32` of a GL_RGBA/GL_UNSIGNED_BYTE triple, so `R = rgba & 0xFF … A = rgba >> 24`. **The production path (clear → read_pixels) did not change a byte**: `PeerLatchTest` uses the same green literal `{0,1,0,1}` and asserts the same `0xFF00FF00`, and its corresponding case was green throughout, which is the control for this conclusion. Red `0xFF0000FF` is a palindrome under byte reversal, which is why only the green session failed at the time—this is not two separate bugs.
**What this slice explicitly did not do (the next layer's debt)**: DirectGLES's `g_Display/g_Config/g_Context/g_Surface` and the six twin registries are still process-level (P14b's per-context native tuple), so the **native contexts of two concurrent sessions are not isolated**: one session's teardown still tears down the process's EGL context, so this slice's rendering acceptance is done only while both sessions are alive; the evidence after closing one is at the record level (records are still applied and get replies). `MGPipeServerSetContextLive` / `MGPipeServerSetOwnedWindow` and `PipeInputs.cpp` are likewise process-level and outside this slice's file set. `MG_Util::PipeStats::Init/Shutdown` is still process-level; under multiple sessions it is telemetry noise, not correctness. `SessionFail` (a real Fatal when not armed) still takes the whole process down—that is the reason the `--serve` fork shape exists.
## Backend (DirectGLES)
1. **Native tuple per context**. `g_Display` stays process-level (initializing the native display once is reasonable); `g_Context`/`g_Surface`/`g_Config` (`DirectGLES.cpp:16183-16186`) become a per-(session, contextSlot) table; native contexts are created per share group with `eglCreateContext(share=…)`.
2. **Remove the unconditional teardown**. `InitDisplayAndContext`'s first statement `DestroyEGLContext()` (`DirectGLES.cpp:16569`) and `BackendObject_DirectGLES`'s `DestroyEGLContext()+ResetEGLRuntimeState()` before surface creation (`BackendObject_DirectGLES.cpp:972-982`, `:1007-1014`) become: if the target context already exists, reuse its native context and only rebind the surface; pbuffer→window→pbuffer loses no resources. `DestroyEGLContext` tears down only the given context; `eglTerminate` only when the last context is gone.
3. **Managers: one table per share group / context**. The six twin registries (`Managers.cpp:6895`, `:11035`, `:12835`, `:13188`, `:16255`, `:16580`) are instantiated per share group; `g_activeTextureUnit`/`g_boundTexturesCache`/the sampler cache (`Managers.cpp:11031-11032` etc.) per context; `DropEveryTwinForEndedServerSession` (`Managers.cpp:425-443`) clears only this session. `g_backendContextGeneration` becomes a per-context generation. **(The twin key and per-session cleanup have landed, see S6; the unit shadow and the context generation are still owed.)**
4. **Review DirectVulkan alongside**. Magma's per-device/per-queue structures also need to be split by session; this phase only ensures no compile regression, and Magma's acceptance under multiple sessions is listed separately.
### S4 landed shape (native tuple per context + share-group keying)
Items 1 and 2 above are P14b's target shape; S4 landed the layer "native tuple attributed by context, creating a second context/surface no longer tears down the context, share group enters native", and the actual shape is below.
**The native tuple is keyed by (session, token)** (`MG_Backend/DirectGLES/DirectGLES.cpp`'s `NativeContextTuple` / `NativeSessionState` registry). `g_Display` is still one per process with a single `eglInitialize`, and `eglTerminate` only when the last native context is gone (`g_displayUsers` counter). `EGLContext`/`EGLConfig` follow the tuple; **the native surface is one per session** (in EGL a surface does not belong to a context, only the draw/read binding does), and the tuple records which surface it currently draws to. The key is answered by a probe the server layer installs (`SetNativeContextKeyResolver`, installed once in `MG_Remote/Server/SessionRuntime.cpp` through `ThreadSessionScope`): the answer is **this thread's session identity + `ServerSession::CurrentContextToken()`**; on a thread without a probe (monolith, pure frontend process, unit case, inproc single-process shape) the answer is always `{0,0}`—which is exactly the process singleton being replaced, so the single-context world is unchanged character for character.
**Creation no longer tears down the context**. `InitDisplayAndContext()` (whose first statement was the unconditional `DestroyEGLContext()`) is replaced by `EnsureNativeContext(tuple, surfaceBit, window)`: if the tuple already has a native context, reuse it and only choose a config if needed; create one only if there is none. `BackendObject_DirectGLES::CreateEGL{Window,Pbuffer}Surface` likewise drops the teardown of `DestroyEGLContext()+ResetEGLRuntimeState()` and keeps only the base class's per-surface bookkeeping. So pbuffer→window→pbuffer merely adds to or switches within the session's surface set, and the tuple's `EGLContext` does not change a character—so objects (backend twins live directly in the native context) are naturally not lost. `DestroyEGLContext()` is now the **session's** full teardown (the semantics of `ReleaseEGLResources`/`~BackendObject_DirectGLES`); destroying a single context is the new `DestroyNativeContextFor(token)`.
**The share group enters native** (`CreateNativeContextFor(token, shareGroup)`). When the `CreateContext` control frame arrives, the server creates a native context for the token: **within the same session, the `EGLContext` of the tuple with the same shareGroupToken that already has a live context is used as the share parameter of `eglCreateContext`**, otherwise `EGL_NO_CONTEXT`. Later contexts in the group therefore share the native object namespace. If creation fails, it rolls back that session entry and returns `ok=false` to the client.
**`bind_context` is the native switch point**. When the MakeCurrent control frame arrives, `CurrentContextToken()` is still the old value (S1 deliberately lets the client emit the binding record only after make-current succeeds), so switching native there would bind to the context just left. `ServerVerbSink::OnBindContext` (`MG_Remote/Server/PipeApplier.cpp`) calls `DirectGLES::MakeNativeContextCurrentForBoundToken()` after `session->BindContext(token)`: resolve the tuple by the new token, return if it is the same as `t_boundNativeContext` (each bind of a single context costs zero), and do a native `eglMakeCurrent` only when different.
**Acceptance evidence** (added this commit, `MG_Test/Wire/ServerLoopTest.cpp`, real headless EGL): `ServerLoopEglTest.CreatingASecondContextLeavesTheFirstNativeContextAlive` (three context tokens in one session; three native EGLContexts alive at the same time and distinct—restoring the pre-S4 unconditional teardown leaves only one); `ServerLoopEglTest.CreatingAnotherSurfaceKeepsTheSameNativeContext` (after creating a second pbuffer the tuple's `EGLContext` handle is unchanged and the native context count is still 1). The existing set does not regress: the 97 cases this slice names are all green (86 baseline + 11 `ServerLoopEglTest` + the two above).
**What this slice explicitly did not do (the next layer's debt)**:
- **`g_applier` was not changed to {shareGroup → applier}** (server item 3 above). The reason is not time but **shape**: `MGPipeApplierState` mixes "the share group's object records" and "the per-context working state" in one structure (`PipeApply.h:515-933`; its own comment at line 101 already points out this split), and keying it by share group literally would make **two contexts of the same share group share working state**—bindings, current program and unit sets overwrite each other, which is worse than not changing. The right approach is to first split the structure along that line (object tables into the share group, working state into the context), which is a separate cut. Today `g_applier` and `gMGPipeApplierReset` are untouched character for character. **(S5 did it, see the next section.)**
- **The six twin registries and the twin key `{shareGroup, slot, gen}` are unchanged** (`Managers.cpp`). A twin is still reused by a backend context that is alive by reference; correctness under multiple contexts rests on "one native context, one twin generation", which holds while both contexts are alive (measured this time) but has no evidence on paths that migrate a twin across contexts. **(S5 still did not do it; S6 did, see "S6 landed shape".)**
- **Driver-level proof of the share group did not land**. `eglCreateContext(share=…)` is wired, but the probe that asks `glIsBuffer` directly through headless EGL got no usable control on this machine (`glIsBuffer` returns false right after `glGenBuffers` in the same context), so it was not taken in as "an empty run that was green". Proving it at the driver layer requires understanding that probe first and then adding a case. **(S5 did not figure it out either: see S5's not-done items and "why it was not done".)**
- **Wire item 1's per-record `ContextSlot` is not done**; it is still S1's edge announcement + `bind_context`.
- **`g_backendContextGeneration`/`g_syncContextGeneration` are still process-level**: destroying a single context advances the global generation, so other contexts' old fence/query handles read as "already signaled". The safe direction (at worst waiting longer), but not a per-context generation; belongs to P14b/c.
- **ServerLoop's MakeCurrent deduplication is still "the one currently bound tuple"**, not a per-context table. The reason is in `ServerLoop.h:560-573`: ID-67's pinned case (A→B→A must be three native binds) defines "different tuple" as a change of **the current binding**, and in EGL a thread has only one current context at a time, so returning to A really must rerun those seven frontend context invalidations. "Each context holds its own native triple" is satisfied by the backend's {session, token} registry; the unit of this deduplication layer is still the thread's current binding.
### S5 landed shape (applier keyed by {session, context} / {session, shareGroup})
The last piece S4 left: `PipeApply.cpp`'s process-level `g_applier` is now a **per-(session, context) registry**, whose object records are bucketed by {session, share group}.
**Structure split** (`MG_Pipe/PipeApply.h`). The former single `MGPipeApplierState` is split into two structures by two lifetimes:
| `MGPipeObjectRecords` (share group) | `MGPipeWorkingState` (context) |
|---|---|
| `Resources`, `VertexElementsCsos`, `TextureResources`, `RenderbufferResources`, `SamplerCsos`, `SamplerViewCsos`, `ShaderCsos`, `CompositeShaderCsos`, `FramebufferRecords` | `RenderStateCsos`, `BoundRenderStateCso`, `Residual`, `ScatteredChunkBits`, the four wire counters and the four refusal counters, `BoundVertexElements`/`VertexBuffers*`/`IndexBuffer*`, `MapPersistentRoundtrips`, `BoundFramebuffer`/`FramebufferSerial`/`StaleFramebufferRecordLookups`, the three unit windows, the three program handles, the three binding-point windows, `IsTransformFeedbackActive`, `TextureShutterSerial`/`ContextSerial`, the verb handle group under `#if DISAGGREGATED` |
`RenderStateCsos` on the working side is not a typo: it is **cleared by `MGPipeApplierReset`** today (a fresh CSO table per make-current), and by the existing rule it stays in the per-context half. `FramebufferRecords` staying on the object side is also by the existing rule (reset does not clear it), and its slots come from the global allocator, so one share group holding the records of two contexts is "a wider table" rather than an alias.
`MGPipeApplierState` now **inherits** `MGPipeWorkingState` and holds a `MGPipeObjectRecords& Objects`, and also binds the nine object tables **as reference members under their original names** (`Resources`, `TextureResources`…). The reason is written in the header: the ~200 call sites in MG_Backend / MG_IntegrationTest / MG_Test have always read `st.Resources` as "this object's share group record"; binding references leaves those read sites **unchanged** while resolving correctly by the group their context belongs to; turning a keying change into a renaming change adds risk without adding correctness. The header can use both `Objects.X` (making the group explicit where the two halves are **created**) and `X` (the spelling the backend has always used); they are the same table.
**Registry and resolution chain** (`PipeApply.cpp`). Three layers, isomorphic to S2's `gPipeInputs` and S4's native tuple key:
- `MGPipeApplierKey{ SessionKey, ContextToken }`, answered by a probe installed by `MGPipeSetApplierKeyResolver`; `SessionRuntime.cpp` installs it in `InstallSessionRuntimeHooks` (installed as soon as `ThreadSessionScope` opens). The probe's answer is **the address of this thread's session's `ServerSession*` + `CurrentContextToken()`**; a thread that is not a session thread answers false and gets the process-level applier—which is exactly the singleton being replaced, so monolith / pure client / inproc single-process shape / unit cases are unchanged character for character.
- `MGPipeApplierRegisterContext(session, token, groupToken)` / `MGPipeApplierUnregisterContext` / `MGPipeApplierReleaseSession`. **Register rather than infer**: `ServerSession::CreateContext` / `DestroyContext` call these on the apply thread, so the resolution probe is always just "read the current token this session already maintains", without reading the session's map from another thread; `Accept` and `~SessionRuntime` release the whole session.
- **Group key**: `shareGroupToken != 0 ? shareGroupToken : (contextToken | high-bit sentinel)`. The frontend's share group tokens and context tokens come from two counters; without isolation, group 7 and context 7 would become one group; `0` is the sentinel for "this context started its own group" from the S1 comment (and the value passed by hand-built contexts such as `ServerCreateEGLContext(token, 0, 0)`), landing as "its own group" rather than "the same group as the other 0".
- **The group's object records are released only when the last context leaves** (the per-group version of `MGPipeApplierReleaseObjectRecords`); while the other context of a group is still there, not one record is lost.
- **Thread-local cache + generation number**. `MGPipeApplier()` is called by the backend on every state read, so the fast path is "if this thread's last (session, token) and the registry generation both match, return directly"; every registry change does `++generation`, and a cached pointer is dereferenced only when the generations are equal—that is why "another thread destroyed the context" leaves no dangling cache. The fast path costs three TLS reads, one atomic read and two comparisons; with a null probe (monolith) it is one function pointer comparison.
**Frontend/session integration**: `EGLImpl::MakeCurrent`'s `EmitContextBinding` is untouched—S1's edge announcement was always all the information "this ring belongs to whom from now on", and S5 is simply the first time **reading** it.
**Acceptance evidence** (added this commit):
- `MG_Test/Wire/ApplierOwnershipTest.cpp`, 5 cases, driving the registry and resolution directly (no EGL, no wire): same-named handles in two nonshared contexts are two records that do not overwrite each other (nor does reset lose them); two contexts of one share group **share the object table while each holds working state** (current program and vertex-buffer windows are not visible to each other, while a create on that one table is visible to both); two sessions with the same group/context token names share nothing; a group's records live until the last context leaves, and a re-minted token does not inherit a dead group; a thread without a session still gets the process-level applier.
**Negative control** (mandatory, otherwise it is an empty green): change the resolution probe the test installs to null (i.e. back to the pre-S5 "everyone gets the process-level applier"), and all 5 cases **go red**; switch it back and all are green.
- `MultiSessionTest.TwoSessionsInterleaveTwoContextsEachWithoutCrossTalk`: on the real `--serve` predecessor (the in-process unix supervisor), two sessions with two contexts each (same token names and same group token names), **8 interleaved rounds**: each round first sends one `bind_context` per session to switch context, then runs a full clear + real readback. The green and red colors witness for each other; 0 `SessionLatch{` lines in the log. This case stresses both the **production** resolution chain (the probe installed by `ThreadSessionScope`) and concurrency (two apply threads running at once).
- The existing set does not regress: the 97 cases this slice names and the original 4 cases of `MultiSessionFixture` are all green (including `ServerLoopEglTest`'s 11 and `ContextStateOwnershipTest`'s 6). Two `SanityTest` cases were changed to save/restore the working fields they really modify, because `MGPipeApplierState` is no longer copyable.
- **Name-by-name comparison of the full host ctest against the baseline** (not "looks about the same"): first `git stash` away all of this slice's changes, rebuild, run the full suite (`ctest -j 8`, 2735 cases) and keep the failure list; then restore this slice, rebuild, run the same pass, and `comm` the two lists:
| | Count |
|---|---|
| Baseline failures | 266 |
| This slice's failures | 265 |
| **New failures in this slice** | **0** |
| Baseline failures that this slice does not fail | 1 (`ProgramTest.CompileVertex`, a known flake in the glslang batch) |
The failure lists all fall in the glslang / shader compilation family (`ProgramTest`, `ProgramInterfaceTest`, `AsyncLinkTest`, `GlslangCaptureProbeTest`, `TranslationCacheTest`…), consistent with the existing baseline of the dirty `3rdparty/glslang` submodule.
**What S5 explicitly did not do (the next layer's debt)**:
- **The six twin registries and the twin key are still unchanged** (`MG_Backend/DirectGLES/Managers.cpp`'s six `g_backend*` static registries; the key is in `Managers.h:315`'s `StateBackendObjectRegistry` → `SlotTables.h`'s `BackendSlotTable<MGPipeHandle{Slot,Gen}>`). **This is the remaining half of "same-named handles in two nonshared contexts" after S5**: the two records in the applier are right (tested), but the twin layer is keyed by `{slot, gen}`, so the same handle value from two contexts resolves to the same twin; the reverse also holds—paths that reuse a twin across contexts are not grouped by share group. The `glIsBuffer` probe from the S4 report still has no usable control on this machine, so **driver-level shared / nonshared evidence is still missing**, and it was not taken in this time as "an empty run that was green" (this is the evidence this slice most owes the next cut). Changing the shape means adding a group dimension to `BackendSlotTable` or instantiating the six registries per group, touching every call site in `Managers.cpp`; that is not a cut that can be completed safely in this round's time. **(S6 did it, see the next section; the driver-level probe is still unsolved, and S6 took the twin identity route as substitute evidence.)**
- **Resource retention across pbuffer→pbuffer→pbuffer** is only at the level S4 landed (`ServerLoopEglTest.CreatingAnotherSurfaceKeepsTheSameNativeContext`: switching surfaces does not change the tuple's `EGLContext` handle). The real "back and forth among three pbuffers with all resources intact" needs the window half and cannot be verified headless on this machine; recorded only, per S4's wording.
- **Wire item 1's per-record `ContextSlot`** is still not done, still S1's edge announcement + `bind_context`. So "records of two contexts interleaved on one ring" holds only when the client emits in make-current order (the interleaving stress case this round goes through exactly that order).
- **`MGPipeApplierShareGroupCountForTesting`** is a test observation surface, not a production API.
- **`MGPipeApplierState`'s two spellings—the nine table names and `Objects.X`—coexisting** is the deliberate price for leaving ~200 read sites unchanged; the chance to rename comes in the same cut as the twin registry.
- **`g_backendContextGeneration`/`g_syncContextGeneration` and ServerLoop's MakeCurrent deduplication** are as listed in the S4 section, still untouched.
### S6 landed shape (twin tables keyed by {session, shareGroup})
The last piece S5 left: the eight backend twin tables (the six `StateBackendObjectRegistry`, plus `BackendBufferResourceTable` and `BackendSamplerViewTable`) go from process-level `{slot, gen}` tables to tables **bucketed by `{session, shareGroup}`**. This is the remaining half of "same-named handles in two nonshared contexts"—the applier's records are already separated (S5), but the twin those records point at was still one.
**Key structure** (`MG_Backend/DirectGLES/DirectGLES.h`). `TwinKey{ SessionKey, ShareGroupKey }`, **the second half of the same pair** as the applier's `MGPipeApplierKey`: `SessionKey` is the address of the `ServerSession*` (the same value S5 registers with, so the two sides agree by construction), and `ShareGroupKey` goes through `MGPipeApplierShareGroupKeyFor(session, currentToken)`—**sharing one function instead of writing the rule twice**, because a record and the twin it describes must always land in the same bucket, and a second spelling of "0 means this context started its own group" is exactly how they would come apart. `{0,0}` is reserved for "a thread that belongs to no session", i.e. the process singleton being replaced.
**Resolution chain** (`MG_Remote/Server/SessionRuntime.cpp`). The third isomorphic probe: `ResolveThreadTwinKey` reads the `t_runtime` installed by `ThreadSessionScope` → `runtime->Session().CurrentContextToken()` → `MGPipeApplierShareGroupKeyFor`; installed once by `InstallSessionRuntimeHooks` with `SetTwinKeyResolver` (parallel to S2's PipeInputs probe, S4's native tuple key and S5's applier key). On a thread without a probe (monolith, pure client, inproc single-process shape, unit case) the answer is always `{0,0}`. **The probe reads only server-session-side state and does not touch `MG_State`**: `CurrentContextToken()` is an atomic the apply thread maintains itself, and `MGPipeApplierShareGroupKeyFor` reads the applier's registry, so the apply thread's constraint "no frontend keyed lookup" (`Managers.h:341/406/430-436`) stands as written.
**Table shape** (`SlotTables.h`'s `SlotTableRegistry`). A bucket is a `SharedPtr<BackendSlotTable<…, kKind>>` stored in an unordered_map by key, with a thread-local memo "last key → bucket" (the hot path is one comparison). **~150 call sites are unchanged**: `SlotTableRegistry` forwards every handle-keyed entry on the table (`GetOrCreate` / `FindByHandle` / `LiveGenAt` / `HandleOf` / `StateForHandle` / `NoteStateForHandle` / `ReleaseByHandle` / `ForEachLive` / `LiveCount` / the two capacity observations) to **the calling thread's bucket**, so `g_backendTextureObjects.FindByHandle(h)` is still that line of text but answers with this context's name space; inside `StateBackendObjectRegistry` `m_slotTable` likewise becomes `m_slotTables` and is forwarded. Two deliberate trade-offs:
- **The holder list stays process-level**. A notice is about the **object**, not the bucket: `OnFrontendObjectDestroyed` / `ReleaseTwinByHandle` must reach the by-value copy held by the fixture or the context reset, whichever bucket it is in—"which bucket holds it" is precisely the problem that caused the double-holder leak. Every shared holder is one bucket, so death notices naturally cover all buckets.
- **`ForEachLive` walks the calling thread's bucket**, not all buckets. The caller asks "which of the objects I can see need this", and what it can see is its own share group; walking all buckets would reach a neighbor session's objects. The two places that need a whole-process view (death, diagnostics) use the new `ForEachBucket(fn)` (the callback carries the key).
**New control surfaces**: `Drop(key)` (one group), `DropSession(sessionKey)` (all groups of a session), `ResetBuckets()` (all, i.e. what `= {}` meant in the old shape), `BucketCount()` / `BucketSnapshot()` / `BucketForCallingThread()` (observation surfaces for tests and fixtures). `BackendSlotTable::Reset()` is written as "move both spaces out first, then destruct", for the same reason as `ReleaseTwinAt`: a twin's destructor is a driver call and may reenter `GetOrCreate`.
**`DropEveryTwinForEndedServerSession` becomes per-session** (`Managers.cpp`). It runs on **the apply thread of the session that is ending**, and after S2 other sessions in the same process may still be rendering, so it is now "delete all buckets of the calling thread's session"; a thread without a session (unit cases, `SanityTest`'s `Transport=Spawn` shape, fork workers) performs the full cleanup, character for character as the old shape. The three unit shadows `g_boundTexturesCache` / `g_boundSamplersCache` / `g_activeTextureUnit` are still process-level and are still cleared wholesale here (see the debt below).
**The comment at `Managers.h:2190` is corrected as well**: it used to say "a texture is owned by exactly one context (share groups are not implemented)". What really holds is that **a texture belongs to a share group** (S3's `ShareGroupState` holds the object table, and after S6 the twin table is keyed by group as well), and both contexts of a group may legally modify it; `m_syncedShapeContextId` is therefore only half of a cheap gate—another context in the same group changing shape stamps a new id and (redundantly, but safely) re-pushes once, while what really catches the change is the per-mutation versions, which do not depend on the context.
**Acceptance evidence** (added this commit):
- `MG_Test/Wire/TwinOwnershipTest.cpp`, 5 cases, driving the **real** twin tables directly (no EGL, no wire): two nonshared groups in one session—same-named handles are two twins that do not overwrite each other; two contexts of one group resolve **the same** twin (the twin-layer equivalent of driver-level sharing—a twin is the object that holds the driver id); one session's `DropBucketsOfSession` takes only its own twins and leaves the neighbor session's untouched; a thread that belongs to no session still gets the process-level table and does not cross with the sessions'. A sixth case repeats the first three on the `TwinRegistry` template (the six registries are the same shape) and also pins the per-bucket generation gate.
**Negative control** (mandatory): change `SlotTableRegistry::ForCallingThread` to always answer `{0,0}` (i.e. restore the pre-S6 process-level table), and 4 of the 5 cases **go red**; `TwoContextsOfOneGroupShareTheGroupsTwins` stays green—with one key the two shapes answer the same, which is why that case asserts "sharing must happen" rather than "two buckets exist". Switch back and all are green.
- The existing set does not regress: the 103 cases this slice names (`EmbeddedServerTest`, `ServerDisplayTest`, `UnixSupervisor`, `InProcessServer`, `SupervisorChildren`, `ServerLoopTest`, `ServerLoopEglTest`, `MultiSessionFixture`, `PeerLatch`, `SurfaceControlFrameTest`, `ContextStateOwnershipTest`, `ApplierOwnershipTest`) are all green, and two real-rendering cases of `MultiSessionFixture` now run on session-isolated twin tables.
- **Name-by-name comparison of the full host ctest against the baseline** (the same method as S5: `git stash push -u -- MobileGL docs` away this slice, rebuild, run the full suite and keep the failure list; restore and run again; `comm` the two lists by **case name** rather than by line number—this slice added a test file, so line numbers would shift throughout):
| | Count |
|---|---|
| Baseline failures | 277 |
| This slice's failures | 278 |
| **New failures in this slice** | **0** |
| Baseline failures that this slice does not fail | 0 |
The difference between the two lists is exactly one name: `LogForwardChannel.APeerThatStopsReadingCostsWarnLinesNotTheCallersTime`, which **is also flaky on the baseline**—run alone repeatedly on the same machine, the baseline failed 4/60 and this slice 2/40, with identical failing assertions on both sides (the `Dropped` line count vs `counters.lossyDropped` mismatch at `LogForwardTest.cpp:446`, and `counters.notices == 2` instead of 1 at `:448`), a race in that case's own log channel: it makes the peer stop reading and then asserts "only one disconnect notice is sent", while the notice itself is sent by a background thread according to the queue level. That case builds no backend and touches no twin; it is unrelated to this slice and is recorded as a flake under the existing baseline wording. The remaining failures all fall in the glslang / shader compilation family (`ProgramTest` 80, `ProgramInterfaceTest` 32, `AsyncLinkTest` 17, `GlslangCaptureProbeTest` 15, `ShaderCompileAdoptionTest` 14…), consistent with the existing baseline of the dirty `3rdparty/glslang` submodule.
**What S6 explicitly did not do (the next layer's debt)**:
- **The unit shadows are still process-level**: `g_activeTextureUnit`, `g_boundTexturesCache`, `g_boundSamplersCache` and the sampler cache (`Managers.cpp:11031-11032` etc.) are the other half that §3 item 3 leaves to P14b/c. They **neither conflict with nor complement** the twin keying: the caches compare pointer identity, so twins separated by group only make "the other group's twin" compare unequal and rebind (the safe direction); the real residual problem is "the same twin is hit by the cache after a native context switch and the bind is skipped", which already existed when S4 made the native context per-context and belongs to the same debt.
- **The driver-level `glIsBuffer` probe is still unsolved** (the same thing S4/S5 recorded). S6 therefore did not take the "ask the real driver" route, and instead asserted identity at the twin layer under the allowance of the S5 report: a twin is the object holding the driver id, so two contexts getting different twins means two driver objects. Making it driver-level evidence requires first solving the probe problem from the S4 report ("`glIsBuffer` returns false right after `glGenBuffers` in the same context").
- **`g_backendContextGeneration`/`g_syncContextGeneration` are still process-level**, as listed in the S4/S5 sections.
- **`MGPipeApplierState`'s two spellings (`Objects.X` and the table names) are still not converged**; S5 said "the chance to rename comes in the same cut as the twin registry", and S6 chose not to touch it (that cut's value is tidiness, while S6's diff already changes the behavior of 8 tables; bundling a rename in would only add risk).
- **Wire item 1's per-record `ContextSlot`** is still not done.
## Phases and acceptance
| Phase | Content | Acceptance |
|---|---|---|
| P14a | wire context identity + frontend GLContext/ShareGroupState split + CreateContext/DestroyContext on the wire | shared contexts access the same buffer/texture; nonshared same-named resources are isolated; per-context viewport/FBO/bindings/error are independent; state survives a context handover across threads |
| P14b | backend per-context native tuple + surface lifetime | pbuffer→window→pbuffer loses no resources; the Qt offscreen probe + real-window context sequence does not lose the first window's content |
| P14c | server multiple sessions in one process (registry, per-session applier/apply-thread/reverse routing), removing the fork-worker dependency | two sessions with the same handle values are isolated and can be closed independently; one session crashing does not drag the other down; the in-process server renders two concurrent clients without cross talk |
| P14d | anland switches to the unified embedded server | KWin (OnScreen session) + Konsole (Offscreen session) on the same server, both presented on screen; see the acceptance chain in the handover document |
Every phase passes the existing gates: the full host ctest, `split_coverage.py`'s three arms, the unchanged monolith G1 symbols; in a phase with wire changes both ends rebuild with the same stamp. Multi-context semantics must also hold on the monolith path (`MOBILEGL_PIPE_PUSH=0`)—before and after the split both ends share one `MG_State`.
## Explicitly not done
- Sharing GL objects across sessions (EGL semantics do not allow sharing across connections anyway; if needed, a separate import design).
- per-context ring (see the trade-off in wire 1).
- Putting container objects such as FBO/VAO into the share group.
- Keeping `--serve --max-sessions`'s fork dispatch as any acceptance path; the tool itself may stay for debugging, but anland and multi-session acceptance must not depend on it.