Bridge Remote speech through bounded reader assembly
This commit is contained in:
1 parent
703d44029c
commit
393ff90f00
12 files changed
+883
-86
No files matched your search
@@ -172,6 +172,40 @@ limits. See [the exact scope and checks](remote/speech.md). The speech worker
|
||||
and coordinator are not connected; the source command remains relay-only.
|
||||
Audible speech, real interoperability and the remaining release gates are open.
|
||||
|
||||
Thirteenth implementation increment (2026-11-04): the external coordinator now
|
||||
connects typed relay speech to reader presentation IPC and matching controlled
|
||||
reader output events to relay writes. Heartbeat/presentation/close share one
|
||||
sequenced owner; speech queues are bounded by 64 items and 256 KiB, including
|
||||
in-flight work. Split incoming utterances are admitted together or rejected
|
||||
before any prefix enters the child queue. Stale/pre-peer output is discarded;
|
||||
revocation and overflow clear queues and cancel the socket independently of
|
||||
blocked reader calls or relay writes. Both-role SDK child-process fixtures cover
|
||||
the forms/storage/TLS/speech path. See [the scope and verification](remote/speech.md).
|
||||
The full Remote race suite, ten repetitions of the focused speech/SDK-process
|
||||
race cases and repository `make check` passed, including existing Tentacle host
|
||||
workflows and reader Remote consent/typed-speech tests. No reader source changed.
|
||||
Production output observation, delivery policy,
|
||||
atomic split-utterance delivery and audible speech remain pending. A reader with
|
||||
no speech owner rejects presentation and Remote closes the lease; connection UI
|
||||
warnings remain. Phase B/C and all live release gates remain open.
|
||||
|
||||
Fourteenth implementation increment (2026-11-04): split relay utterances now
|
||||
assemble atomically in the reader before speech-owner admission. Optional
|
||||
utterance/final IPC metadata preserves the shared operation sequence, permits
|
||||
heartbeats during assembly and rejects interleaving, replay and priority changes.
|
||||
The reader independently bounds staged, queued and in-flight speech to 64 frames
|
||||
and 256 KiB; owner release is idempotent and scoped to its original lease.
|
||||
Overflow and lease retirement discard incomplete work without exposing a prefix.
|
||||
Both SDKs provide matching presentation validators. The actual source-built
|
||||
command/private-relay/reader-host fixture checks long escaped multilingual speech
|
||||
arriving as one complete owner delivery. See [the contract and checks](remote/speech.md).
|
||||
The full Remote race suite, reader wire/host/both-SDK race suites (host: about
|
||||
127 seconds), focused real-host connection race tests, focused vet and repository
|
||||
`make check` passed.
|
||||
Production output observation, delivery-time arbitration, remote cancellation
|
||||
ownership and audible speech remain pending. No installed or active reader was
|
||||
replaced; Phase B/C and all live release gates remain open.
|
||||
|
||||
## 1. Intended result and recommended approach
|
||||
|
||||
Build a native Go Tentacle named **Remote**, with package ID `remote`, in this
|
||||
@@ -719,8 +753,9 @@ do not claim them from a design diagram.
|
||||
limits in the reader repository. Runtime Remote code stays external.
|
||||
- [ ] Implement and document typed desktop services and their delivery-time checks.
|
||||
Typed speech validation, lease-bound output events, an explicit reader-owned
|
||||
incoming mailbox and both SDKs now have private coverage. The production speech
|
||||
owner and delivery-time output policy remain pending; see [speech.md](remote/speech.md).
|
||||
incoming mailbox and both SDKs now have private coverage. The external speech
|
||||
coordinator is connected; the production reader speech owner and delivery-time
|
||||
output policy remain pending; see [speech.md](remote/speech.md).
|
||||
|
||||
Exit: permission denials, timeout/overflow, stale epochs and process failures are
|
||||
tested; existing Tentacles still install, register, run, disable and update.
|
||||
@@ -741,8 +776,9 @@ tested; existing Tentacles still install, register, run, disable and update.
|
||||
- [ ] Add core output observation and incoming remote presentation with origin
|
||||
tracking, cancel order and lock/handoff revocation.
|
||||
The [typed speech transport and relay conversion](remote/speech.md) prerequisite
|
||||
now exists, preserving whitespace and UTF-8 across bounded IPC frames. The
|
||||
source command remains relay-only until the worker/coordinator are connected.
|
||||
now connects to the external coordinator, preserving whitespace and UTF-8
|
||||
across bounded IPC frames. Production reader output ownership and audible
|
||||
speech remain pending; connection controls retain their relay-testing scope.
|
||||
- [ ] Demonstrate controlled Cthulhu speech to NVDA and NVDA speech to controlling
|
||||
Cthulhu, then Cthulhu-to-Cthulhu. Verify read-all, spelling and ordinary stop.
|
||||
|
||||
|
||||
+5
-4
@@ -9,8 +9,9 @@ See [the source command and physical-input checks](command.md).
|
||||
|
||||
Implemented:
|
||||
|
||||
- Typed speech conversion and matching reader IPC validators/mailbox, with
|
||||
private Go/Python host coverage. This is transport only; production speech
|
||||
- Typed speech conversion, coordinator queues, atomic reader assembly and matching reader IPC
|
||||
validators/mailbox, with both-role SDK-process/private-TLS coverage and
|
||||
Go/Python host coverage. This is transport only; production speech
|
||||
delivery/export is still pending. See [speech.md](speech.md).
|
||||
- Bounded newline JSON framing, duplicate-key and collection validation, and
|
||||
typed speech, keyboard, membership, clipboard and Braille decoding.
|
||||
@@ -26,8 +27,8 @@ Implemented:
|
||||
Storage does no network I/O; see [storage.md](storage.md).
|
||||
- A coordinator using public Go SDK leases and lifecycle events for explicit
|
||||
connection attempts, heartbeats, revocation and ordered failure cleanup.
|
||||
It requires reader-issued approval, never retries and performs no desktop
|
||||
effects; see [lifecycle.md](lifecycle.md).
|
||||
It requires reader-issued approval, never retries and bridges typed speech
|
||||
IPC; the production reader speech owner is pending. See [lifecycle.md](lifecycle.md).
|
||||
- Explicit certificate inspection with no application data, fingerprint review
|
||||
with Copy/Trust once/Cancel, and masked Remember/Forget key form handlers.
|
||||
A single library connection workflow now combines them with explicit saved-key
|
||||
|
||||
@@ -6,6 +6,12 @@ consent and the existing connection workflow. It is **relay testing only**:
|
||||
there is no speech delivery, keyboard forwarding/injection, clipboard transfer
|
||||
or Braille service. There is still no installable manifest or catalog entry.
|
||||
|
||||
The subsequent [speech coordinator increment](speech.md) now connects typed
|
||||
relay speech to presentation IPC and reader output events to relay writes.
|
||||
Production reader speech ownership is still pending, so these controls retain
|
||||
their relay-testing warnings. Receiving speech with no reader owner closes the
|
||||
connection and lease; it does not enable audible delivery.
|
||||
|
||||
Base revisions checked against maintained upstreams on 2026-11-04: reader
|
||||
`testing` at `4cf3335`, Tentacles `master` at `0c74038`. No installed reader or
|
||||
active desktop session is changed by building or running the private tests.
|
||||
|
||||
@@ -11,11 +11,14 @@ real-host relay integration. Earlier increment descriptions below are historical
|
||||
connection registration is implemented, while physical-source approval and
|
||||
desktop services remain pending.
|
||||
|
||||
The next increment adds [typed speech IPC and relay conversion](speech.md).
|
||||
Subsequent increments add [typed speech IPC and relay conversion](speech.md).
|
||||
The reader has an explicit bounded speech mailbox and lease-bound output
|
||||
events, exercised through both SDKs. No production output owner is connected;
|
||||
the command remains relay-only. Policy-resolved observation, remote speech
|
||||
delivery, coordinator wiring and live speech acceptance are still open.
|
||||
events, exercised through both SDKs. The external coordinator now joins those
|
||||
interfaces to relay speech, with ordered calls and bounded cancellable queues.
|
||||
Split utterances now reach the reader owner as one complete assembly, with
|
||||
independent reader frame/byte limits that include work in flight.
|
||||
No production reader output owner is connected; policy-resolved observation,
|
||||
remote speech delivery and live speech acceptance remain open.
|
||||
|
||||
## Confirmed reader boundaries
|
||||
|
||||
|
||||
+20
-15
@@ -2,17 +2,19 @@
|
||||
|
||||
Current integration: [the source command](command.md) now supplies reader-owned
|
||||
consent and connection controls. The original library increment below predates
|
||||
that wiring. There are still no desktop effects or installable Remote package.
|
||||
that wiring. The [speech transport integration](speech.md) now bridges typed
|
||||
presentation/output IPC with bounded queues. Production reader speech ownership
|
||||
and an installable Remote package remain pending.
|
||||
|
||||
Implemented as a source-library increment on 2026-11-03, based on Tentacles
|
||||
`63e84e9` and the public Go SDK in reader `573d15d`. The Tentacles branch matched
|
||||
`origin/master` after fetch. The reader revision was inspected locally; its
|
||||
remote branch was not refreshed for this increment. No reader code changed.
|
||||
|
||||
`src/coordinator.go` joins the existing relay transport and membership machine
|
||||
to the reader's protocol 1.1 lifecycle API. It supplies no connection dialog,
|
||||
desktop effects, executable or package. There is still no production issuer of
|
||||
the reader approvals it requires.
|
||||
`src/coordinator.go` joins relay transport and membership to the reader's
|
||||
protocol 1.1 lifecycle API. The original increment supplied only this library;
|
||||
the source command now provides the executable, connection controls and core
|
||||
consent described above.
|
||||
|
||||
## Ownership and explicit connection
|
||||
|
||||
@@ -45,23 +47,26 @@ must have the expected epoch and a 32-character identifier. Reader-facing
|
||||
|
||||
Snapshots distinguish opening a lease, connecting, waiting for a peer, and ready
|
||||
relay membership. **Ready means one opposite-role relay peer, not active desktop
|
||||
control.** Known desktop payloads are validated, counted and discarded without
|
||||
retention. No output/input queue or effect callback is exposed by this increment.
|
||||
control.** Typed speech uses the bounded queues and role/grant checks documented
|
||||
in [speech.md](speech.md). Other known desktop payloads are validated, counted
|
||||
and discarded without retention. No keyboard/Braille/clipboard effect is exposed.
|
||||
|
||||
## Liveness and teardown
|
||||
|
||||
The worker sends `remote.heartbeat` each second, including while TLS/join is
|
||||
pending. Heartbeats and the final close use strictly increasing per-lease
|
||||
sequence numbers. The following stop the relay lifetime:
|
||||
sequence numbers shared with presentation calls. The following stop the relay lifetime:
|
||||
|
||||
- Explicit Disconnect, coordinator close or parent-context cancellation.
|
||||
- A matching-epoch `remote.revoked`, a replacement action or SDK event EOF.
|
||||
- Heartbeat failure, TLS/join/read failure, malformed relay messages, invalid
|
||||
role/origin or any terminal membership change.
|
||||
- Speech queue overflow, reader presentation failure or relay output failure.
|
||||
|
||||
The socket context is cancelled immediately and peer readiness is cleared before
|
||||
waiting for cleanup RPCs. The worker finishes an in-flight heartbeat, then requests
|
||||
`remote.close`; each call has a two-second deadline. It deliberately does not
|
||||
waiting for cleanup RPCs. Pending speech is drained immediately. Teardown waits
|
||||
for the operation and relay-output workers, then requests `remote.close`; each
|
||||
reader call has a two-second deadline. It deliberately does not
|
||||
cancel a healthy SDK call during ordinary Disconnect: SDK call cancellation
|
||||
retires the entire Tentacle process session. Reader-side lease expiry remains
|
||||
independent if communication fails. These bounds are not physical-key recovery
|
||||
@@ -105,10 +110,10 @@ invocation for Hello World, Wormhole and Battery Status. Review the new source
|
||||
and these contracts before submission; neither command installs or replaces the
|
||||
active reader.
|
||||
|
||||
Next: production local consent and lock/handoff integration, endpoint/role
|
||||
selection and registration of the library forms, persistent-pin UI, typed reader
|
||||
output/presentation services and their effect
|
||||
ownership. Xorg provenance/collision safety and virtual/raw Braille remain open.
|
||||
There is no new live workflow to test yet. Audible speech, physical input and
|
||||
Next: production reader output/presentation ownership and delivery policy,
|
||||
including applying priority once to assembled utterances and protecting local status. Xorg
|
||||
provenance/collision safety and virtual/raw Braille remain open. The source
|
||||
command's physical-input procedure remains in [command.md](command.md).
|
||||
Audible speech, physical input and
|
||||
Braille, real NVDA/Orca sessions and installed-package behavior remain separate
|
||||
acceptance gates in the parent plan.
|
||||
+4
-3
@@ -110,9 +110,10 @@ speech/cancel and key transitions before submitting them.
|
||||
The [library coordinator](lifecycle.md) now closes the transport on terminal
|
||||
session errors, requests core lease closure on failure and rejects cancelled
|
||||
worker results. Private fixtures test those layers together using the public Go
|
||||
SDK. There is still no running Tentacle or production consent issuer. Desktop
|
||||
payloads are counted and discarded; transport write capacity does not replace
|
||||
the proposed separate host control/input/output queues.
|
||||
SDK. The source command now supplies production consent wiring. Typed speech
|
||||
uses the [coordinator's bounded speech bridge](speech.md); other desktop payloads
|
||||
are counted and discarded. Transport write capacity does not replace separate
|
||||
host control/input/output queues or production reader output ownership.
|
||||
|
||||
## Timeouts, trust and liveness
|
||||
|
||||
|
||||
+76
-16
@@ -1,9 +1,18 @@
|
||||
# Typed speech transport and relay conversion
|
||||
|
||||
Remote now has a tested conversion boundary between NVDA protocol-v2 speech and
|
||||
the matching experimental reader's typed speech IPC. This is a prerequisite for
|
||||
speech integration. The source command still discards desktop payloads and does
|
||||
not call `remote.present` or send reader output to the relay.
|
||||
Remote now connects NVDA protocol-v2 speech conversion to the matching
|
||||
experimental reader's typed speech IPC. Controller sessions call `remote.present`;
|
||||
controlled sessions send matching `remote.output` events to the relay. The
|
||||
production reader has no speech worker or output observer connected to these
|
||||
interfaces yet, so the command remains a relay-testing tool with no audible
|
||||
speech-service claim. A reader without a presentation owner rejects incoming
|
||||
speech; Remote closes that connection and its lease instead of silently dropping
|
||||
the error. No installed or active reader was changed.
|
||||
|
||||
The coordinator and assembly increments were based on Tentacles `703d440` (`master`) and reader
|
||||
`9e15f86` (`testing`), both confirmed current with `git pull --ff-only` on
|
||||
2026-11-04. The assembly increment changes reader wire/host code and both SDKs
|
||||
as well as the external coordinator. No production speech worker is enabled.
|
||||
|
||||
`src/speech_bridge.go` converts speech, cancel and pause messages. It preserves
|
||||
text fragments and whitespace, resolved spelling/language state, end-utterance
|
||||
@@ -17,38 +26,89 @@ Outbound conversion emits NVDA command arrays, resets character/language state
|
||||
when necessary, and leaves origin IDs to the relay. It validates every payload
|
||||
through the same typed reader schema before serialization.
|
||||
|
||||
These helpers operate on data only. The future coordinator must check relay
|
||||
membership before conversion, serialize presentation/heartbeat/close operation
|
||||
sequences, recheck reader lease/epoch and peer readiness before each delivery or
|
||||
send, and stop work on revocation. Split frames retain priority metadata; atomic
|
||||
utterance admission and priority/cancel semantics still require reader-owner
|
||||
integration. No audible pause/resume or priority fidelity is established here.
|
||||
`src/speech_stream.go` owns per-attempt speech queues. The relay reader checks
|
||||
membership, peer origin and direction before conversion. Incoming speech requires
|
||||
the controller role and `remote-present`; observed output requires the controlled
|
||||
role, `output-observe`, and the exact current lease/epoch. Events received while
|
||||
waiting for a peer are discarded rather than replayed to a later helper. Received
|
||||
speech never becomes an observed-output event in the Tentacle.
|
||||
|
||||
One worker serializes presentation and heartbeat calls using their shared
|
||||
monotonic operation sequence. It checks a due heartbeat before each presentation,
|
||||
including split frames; heartbeats also run during dial/join. A separate worker
|
||||
serializes relay output in SDK event order. The SDK event consumer never waits
|
||||
for relay writes or reader calls. Both workers recheck the current attempt,
|
||||
cancellation and peer readiness before handing off work. Core remains responsible
|
||||
for checking its lease and output/security policy at actual speech delivery.
|
||||
|
||||
Queues admit at most 64 items and 256 KiB of serialized speech across both
|
||||
directions, including work in flight. A split incoming utterance reserves all
|
||||
of its frames together or admits none. Overflow stops the connection; no cancel
|
||||
is selectively dropped. Revocation, replacement, disconnect, SDK EOF, membership
|
||||
failure and worker failure cancel the socket and clear pending speech. Teardown
|
||||
waits for both workers before the final sequenced close. An in-flight reader
|
||||
call retains its independent two-second deadline, so ordinary disconnect does
|
||||
not cancel a healthy SDK session. In-flight accepted work still needs the
|
||||
reader's delivery-time context check; closing a queue cannot undo delivered audio.
|
||||
|
||||
Split utterances now retain one `utterance` identifier across their reader
|
||||
calls, equal to the first fragment's operation sequence; only the last sets
|
||||
`final: true`. Heartbeats may occur between fragments. Core assembles the whole
|
||||
utterance before admitting one owner delivery, with a single priority and the
|
||||
original fragment/utterance boundaries. A failed or revoked assembly exposes no
|
||||
prefix to the owner. Single-frame speech, cancel and pause keep their original
|
||||
single-call representation. These fields belong only to reader IPC; NVDA relay
|
||||
frames are unchanged.
|
||||
|
||||
The reader independently enforces 64 frames and 256 KiB across staged, queued
|
||||
and in-flight speech. Its owner must call the delivery's idempotent `Release`
|
||||
after delivery/discard; stale releases cannot affect replacement leases. Byte
|
||||
or frame overflow revokes the lease and drops the assembly. The future speech
|
||||
owner still needs delivery-time policy, local priority and remote cancellation
|
||||
ownership. Atomic assembly is not backend completion or audible delivery. No
|
||||
audible pause/resume or priority fidelity is established.
|
||||
|
||||
The matching reader adds a disabled-by-default incoming speech mailbox, typed
|
||||
Go/Python validators and `remote.output` events. See
|
||||
[its precise contract](../../cthulhu/docs/tentacle-remote-speech.md). These SDK
|
||||
additions are prerequisites for building this increment; use the matching reader
|
||||
source, not an older release. The existing connection command remains the only
|
||||
production entry point and makes no speech-service claim.
|
||||
source, not an older release. Production output ownership and origin filtering
|
||||
remain reader responsibilities.
|
||||
|
||||
Verification:
|
||||
|
||||
```sh
|
||||
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1
|
||||
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1 -timeout=90s
|
||||
make check GOPROXY=off
|
||||
```
|
||||
|
||||
Both passed for the assembly increment. Reader wire/host/both-SDK race suites
|
||||
also passed with a 240-second timeout (the host suite took about 127 seconds),
|
||||
as did the focused real-host connection race tests and affected-package vet.
|
||||
|
||||
Conversion tests exercise spelling/language reset, cancel/pause, priorities,
|
||||
unsupported commands, whitespace and long escaped multilingual text. Reader
|
||||
tests send speech through real Go/Python SDK child processes and exercise stale
|
||||
leases, replay, absent owners, origin restrictions and overflow cancellation.
|
||||
The repository check also runs the reader's Remote speech host/SDK tests.
|
||||
Coordinator tests cover FIFO split/cancel/pause, shared heartbeat/present/close
|
||||
sequences, lease/grant/role checks, pre-peer output, stale output, unavailable
|
||||
owners, whole-utterance admission bounds and queue cleanup. A blocked reader
|
||||
presentation and a blocked relay write establish that lifecycle cancellation
|
||||
can stop the socket without waiting for either effect path. Both-role child
|
||||
process fixtures exercise actual Go SDK framing, connection forms, storage and
|
||||
private TLS relay speech together. The reader's real-host/private-relay fixture
|
||||
now passes long escaped multilingual speech from the source-built command into
|
||||
one complete test-owner delivery. Reader SDK-process tests also establish no
|
||||
prefix before finalization, interleaving/priority/replay rejection, heartbeat
|
||||
progress, assembly retirement, both budget limits and idempotent/stale release.
|
||||
The repository check runs these reader Remote speech and connection tests.
|
||||
Existing greeting, Wormhole, Battery Status and connection/consent checks remain
|
||||
regressions. These checks produce no audible speech and establish no physical
|
||||
keyboard, Braille or real NVDA/Orca interoperability acceptance.
|
||||
|
||||
After the worker/coordinator integration, test ordinary reading, spelling,
|
||||
After reader-owner integration, test ordinary reading, spelling,
|
||||
read-all, key echo, stop speech and local status in both roles. Then test lock,
|
||||
handoff, disconnect and peer loss for stale output and loops, using disposable
|
||||
desktops before testing installed releases. Those workflows cannot be accepted
|
||||
from this transport-only increment.
|
||||
from this transport increment. Keep connection UI warnings until production
|
||||
speech ownership and acceptance are established.
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
)
|
||||
|
||||
// A test-only executable peer. The parent supplies synthetic approval over real
|
||||
// SDK process pipes; no production command can instantiate this workflow yet.
|
||||
// SDK process pipes. Production reader consent is tested separately.
|
||||
func TestConnectionWorkflowSDKPeer(t *testing.T) {
|
||||
if os.Args[len(os.Args)-1] != "remote-workflow-peer" {
|
||||
return
|
||||
@@ -85,9 +85,23 @@ func TestConnectionWorkflowSDKPeer(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
for _, role := range []string{"controller", "controlled"} {
|
||||
t.Run(role, func(t *testing.T) { testConnectionWorkflowPublicSDKProcess(t, role) })
|
||||
}
|
||||
}
|
||||
|
||||
func testConnectionWorkflowPublicSDKProcess(t *testing.T, role string) {
|
||||
wireRole, peerRole, grant := controller, "slave", "remote-present"
|
||||
if role == "controlled" {
|
||||
wireRole, peerRole, grant = controlled, "master", "output-observe"
|
||||
}
|
||||
certificate, _ := testCertificate(t, false)
|
||||
probed := make(chan struct{})
|
||||
joined := make(chan struct{})
|
||||
relaySpeech := make(chan message, 1)
|
||||
requestSpeech := make(chan struct{})
|
||||
var requestOnce sync.Once
|
||||
t.Cleanup(func() { requestOnce.Do(func() { close(requestSpeech) }) })
|
||||
var serverMu sync.Mutex
|
||||
connections := 0
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
@@ -103,11 +117,27 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
close(probed)
|
||||
return
|
||||
}
|
||||
if relayHandshake(t, connection, controller) == nil {
|
||||
reader := relayHandshake(t, connection, wireRole)
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
_, _ = io.WriteString(connection, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"`+peerRole+`"}]}`+"\n")
|
||||
close(joined)
|
||||
if role == "controller" {
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"speak\",\"origin\":7,\"sequence\":[\" fixture speech \"],\"priority\":1}\n")
|
||||
} else {
|
||||
<-requestSpeech
|
||||
frame, err := readFrame(reader)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
value, err := decodeMessage(frame)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
relaySpeech <- value
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, connection)
|
||||
})
|
||||
testBinary, err := os.Executable()
|
||||
@@ -173,12 +203,18 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
result := any(struct{}{})
|
||||
if frame.Method == "remote.open" {
|
||||
var open sdk.RemoteOpen
|
||||
if json.Unmarshal(frame.Params, &open) != nil || open.Epoch != 1 || open.Role != "controller" {
|
||||
if json.Unmarshal(frame.Params, &open) != nil || open.Epoch != 1 || open.Role != role {
|
||||
t.Error("invalid SDK lease request")
|
||||
return
|
||||
}
|
||||
result = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: open.Epoch}
|
||||
}
|
||||
if frame.Method == "remote.present" {
|
||||
var presentation sdk.RemotePresentation
|
||||
if json.Unmarshal(frame.Params, &presentation) != nil || presentation.Lease != strings.Repeat("b", 32) || presentation.Epoch != 1 || presentation.Sequence == 0 || presentation.Speech.Priority != 1 || len(presentation.Speech.Parts) != 1 || presentation.Speech.Parts[0].Text != " fixture speech " {
|
||||
t.Error("SDK changed incoming speech")
|
||||
}
|
||||
}
|
||||
if send(map[string]any{"jsonrpc": "2.0", "id": frame.ID, "result": result}) != nil {
|
||||
return
|
||||
}
|
||||
@@ -200,7 +236,7 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "id": "1", "method": "initialize", "params": map[string]any{
|
||||
"protocol": map[string]int{"major": 1, "minor": 1}, "session": "fixture",
|
||||
"apis": []string{"commands", "presentation", "interaction", "session-events", "remote-access"},
|
||||
"capabilities": []string{"presentation", "interaction", "remote-present"},
|
||||
"capabilities": []string{"presentation", "interaction", grant},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -214,7 +250,7 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{
|
||||
Kind: "remote.action", Sequence: 1, Epoch: 1, Action: strings.Repeat("a", 32), Role: "controller", Grants: []string{"remote-present"},
|
||||
Kind: "remote.action", Sequence: 1, Epoch: 1, Action: strings.Repeat("a", 32), Role: role, Grants: []string{grant},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -259,16 +295,72 @@ func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
}
|
||||
invoke("remote-connection", "connect", "")
|
||||
awaitDone(t, joined)
|
||||
invoke("remote-connection", "disconnect", "")
|
||||
for _, expected := range []string{"remote.open", "remote.close"} {
|
||||
expectedCalls := []string{"remote.open", "remote.present"}
|
||||
if role == "controlled" {
|
||||
expectedCalls = []string{"remote.open"}
|
||||
ready := false
|
||||
for !ready {
|
||||
status := invoke("remote-connection", "refresh", "")
|
||||
if status.Form == nil {
|
||||
t.Fatal("missing connection status")
|
||||
}
|
||||
for _, element := range status.Form.Elements {
|
||||
for _, item := range element.Items {
|
||||
if item.ID == "status" && item.Label == connection_status_text(connectionStatus{state: "ready"}) {
|
||||
ready = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
t.Fatal("connection never became ready")
|
||||
}
|
||||
}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{
|
||||
Kind: "remote.output", Sequence: 2, Epoch: 1, Lease: strings.Repeat("b", 32),
|
||||
Speech: &sdk.RemoteSpeech{Kind: "speak", Priority: 1, Parts: []sdk.RemoteSpeechPart{{Text: " fixture speech "}}},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requestOnce.Do(func() { close(requestSpeech) })
|
||||
select {
|
||||
case value := <-relaySpeech:
|
||||
if value.kind != "speak" || value.origin != 0 || value.payload.(speech).parts[0].text != " fixture speech " {
|
||||
t.Fatal("SDK changed observed speech")
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("SDK did not forward observed speech")
|
||||
}
|
||||
}
|
||||
for _, expected := range expectedCalls {
|
||||
for {
|
||||
select {
|
||||
case method := <-leaseCalls:
|
||||
if method == "remote.heartbeat" {
|
||||
continue
|
||||
}
|
||||
if method != expected {
|
||||
t.Fatal("unexpected lease operation", method)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("missing lease operation", expected)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
invoke("remote-connection", "disconnect", "")
|
||||
for {
|
||||
select {
|
||||
case method := <-leaseCalls:
|
||||
if method == "remote.heartbeat" {
|
||||
continue
|
||||
}
|
||||
if method != "remote.close" {
|
||||
t.Fatal("missing ordered close", method)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("missing close")
|
||||
}
|
||||
break
|
||||
}
|
||||
if result := invoke("remote-connection", "cancel", ""); !result.Done {
|
||||
t.Fatal("SDK did not close the workflow")
|
||||
|
||||
+42
-31
@@ -37,10 +37,11 @@ type connectionAttempt struct {
|
||||
done chan struct{}
|
||||
epoch uint64
|
||||
err error // Protected by coordinator.mu.
|
||||
speech *speechStream // Protected by coordinator.mu; nil until open succeeds.
|
||||
}
|
||||
|
||||
// coordinator joins reader consent and relay lifetime; it performs no desktop
|
||||
// effects. A fresh core action AND an explicit connect call are required for
|
||||
// coordinator joins reader consent, typed speech IPC and relay lifetime.
|
||||
// A fresh core action AND an explicit connect call are required for
|
||||
// every attempt. It never loads credentials, saves trust, or retries a network.
|
||||
type coordinator struct {
|
||||
client sessionClient
|
||||
@@ -109,6 +110,8 @@ func (c *coordinator) read_events() {
|
||||
if c.active != nil && event.Epoch == c.active.epoch {
|
||||
c.stop_locked(errLease)
|
||||
}
|
||||
case "remote.output":
|
||||
c.observe_locked(event)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
@@ -183,6 +186,9 @@ func (c *coordinator) stop_locked(err error) {
|
||||
}
|
||||
c.active.cancel() // Socket cancellation never waits for reader RPC cleanup.
|
||||
c.status.state, c.status.peer = "stopping", 0
|
||||
if c.active.speech != nil {
|
||||
c.active.speech.drain()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,8 +253,8 @@ func (c *coordinator) call(method string, params, result any) error {
|
||||
func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e endpoint, key string) {
|
||||
var lease sdk.RemoteLease
|
||||
var conn *relayConn
|
||||
var sequence uint64
|
||||
var heartbeatDone chan struct{}
|
||||
var stream *speechStream
|
||||
var operationsDone, outputDone chan struct{}
|
||||
var failure error
|
||||
defer func() {
|
||||
// Stop relay and heartbeat admission before serializing the final close.
|
||||
@@ -258,12 +264,18 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
if conn != nil {
|
||||
conn.close()
|
||||
}
|
||||
if heartbeatDone != nil {
|
||||
<-heartbeatDone
|
||||
if operationsDone != nil {
|
||||
<-operationsDone
|
||||
}
|
||||
if outputDone != nil {
|
||||
<-outputDone
|
||||
}
|
||||
closeFailed := false
|
||||
if lease.Lease != "" {
|
||||
sequence++
|
||||
sequence := uint64(1)
|
||||
if stream != nil {
|
||||
sequence = stream.sequence + 1
|
||||
}
|
||||
closeFailed = c.call("remote.close", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
@@ -312,28 +324,14 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
c.status.state = "connecting"
|
||||
}
|
||||
c.mu.Unlock()
|
||||
heartbeatDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(heartbeatDone)
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if a.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
sequence++
|
||||
if c.call("remote.heartbeat", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil {
|
||||
stream = newSpeechStream(lease, approval)
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
a.speech = stream
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
operationsDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(operationsDone)
|
||||
c.speech_operations(a, stream)
|
||||
}()
|
||||
var joined message
|
||||
conn, joined, failure = connect(a.ctx, e, r, key)
|
||||
@@ -347,6 +345,11 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
if _, failure = s.accept(a.epoch, joined); failure != nil || !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
outputDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(outputDone)
|
||||
c.speech_output(a, stream, conn)
|
||||
}()
|
||||
for a.ctx.Err() == nil {
|
||||
m, err := conn.read()
|
||||
if err != nil {
|
||||
@@ -360,13 +363,21 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
|
||||
failure = err
|
||||
return
|
||||
}
|
||||
// Desktop services are not implemented. Retain no payload and expose no
|
||||
// effect queue which could be mistaken for delivery-time authorization.
|
||||
if accepted && s.ignored != ^uint64(0) {
|
||||
s.ignored++
|
||||
if !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
if accepted {
|
||||
handled, err := c.receive_speech(a, stream, m)
|
||||
if err != nil {
|
||||
failure = err
|
||||
return
|
||||
}
|
||||
if !handled && s.ignored != ^uint64(0) {
|
||||
s.ignored++
|
||||
if !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,7 +171,7 @@ func TestCoordinatorMembershipFailureAndExplicitReconnect(t *testing.T) {
|
||||
depart := make(chan struct{})
|
||||
var once sync.Once
|
||||
t.Cleanup(func() { once.Do(func() { close(depart) }) })
|
||||
r, peerRole, effect := controller, "slave", `{"type":"speak","origin":7,"sequence":["private fixture"]}`
|
||||
r, peerRole, effect := controller, "slave", `{"type":"display","origin":7,"cells":[0,255]}`
|
||||
if roleName == "controlled" {
|
||||
r, peerRole, effect = controlled, "master", `{"type":"key","origin":7,"vk_code":65,"extended":false,"pressed":true}`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
const maxSpeechItems = 64
|
||||
|
||||
type speechItem struct {
|
||||
speech sdk.RemoteSpeech
|
||||
bytes int
|
||||
batch bool
|
||||
first bool
|
||||
final bool
|
||||
}
|
||||
|
||||
// One stream belongs to one attempt and lease. The coordinator mutex owns
|
||||
// admission/accounting, including in-flight work. Only speech_operations owns
|
||||
// sequence; teardown reads it after that worker finishes.
|
||||
type speechStream struct {
|
||||
lease sdk.RemoteLease
|
||||
role string
|
||||
grants []string
|
||||
incoming chan speechItem
|
||||
outgoing chan []byte
|
||||
items int
|
||||
bytes int
|
||||
sequence uint64
|
||||
}
|
||||
|
||||
func newSpeechStream(lease sdk.RemoteLease, approval sdk.SessionEvent) *speechStream {
|
||||
return &speechStream{lease: lease, role: approval.Role, grants: slices.Clone(approval.Grants),
|
||||
incoming: make(chan speechItem, maxSpeechItems), outgoing: make(chan []byte, maxSpeechItems)}
|
||||
}
|
||||
|
||||
func (stream *speechStream) drain() {
|
||||
for {
|
||||
select {
|
||||
case item := <-stream.incoming:
|
||||
stream.items--
|
||||
stream.bytes -= item.bytes
|
||||
case frame := <-stream.outgoing:
|
||||
stream.items--
|
||||
stream.bytes -= len(frame)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *coordinator) speech_ready_locked(a *connectionAttempt, stream *speechStream) bool {
|
||||
return c.active == a && a.ctx.Err() == nil && a.speech == stream && c.status.state == "ready" && c.status.peer != 0
|
||||
}
|
||||
|
||||
// SDK event ownership never waits for a relay write. Pre-peer output is dropped
|
||||
// rather than retained for a helper who joins later. Core supplies the origin;
|
||||
// only events matching this controlled lease can reach this queue.
|
||||
func (c *coordinator) observe_locked(event sdk.SessionEvent) {
|
||||
a := c.active
|
||||
if a == nil || a.speech == nil {
|
||||
return
|
||||
}
|
||||
stream := a.speech
|
||||
if !c.speech_ready_locked(a, stream) || stream.role != "controlled" || !slices.Contains(stream.grants, "output-observe") || event.Lease != stream.lease.Lease || event.Epoch != stream.lease.Epoch {
|
||||
return
|
||||
}
|
||||
if event.Speech == nil {
|
||||
c.stop_locked(errProtocol)
|
||||
return
|
||||
}
|
||||
frame, err := relay_speech(*event.Speech)
|
||||
if err != nil {
|
||||
c.stop_locked(errProtocol)
|
||||
return
|
||||
}
|
||||
if stream.items == maxSpeechItems || stream.bytes+len(frame) > maxQueuedBytes {
|
||||
c.stop_locked(errLimit)
|
||||
return
|
||||
}
|
||||
stream.items++
|
||||
stream.bytes += len(frame)
|
||||
stream.outgoing <- frame // Capacity reserved above, including in-flight work.
|
||||
}
|
||||
|
||||
// Membership/origin checks have already run in the relay reader. Admit all
|
||||
// converted frames together or none, retaining FIFO cancel/pause order. Split
|
||||
// utterances are also assembled by core before reaching its speech owner.
|
||||
func (c *coordinator) receive_speech(a *connectionAttempt, stream *speechStream, message message) (bool, error) {
|
||||
if message.kind != "speak" && message.kind != "cancel" && message.kind != "pause_speech" {
|
||||
return false, nil
|
||||
}
|
||||
if stream.role != "controller" || !slices.Contains(stream.grants, "remote-present") {
|
||||
return false, nil
|
||||
}
|
||||
frames, err := reader_speech(message)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
items := make([]speechItem, len(frames))
|
||||
bytes := 0
|
||||
for index, speech := range frames {
|
||||
data, err := json.Marshal(speech)
|
||||
if err != nil {
|
||||
return true, errProtocol
|
||||
}
|
||||
items[index] = speechItem{speech: speech, bytes: len(data), batch: len(frames) > 1, first: index == 0, final: index == len(frames)-1}
|
||||
bytes += len(data)
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.speech_ready_locked(a, stream) {
|
||||
return true, errLease
|
||||
}
|
||||
if stream.items+len(items) > maxSpeechItems || stream.bytes+bytes > maxQueuedBytes {
|
||||
return true, errLimit
|
||||
}
|
||||
stream.items += len(items)
|
||||
stream.bytes += bytes
|
||||
for _, item := range items {
|
||||
stream.incoming <- item
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (c *coordinator) speech_release(stream *speechStream, bytes int) {
|
||||
c.mu.Lock()
|
||||
stream.items--
|
||||
stream.bytes -= bytes
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// All heartbeat/present calls share this owner, including during dial/join.
|
||||
// Check a due heartbeat before every effect so a busy speech queue cannot
|
||||
// indefinitely postpone lease liveness. Calls retain their independent SDK
|
||||
// deadline: disconnect must not cancel a healthy process session.
|
||||
func (c *coordinator) speech_operations(a *connectionAttempt, stream *speechStream) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
var utterance uint64
|
||||
heartbeat := func() bool {
|
||||
if a.ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
stream.sequence++
|
||||
err := c.call("remote.heartbeat", sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, nil)
|
||||
if err != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !heartbeat() {
|
||||
return
|
||||
}
|
||||
case item := <-stream.incoming:
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if !heartbeat() {
|
||||
c.speech_release(stream, item.bytes)
|
||||
return
|
||||
}
|
||||
default:
|
||||
}
|
||||
c.mu.Lock()
|
||||
ready := c.speech_ready_locked(a, stream)
|
||||
c.mu.Unlock()
|
||||
if !ready {
|
||||
c.speech_release(stream, item.bytes)
|
||||
return
|
||||
}
|
||||
stream.sequence++
|
||||
request := sdk.RemotePresentation{RemoteOperation: sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, Speech: item.speech}
|
||||
if item.batch {
|
||||
if item.first {
|
||||
utterance = stream.sequence
|
||||
}
|
||||
request.Utterance, request.Final = utterance, item.final
|
||||
}
|
||||
err := c.call("remote.present", request, nil)
|
||||
c.speech_release(stream, item.bytes)
|
||||
if err != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *coordinator) speech_output(a *connectionAttempt, stream *speechStream, conn *relayConn) {
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
return
|
||||
case frame := <-stream.outgoing:
|
||||
c.mu.Lock()
|
||||
ready := c.speech_ready_locked(a, stream)
|
||||
c.mu.Unlock()
|
||||
if !ready {
|
||||
c.speech_release(stream, len(frame))
|
||||
return
|
||||
}
|
||||
err := conn.write(a.ctx, frame)
|
||||
c.speech_release(stream, len(frame))
|
||||
if err != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(err)
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
func TestCoordinatorIncomingSpeechOrderAndSequence(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, nil)
|
||||
action := approve(t, c, client, 1, "controller")
|
||||
text := " " + strings.Repeat("é\x00", 3000) + " "
|
||||
speak, _ := json.Marshal(map[string]any{"type": "speak", "origin": 7, "priority": 2, "sequence": []any{
|
||||
[]any{"CharacterModeCommand", map[string]any{"state": true}},
|
||||
[]any{"LangChangeCommand", map[string]any{"lang": "fr"}}, text,
|
||||
[]any{"EndUtteranceCommand", map[string]any{}},
|
||||
}})
|
||||
decoded, err := decodeMessage(speak)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected, err := reader_speech(decoded)
|
||||
if err != nil || len(expected) < 2 {
|
||||
t.Fatal("fixture must split", err)
|
||||
}
|
||||
fragments := len(expected)
|
||||
paused := true
|
||||
expected = append(expected, sdk.RemoteSpeech{Kind: "cancel"}, sdk.RemoteSpeech{Kind: "pause", Paused: &paused})
|
||||
cert, roots := testCertificate(t, true)
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"slave"}]}`+"\n")
|
||||
_, _ = conn.Write(append(speak, '\n'))
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"cancel\",\"origin\":7}\n{\"type\":\"pause_speech\",\"origin\":7,\"switch\":true}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
for index, speech := range expected {
|
||||
request := nextCall(t, client, "remote.present").params.(sdk.RemotePresentation)
|
||||
if request.Lease != strings.Repeat("b", 32) || request.Epoch != 1 || request.Sequence != uint64(index+1) || !reflect.DeepEqual(request.Speech, speech) {
|
||||
t.Fatal("speech changed or reordered")
|
||||
}
|
||||
if index < fragments {
|
||||
if request.Utterance != 1 || request.Final != (index == fragments-1) {
|
||||
t.Fatal("split speech lacked a single assembly/final marker")
|
||||
}
|
||||
} else if request.Utterance != 0 || request.Final {
|
||||
t.Fatal("cancel/pause joined the preceding utterance")
|
||||
}
|
||||
}
|
||||
heartbeat := nextCall(t, client, "remote.heartbeat").params.(sdk.RemoteOperation)
|
||||
if heartbeat.Sequence != uint64(len(expected)+1) {
|
||||
t.Fatal("heartbeat sequence interleaved incorrectly")
|
||||
}
|
||||
awaitDone(t, c.disconnect())
|
||||
closed := nextCall(t, client, "remote.close").params.(sdk.RemoteOperation)
|
||||
if closed.Sequence != heartbeat.Sequence+1 {
|
||||
t.Fatal("close sequence did not follow presentation/heartbeat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorRevocationDuringPresentation(t *testing.T) {
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
c, client := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
if method == "remote.present" {
|
||||
close(started)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
t.Error("revoke cancelled healthy SDK call")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
t.Cleanup(func() { once.Do(func() { close(release) }) })
|
||||
action := approve(t, c, client, 1, "controller")
|
||||
cert, roots := testCertificate(t, true)
|
||||
closed := make(chan struct{})
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"slave\"}]}\n{\"type\":\"speak\",\"origin\":7,\"sequence\":[\"first\"]}\n{\"type\":\"cancel\",\"origin\":7}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
close(closed)
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
awaitDone(t, started)
|
||||
nextCall(t, client, "remote.present")
|
||||
client.events <- sdk.SessionEvent{Kind: "remote.revoked", Epoch: 1}
|
||||
awaitDone(t, closed)
|
||||
once.Do(func() { close(release) })
|
||||
closeRequest := nextCall(t, client, "remote.close").params.(sdk.RemoteOperation)
|
||||
if closeRequest.Sequence != 2 {
|
||||
t.Fatal("revocation delivered queued speech or raced final close")
|
||||
}
|
||||
awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "failed" })
|
||||
}
|
||||
|
||||
func TestCoordinatorUnavailableSpeechOwnerClosesLease(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, func(_ context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
if method == "remote.present" {
|
||||
return &sdk.SessionError{Code: -32601, Message: "private host diagnostic"}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
action := approve(t, c, client, 1, "controller")
|
||||
cert, roots := testCertificate(t, true)
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[{\"id\":7,\"connection_type\":\"slave\"}]}\n{\"type\":\"cancel\",\"origin\":7}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
nextCall(t, client, "remote.present")
|
||||
nextCall(t, client, "remote.close")
|
||||
status := awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "failed" })
|
||||
if status.err != errLease {
|
||||
t.Fatal("unavailable speech owner did not fail closed with a constant error")
|
||||
}
|
||||
}
|
||||
|
||||
type speechWriteProbe struct {
|
||||
net.Conn
|
||||
started chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (conn *speechWriteProbe) Write(data []byte) (int, error) {
|
||||
conn.once.Do(func() { close(conn.started) })
|
||||
return conn.Conn.Write(data)
|
||||
}
|
||||
|
||||
func TestSpeechStreamRevocationWhileRelayWriteStalls(t *testing.T) {
|
||||
client := &fixtureClient{events: make(chan sdk.SessionEvent, 8)}
|
||||
c := newCoordinator(t.Context(), client)
|
||||
ctx, cancel := context.WithCancel(c.ctx)
|
||||
stream := newSpeechStream(sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}, sdk.SessionEvent{Role: "controlled", Grants: []string{"output-observe"}})
|
||||
a := &connectionAttempt{ctx: ctx, cancel: cancel, epoch: 1, speech: stream}
|
||||
c.mu.Lock()
|
||||
c.active, c.status = a, connectionStatus{state: "ready", peer: 7}
|
||||
c.mu.Unlock()
|
||||
writer, reader := net.Pipe()
|
||||
probe := &speechWriteProbe{Conn: writer, started: make(chan struct{})}
|
||||
conn := newRelayConn(ctx, probe)
|
||||
workerDone := make(chan struct{})
|
||||
go func() { defer close(workerDone); c.speech_output(a, stream, conn) }()
|
||||
t.Cleanup(func() {
|
||||
c.close()
|
||||
conn.close()
|
||||
reader.Close()
|
||||
awaitDone(t, workerDone)
|
||||
awaitDone(t, c.done)
|
||||
})
|
||||
event := sdk.SessionEvent{Kind: "remote.output", Lease: stream.lease.Lease, Epoch: 1, Speech: &sdk.RemoteSpeech{Kind: "cancel"}}
|
||||
client.events <- event
|
||||
awaitDone(t, probe.started)
|
||||
// The write cannot complete: no one reads the other end of net.Pipe.
|
||||
client.events <- event
|
||||
client.events <- sdk.SessionEvent{Kind: "remote.revoked", Epoch: 1}
|
||||
awaitDone(t, workerDone)
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if a.ctx.Err() == nil || stream.items != 0 || stream.bytes != 0 || c.status.peer != 0 || a.err != errLease {
|
||||
t.Fatal("blocked relay prevented revoke/queue cleanup")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorObservedSpeechToRelay(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, nil)
|
||||
action := approve(t, c, client, 3, "controlled")
|
||||
cert, roots := testCertificate(t, true)
|
||||
joinPeer := make(chan struct{})
|
||||
var once sync.Once
|
||||
t.Cleanup(func() { once.Do(func() { close(joinPeer) }) })
|
||||
received := make(chan message, 4)
|
||||
target := testRelay(t, cert, func(conn net.Conn) {
|
||||
reader := relayHandshake(t, conn, controlled)
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
<-joinPeer
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"client_joined\",\"client\":{\"id\":7,\"connection_type\":\"master\"}}\n")
|
||||
for {
|
||||
frame, err := readFrame(reader)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m, err := decodeMessage(frame)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
received <- m
|
||||
}
|
||||
})
|
||||
target.roots = roots
|
||||
if err := c.connect(action, target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, client, "remote.open")
|
||||
awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "waiting" })
|
||||
// Exercise pre-peer rejection synchronously to establish the ordering.
|
||||
event := sdk.SessionEvent{Kind: "remote.output", Lease: strings.Repeat("b", 32), Epoch: 3, Speech: &sdk.RemoteSpeech{Kind: "speak", Parts: []sdk.RemoteSpeechPart{{Text: "old"}}}}
|
||||
c.mu.Lock()
|
||||
c.observe_locked(event)
|
||||
if c.active.speech.items != 0 {
|
||||
t.Error("retained pre-peer output")
|
||||
}
|
||||
c.mu.Unlock()
|
||||
once.Do(func() { close(joinPeer) })
|
||||
awaitStatus(t, c, func(status connectionStatus) bool { return status.state == "ready" })
|
||||
stale := event
|
||||
stale.Epoch--
|
||||
client.events <- stale
|
||||
stale = event
|
||||
stale.Lease = strings.Repeat("c", 32)
|
||||
client.events <- stale
|
||||
paused := false
|
||||
for _, speech := range []sdk.RemoteSpeech{
|
||||
{Kind: "speak", Priority: 1, Parts: []sdk.RemoteSpeechPart{{Text: " bonjour ", Characters: true, Language: "fr"}, {End: true}}},
|
||||
{Kind: "cancel"}, {Kind: "pause", Paused: &paused},
|
||||
} {
|
||||
copy := speech
|
||||
event.Speech = ©
|
||||
client.events <- event
|
||||
}
|
||||
for _, kind := range []string{"speak", "cancel", "pause_speech"} {
|
||||
select {
|
||||
case actual := <-received:
|
||||
if actual.kind != kind || actual.origin != 0 {
|
||||
t.Fatal("stale output, reordered output or forged origin")
|
||||
}
|
||||
if kind == "speak" {
|
||||
converted, err := reader_speech(actual)
|
||||
if err != nil || len(converted) != 1 || converted[0].Priority != 1 || converted[0].Parts[0].Text != " bonjour " || !converted[0].Parts[0].Characters || converted[0].Parts[0].Language != "fr" {
|
||||
t.Fatal("observed speech lost semantics")
|
||||
}
|
||||
}
|
||||
case <-time.After(4 * time.Second):
|
||||
t.Fatal("missing observed speech")
|
||||
}
|
||||
}
|
||||
awaitDone(t, c.disconnect())
|
||||
nextCall(t, client, "remote.close")
|
||||
}
|
||||
|
||||
// An inert stream lets admission bounds and cleanup be checked without timing
|
||||
// a network buffer. No workers consume its queues.
|
||||
func inertSpeechStream(t *testing.T, role string, grants []string) (*coordinator, *connectionAttempt, *speechStream) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
t.Cleanup(cancel)
|
||||
stream := newSpeechStream(sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}, sdk.SessionEvent{Role: role, Grants: grants})
|
||||
a := &connectionAttempt{ctx: ctx, cancel: cancel, epoch: 1, speech: stream}
|
||||
c := &coordinator{active: a, status: connectionStatus{state: "ready", peer: 7}}
|
||||
return c, a, stream
|
||||
}
|
||||
|
||||
func TestSpeechStreamAdmissionBoundsAndGrants(t *testing.T) {
|
||||
for _, direction := range []string{"incoming", "outgoing"} {
|
||||
for _, limit := range []string{"items", "bytes"} {
|
||||
t.Run(direction+"-"+limit, func(t *testing.T) {
|
||||
role, grants := "controller", []string{"remote-present"}
|
||||
if direction == "outgoing" {
|
||||
role, grants = "controlled", []string{"output-observe"}
|
||||
}
|
||||
c, a, stream := inertSpeechStream(t, role, grants)
|
||||
text := "text"
|
||||
if limit == "bytes" {
|
||||
text = strings.Repeat("a", 5800)
|
||||
}
|
||||
m := message{kind: "speak", payload: speech{parts: []speechPart{{kind: "text", text: text}}}}
|
||||
value := sdk.RemoteSpeech{Kind: "speak", Parts: []sdk.RemoteSpeechPart{{Text: text}}}
|
||||
for a.ctx.Err() == nil {
|
||||
if direction == "incoming" {
|
||||
_, err := c.receive_speech(a, stream, m)
|
||||
if err != nil {
|
||||
if err != errLimit {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.stop_locked(err)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
} else {
|
||||
c.mu.Lock()
|
||||
c.observe_locked(sdk.SessionEvent{Kind: "remote.output", Lease: stream.lease.Lease, Epoch: 1, Speech: &value})
|
||||
c.mu.Unlock()
|
||||
}
|
||||
if stream.items > maxSpeechItems || stream.bytes > maxQueuedBytes {
|
||||
t.Fatal("queue exceeded its bounds")
|
||||
}
|
||||
}
|
||||
if stream.items != 0 || stream.bytes != 0 || len(stream.incoming) != 0 || len(stream.outgoing) != 0 || a.err != errLimit {
|
||||
t.Fatal("overflow did not clear queues")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
c, a, stream := inertSpeechStream(t, "controller", nil)
|
||||
handled, err := c.receive_speech(a, stream, message{kind: "cancel"})
|
||||
if handled || err != nil || stream.items != 0 {
|
||||
t.Fatal("missing grant admitted speech")
|
||||
}
|
||||
// An utterance too large for the whole bounded queue admits no prefix.
|
||||
stream.grants = []string{"remote-present"}
|
||||
_, err = c.receive_speech(a, stream, message{kind: "speak", payload: speech{parts: []speechPart{{kind: "text", text: strings.Repeat("\x00", 50000)}}}})
|
||||
if err != errLimit || stream.items != 0 || len(stream.incoming) != 0 {
|
||||
t.Fatal("oversized utterance admitted a prefix")
|
||||
}
|
||||
for _, role := range []string{"controlled", "controller"} {
|
||||
c, _, stream := inertSpeechStream(t, role, nil)
|
||||
c.observe_locked(sdk.SessionEvent{Kind: "remote.output", Lease: stream.lease.Lease, Epoch: 1, Speech: &sdk.RemoteSpeech{Kind: "cancel"}})
|
||||
if stream.items != 0 {
|
||||
t.Fatal("wrong role or missing output-observe admitted output")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user