Repository navigation
feat(smg): add WorkerSyncAdapter for v2 worker: CRDT namespace #1313
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6748c8e
feat(smg): add WorkerSyncAdapter for v2 worker: CRDT namespace
CatherineSue 4e7e665
refactor(smg): move mesh adapters under mesh/adapters/ subdir
CatherineSue 5d300b0
fix(smg): backfill WorkerRegistry from `worker:` namespace on start
CatherineSue cbce753
fix(smg): drain subscription during backfill and warn on bad keys
CatherineSue File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| //! CRDT- and stream-namespace adapters that bridge `MeshKV` to | ||
| //! gateway-local state. Each adapter owns one prefix, serialises | ||
| //! domain types into the shared merge format, and routes remote | ||
| //! updates into the corresponding registry or cache. | ||
|
|
||
| pub mod worker_sync; | ||
|
|
||
| pub use worker_sync::WorkerSyncAdapter; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,252 @@ | ||
| //! `worker:` CRDT adapter: gateway ↔ mesh bridge for `WorkerState`. | ||
| //! | ||
| //! Outbound: `on_worker_changed` bincode-serialises a `WorkerState` | ||
| //! and writes it under `worker:{worker_id}`. `on_worker_removed` | ||
| //! writes a tombstone. Both map 1:1 to the v1 | ||
| //! `MeshSyncManager::sync_worker_state` / `remove_worker_state` | ||
| //! behaviour but target the typed CRDT namespace instead of the | ||
| //! untyped store. | ||
| //! | ||
| //! Inbound: `start` spawns a task that subscribes to the namespace | ||
| //! and routes each non-tombstone update through | ||
| //! `WorkerRegistry::on_remote_worker_state` — the same sink the v1 | ||
| //! `WorkerStateSubscriber` wires up, so registry behaviour | ||
| //! (URL-dedupe, health promotion, `Registered` event fan-out) is | ||
| //! unchanged. Tombstones are logged at debug; the registry does not | ||
| //! yet expose a remote-remove hook, and wiring one belongs in a | ||
| //! later PR together with the v1 mirror teardown. | ||
| //! | ||
| //! The adapter writes through `CrdtNamespace::put`, which fires | ||
| //! local subscribers in addition to gossiping. A local write | ||
| //! therefore echoes back through `start`'s loop and lands in | ||
| //! `on_remote_worker_state`. That path is idempotent — the URL | ||
| //! lookup short-circuits to a health refresh — so the loop is | ||
| //! self-limiting and matches the v1 behaviour where a local | ||
| //! `sync_worker_state` also re-appears in the same node's store | ||
| //! before gossip fans out. | ||
|
|
||
| use std::sync::Arc; | ||
|
|
||
| use bytes::Bytes; | ||
| use smg_mesh::{CrdtNamespace, WorkerState, WorkerStateSubscriber}; | ||
| use tracing::{debug, warn}; | ||
|
|
||
| use crate::worker::WorkerRegistry; | ||
|
|
||
| const PREFIX: &str = "worker:"; | ||
|
|
||
| /// Bridge between the `worker:` CRDT namespace and the gateway's | ||
| /// in-process `WorkerRegistry`. | ||
| pub struct WorkerSyncAdapter { | ||
| workers: Arc<CrdtNamespace>, | ||
| worker_registry: Arc<WorkerRegistry>, | ||
| } | ||
|
|
||
| impl std::fmt::Debug for WorkerSyncAdapter { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| f.debug_struct("WorkerSyncAdapter") | ||
| .field("prefix", &self.workers.prefix()) | ||
| .finish_non_exhaustive() | ||
| } | ||
| } | ||
|
|
||
| impl WorkerSyncAdapter { | ||
| /// Build an adapter wrapping a `worker:`-scoped namespace and the | ||
| /// gateway's worker registry. Panics if the namespace is not | ||
| /// scoped to `worker:` so a mis-wired caller fails fast at | ||
| /// startup rather than silently routing updates to the wrong | ||
| /// prefix. | ||
| pub fn new(workers: Arc<CrdtNamespace>, worker_registry: Arc<WorkerRegistry>) -> Arc<Self> { | ||
| assert_eq!( | ||
| workers.prefix(), | ||
| PREFIX, | ||
| "WorkerSyncAdapter requires a namespace scoped to `{PREFIX}`", | ||
| ); | ||
| Arc::new(Self { | ||
| workers, | ||
| worker_registry, | ||
| }) | ||
| } | ||
|
|
||
| /// Spawn the inbound task. It runs until the namespace's | ||
| /// subscriber channel closes (only on `MeshKV` drop). | ||
| pub fn start(self: &Arc<Self>) { | ||
| let this = Arc::clone(self); | ||
| let mut sub = self.workers.subscribe(""); | ||
|
CatherineSue marked this conversation as resolved.
Resolved
|
||
| #[expect( | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| clippy::disallowed_methods, | ||
| reason = "subscription task ends automatically when the mesh KV drops and closes the channel; no handle needed" | ||
| )] | ||
| tokio::spawn(async move { | ||
| while let Some((key, value)) = sub.receiver.recv().await { | ||
| let Some(worker_id) = key.strip_prefix(PREFIX).filter(|s| !s.is_empty()) else { | ||
| warn!(key, "worker: subscription yielded unexpected key shape"); | ||
| continue; | ||
| }; | ||
| match value { | ||
| Some(fragments) => this.apply_incoming(worker_id, &fragments), | ||
| None => debug!( | ||
| worker_id, | ||
| "remote worker tombstone (no-op pending registry remove-by-mesh hook)" | ||
| ), | ||
| } | ||
| } | ||
| debug!("WorkerSyncAdapter subscription closed"); | ||
| }); | ||
| } | ||
|
|
||
| fn apply_incoming(&self, worker_id: &str, fragments: &[Bytes]) { | ||
| // CRDT `put` publishes a single fragment today. The | ||
| // subscription API is shared with stream namespaces that can | ||
| // deliver chunked payloads, so concatenate defensively; the | ||
| // fast path is a single cheap Bytes copy. | ||
| let total = fragments.iter().map(Bytes::len).sum(); | ||
| let mut bytes = Vec::with_capacity(total); | ||
| for frag in fragments { | ||
| bytes.extend_from_slice(frag); | ||
| } | ||
| match bincode::deserialize::<WorkerState>(&bytes) { | ||
| Ok(state) => self.worker_registry.on_remote_worker_state(&state), | ||
| Err(err) => warn!(worker_id, %err, "failed to decode WorkerState"), | ||
| } | ||
| } | ||
|
|
||
| /// Publish a worker update to the cluster. Callers pass the | ||
| /// registry's current state; the adapter owns (de)serialisation | ||
| /// and key formatting. | ||
| pub fn on_worker_changed(&self, worker_id: &str, state: &WorkerState) { | ||
| match bincode::serialize(state) { | ||
| Ok(bytes) => self.workers.put(&format!("{PREFIX}{worker_id}"), bytes), | ||
| Err(err) => warn!(worker_id, %err, "failed to serialize WorkerState"), | ||
|
CatherineSue marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
|
|
||
| /// Publish a tombstone for a worker, removing it from the CRDT. | ||
| pub fn on_worker_removed(&self, worker_id: &str) { | ||
| self.workers.delete(&format!("{PREFIX}{worker_id}")); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::time::Duration; | ||
|
|
||
| use smg_mesh::{MergeStrategy, MeshKV}; | ||
| use tokio::time::sleep; | ||
|
|
||
| use super::*; | ||
|
|
||
| fn worker_namespace(mesh: &MeshKV) -> Arc<CrdtNamespace> { | ||
| mesh.configure_crdt_prefix(PREFIX, MergeStrategy::LastWriterWins) | ||
| } | ||
|
|
||
| fn sample_state(worker_id: &str, url: &str) -> WorkerState { | ||
| WorkerState { | ||
| worker_id: worker_id.into(), | ||
| model_id: "llama-3".into(), | ||
| url: url.into(), | ||
| health: true, | ||
| load: 0.25, | ||
| version: 1, | ||
| spec: vec![], | ||
| } | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn on_worker_changed_writes_decodable_state() { | ||
| let mesh = MeshKV::new("node-a".into()); | ||
| let ns = worker_namespace(&mesh); | ||
| let registry = Arc::new(WorkerRegistry::new()); | ||
| let adapter = WorkerSyncAdapter::new(ns.clone(), registry); | ||
|
|
||
| let state = sample_state("w1", "http://worker-a:8080"); | ||
| adapter.on_worker_changed("w1", &state); | ||
|
|
||
| let raw = ns.get("worker:w1").expect("adapter wrote through to CRDT"); | ||
| let decoded: WorkerState = bincode::deserialize(&raw).unwrap(); | ||
| assert_eq!(decoded, state); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn on_worker_removed_tombstones_the_entry() { | ||
| let mesh = MeshKV::new("node-a".into()); | ||
| let ns = worker_namespace(&mesh); | ||
| let registry = Arc::new(WorkerRegistry::new()); | ||
| let adapter = WorkerSyncAdapter::new(ns.clone(), registry); | ||
|
|
||
| let state = sample_state("w1", "http://worker-a:8080"); | ||
| adapter.on_worker_changed("w1", &state); | ||
| assert!(ns.get("worker:w1").is_some()); | ||
|
|
||
| adapter.on_worker_removed("w1"); | ||
| assert!( | ||
| ns.get("worker:w1").is_none(), | ||
| "tombstone must hide the prior value from readers" | ||
| ); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn start_routes_remote_state_into_registry() { | ||
| // Two adapters over one store mimic a remote node's write | ||
| // (publisher) arriving at a local subscriber. The underlying | ||
| // store is shared so the publisher's put fires the | ||
| // subscriber adapter's subscription. | ||
| let mesh = MeshKV::new("node-a".into()); | ||
| let ns = worker_namespace(&mesh); | ||
|
|
||
| let registry = Arc::new(WorkerRegistry::new()); | ||
| let subscriber = WorkerSyncAdapter::new(ns.clone(), registry.clone()); | ||
| subscriber.start(); | ||
|
|
||
| let publisher_registry = Arc::new(WorkerRegistry::new()); | ||
| let publisher = WorkerSyncAdapter::new(ns, publisher_registry); | ||
| publisher.on_worker_changed("w1", &sample_state("w1", "http://remote:8080")); | ||
|
|
||
| // Subscription fanout is async; poll briefly. | ||
| for _ in 0..20 { | ||
| if registry.get_by_url("http://remote:8080").is_some() { | ||
| return; | ||
| } | ||
| sleep(Duration::from_millis(10)).await; | ||
| } | ||
| panic!("registry did not see the remote worker"); | ||
| } | ||
|
CatherineSue marked this conversation as resolved.
Resolved
|
||
|
|
||
| #[tokio::test] | ||
| async fn start_ignores_malformed_payload() { | ||
| // A bad payload should not propagate into the registry and | ||
| // must not kill the spawned task — a subsequent valid write | ||
| // still lands. | ||
| let mesh = MeshKV::new("node-a".into()); | ||
| let ns = worker_namespace(&mesh); | ||
| let registry = Arc::new(WorkerRegistry::new()); | ||
| let adapter = WorkerSyncAdapter::new(ns.clone(), registry.clone()); | ||
| adapter.start(); | ||
|
|
||
| ns.put("worker:bogus", b"not-bincode".to_vec()); | ||
| sleep(Duration::from_millis(20)).await; | ||
| assert!(registry.get_by_url("http://remote:8080").is_none()); | ||
|
|
||
| let good = sample_state("w1", "http://remote:8080"); | ||
| ns.put( | ||
| "worker:w1", | ||
| bincode::serialize(&good).expect("state serializes"), | ||
| ); | ||
| for _ in 0..20 { | ||
| if registry.get_by_url("http://remote:8080").is_some() { | ||
| return; | ||
| } | ||
| sleep(Duration::from_millis(10)).await; | ||
| } | ||
| panic!("subscription task aborted after a bad payload"); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| #[should_panic(expected = "WorkerSyncAdapter requires a namespace scoped to `worker:`")] | ||
| async fn new_rejects_wrong_prefix() { | ||
| let mesh = MeshKV::new("node-a".into()); | ||
| let ns = mesh.configure_crdt_prefix("policy:", MergeStrategy::LastWriterWins); | ||
| let registry = Arc::new(WorkerRegistry::new()); | ||
| let _ = WorkerSyncAdapter::new(ns, registry); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| //! Gateway-side glue for the v2 mesh: adapters that bridge the | ||
| //! typed `MeshKV` namespaces to local registries, plus bootstrap | ||
| //! and shutdown wiring added in later steps. | ||
|
|
||
| pub mod adapters; | ||
|
|
||
| pub use adapters::WorkerSyncAdapter; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.