Skip to content
7 changes: 6 additions & 1 deletion discojs/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export abstract class Client<N extends Network> extends EventEmitter<{
*/
#disconnectController = new AbortController();
/**
* Aborted on a crash or a disconnection, whichever comes first.
* Aborted on a crash, disconnection, or explicit stop, whichever comes first.
*/
#stopSignal = AbortSignal.any([
this.#crashController.signal,
Expand Down Expand Up @@ -108,6 +108,11 @@ export abstract class Client<N extends Network> extends EventEmitter<{
return this.getLatestModel();
}

/** Interrupt network waits without disposing the trainer's partial model. */
requestStop(): void {
this.#disconnectController.abort(new ClientDisconnectedError());
}

/**
* Handles the disconnection process of the client from any sort of network server.
*/
Expand Down
86 changes: 86 additions & 0 deletions discojs/src/client/client_stop.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { expect, it, vi } from "vitest";
import { Dataset } from "#dataset/index";
import { LocalClient } from "#client/local_client";
import { abortable } from "#client/utils";
import { MeanAggregator } from "#aggregator/index";
import { titanic } from "#root/default_tasks/titanic";
import { Disco } from "#training/disco";
import { ClientDisconnectedError } from "#root/errors";
import { modelEncode } from "#serialization/index";
import type { Model } from "#models/index";
import type { DataType } from "#types/index";

class WaitingClient extends LocalClient {
entered: () => void = () => undefined;
override async onRoundBeginCommunication(): Promise<void> {
this.entered();
await abortable(new Promise<void>(() => {}), this.stopSignal);
}
}

async function setup() {
const task = await titanic.getTask();
const localTask = {
...task,
trainingInformation: {
...task.trainingInformation,
scheme: "local" as const,
aggregationStrategy: "mean" as const,
validationSplit: 0,
},
};
return {
task: localTask,
client: new WaitingClient(
new URL("http://localhost"),
localTask,
new MeanAggregator(),
),
};
}

it.each(["before startup", "during a network wait"])(
"keeps a saveable model when Stop is requested %s",
async (when) => {
const { task, client } = await setup();
const model = await titanic.modelCard.getModel();
vi.spyOn(client, "getLatestModel").mockResolvedValue(model);
const entered = new Promise<void>((resolve) => {
client.entered = resolve;
});
const disco = new Disco(task, client, { scheme: "local" });
const iterator = disco.train(
new Dataset([
{
Age: "30",
SibSp: "0",
Parch: "0",
Fare: "10",
Pclass: "1",
Sex: "female",
Embarked: "S",
Survived: "1",
},
]),
);
let recovered: Model<DataType> | undefined;
try {
if (when === "before startup") disco.requestStop();
const next = iterator.next();
const stopped = expect(next).rejects.toBeInstanceOf(
ClientDisconnectedError,
);
if (when === "during a network wait") {
await entered;
disco.requestStop();
}
await stopped;
recovered = disco.trainer.releaseModel();
expect(recovered).toBe(model);
expect((await modelEncode(model)).byteLength).toBeGreaterThan(0);
} finally {
recovered?.dispose();
await disco.close();
}
},
);
6 changes: 5 additions & 1 deletion discojs/src/client/decentralized/peer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,23 @@ export type PeerEvents = {
// with ACK_CHUNK_ID so the sender can drain before closing the connection.
/** Platform-neutral peer transport; implementations must emit events asynchronously. */
export interface PeerTransport {
/** When true, the consumer may detach received buffers after emission. */
readonly transferableData?: boolean;
on<K extends keyof PeerEvents>(
event: K,
listener: (value: PeerEvents[K]) => void,
): void;
signal(signal: SignalData): void;
send(data: Uint8Array): void;
/** With transfer enabled, the caller gives up ownership of the buffer. */
send(data: Uint8Array, options?: { transfer?: boolean }): void;
drain(timeout?: number): Promise<void>;
destroy(): Promise<void>;
}

export type PeerFactory = (id: NodeID, isInitiator: boolean) => PeerTransport;

export class Peer extends EventEmitter<PeerEvents> implements PeerTransport {
readonly transferableData = true;
private readonly pc: RTCPeerConnection;
private channel?: RTCDataChannel;
private isDestroyed = false;
Expand Down
86 changes: 85 additions & 1 deletion discojs/src/client/event_connection.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as msgpack from "@msgpack/msgpack";

import type { EventConnection } from "#client/event_connection";
import { sendAndWaitWithRetry } from "#client/event_connection";
import {
PeerConnection,
sendAndWaitWithRetry,
WebSocketServer,
} from "#client/event_connection";
import type { PeerTransport } from "#client/decentralized/peer";
import * as decentralizedMessages from "#client/decentralized/messages";
import type { Message, NarrowMessage } from "#client/messages";
import { MType } from "#client/mtype";
import type * as federatedMessages from "#client/federated/messages";
import { EventEmitter } from "#utils/event_emitter";

const { sockets, FakeWebSocket } = vi.hoisted(() => {
const sockets: FakeWebSocket[] = [];
class FakeWebSocket {
binaryType = "";
onmessage?: (event: { data: unknown }) => void;
onopen?: () => void;
constructor() {
sockets.push(this);
}
}
return { sockets, FakeWebSocket };
});
vi.mock("@epfml/isomorphic-ws", () => ({ default: FakeWebSocket }));

/**
* In-memory fake EventConnection
*/
Expand All @@ -28,6 +49,69 @@ class FakeConnection
const CLIENT_CONNECTED: Message = { type: MType.ClientConnected };
const RETRY_DELAY_MS = 1_000;

describe("incoming message validation", () => {
it("ignores malformed peer messages and still delivers the next valid message", () => {
let receive!: (data: Uint8Array) => void;
const peer: PeerTransport = {
on(type, listener) {
if (type === "data") receive = listener;
},
signal: vi.fn(),
send: vi.fn(),
drain: vi.fn(async () => {}),
destroy: vi.fn(async () => {}),
};
const connection = new PeerConnection(
"local",
"remote",
new FakeConnection(),
() => peer,
);
const received = vi.fn();
connection.on(MType.SharedModel, received);

for (const invalid of [
new Uint8Array([0xc1]), // Invalid MessagePack.
new Uint8Array([0x81]), // Truncated MessagePack.
msgpack.encode({ type: MType.SharedModel, model: "invalid" }),
]) {
expect(() => receive(invalid)).not.toThrow();
}
expect(received).not.toHaveBeenCalled();
const message = { type: MType.SharedModel, model: new Uint8Array([1]) };
receive(msgpack.encode(message));
expect(received).toHaveBeenCalledExactlyOnceWith(message);
});

it("ignores malformed server messages and still delivers the next valid message", async () => {
const connecting = WebSocketServer.connect(
new URL("ws://localhost"),
decentralizedMessages.isMessageFromServer,
() => true,
);
const socket = sockets.at(-1)!;
socket.onopen?.();
const server = await connecting;
const received = vi.fn();
server.on(MType.EnoughParticipants, received);

for (const data of [
"not an ArrayBuffer",
new Uint8Array([0xc1]).buffer,
new Uint8Array([0x81]).buffer,
Uint8Array.from(msgpack.encode({ type: "invalid" })).buffer,
]) {
expect(() => socket.onmessage?.({ data })).not.toThrow();
}
expect(received).not.toHaveBeenCalled();
const message = { type: MType.EnoughParticipants };
socket.onmessage?.({
data: Uint8Array.from(msgpack.encode(message)).buffer,
});
expect(received).toHaveBeenCalledExactlyOnceWith(message);
});
});

/**
* Builds a NewFederatedNodeInfo message.
* @param id the node id the server assigns to us in the message
Expand Down
37 changes: 26 additions & 11 deletions discojs/src/client/event_connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,17 @@ export class PeerConnection
});

this.#peer.on("data", (data) => {
const msg: unknown = msgpack.decode(data);

if (!decentralizedMessages.isPeerMessage(msg)) {
throw new Error(`invalid message received: ${JSON.stringify(msg)}`);
let msg: decentralizedMessages.PeerMessage;
try {
const decoded: unknown = msgpack.decode(data);
if (!decentralizedMessages.isPeerMessage(decoded)) {
debug("ignoring invalid peer message: %o", decoded);
return;
}
msg = decoded;
} catch (error) {
debug("ignoring undecodable peer message: %o", error);
return;
}

this.emit(msg.type, msg);
Expand Down Expand Up @@ -202,7 +209,8 @@ export class PeerConnection
`can't send this type of message: ${JSON.stringify(msg)}`,
);
}
this.#peer.send(Buffer.from(msgpack.encode(msg)));
// The encoding is fresh, so transports can consume its buffer directly.
this.#peer.send(msgpack.encode(msg), { transfer: true });
}

async disconnect(gracePeriod = 0): Promise<void> {
Expand Down Expand Up @@ -236,14 +244,21 @@ export class WebSocketServer

ws.onmessage = (event) => {
if (!(event.data instanceof ArrayBuffer)) {
throw new Error("server did not send an ArrayBuffer");
debug("ignoring server message: expected an ArrayBuffer");
return;
}

const msg: unknown = msgpack.decode(new Uint8Array(event.data));

// Validate message format
if (!validateReceived(msg)) {
throw new Error(`invalid message received: ${JSON.stringify(msg)}`);
let msg: Message;
try {
const decoded: unknown = msgpack.decode(new Uint8Array(event.data));
if (!validateReceived(decoded)) {
debug("ignoring invalid server message: %o", decoded);
return;
}
msg = decoded;
} catch (error) {
debug("ignoring undecodable server message: %o", error);
return;
}

server.emit(msg.type, msg);
Expand Down
15 changes: 15 additions & 0 deletions discojs/src/training/disco.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export class Disco<D extends DataType, N extends Network> extends EventEmitter<{
}> {
public readonly trainer: Trainer<D, N>;
readonly #client: clients.Client<N>;
readonly #stopController = new AbortController();
readonly #logger: Logger;
readonly #task: Task<D, N>;
readonly #preprocessOnce: boolean;
Expand Down Expand Up @@ -250,6 +251,15 @@ export class Disco<D extends DataType, N extends Network> extends EventEmitter<{
if (tabularMetadata !== undefined)
this.trainer.model.metadata = tabularMetadata;

// Finish startup before honoring Stop. Once the model belongs to the
// trainer, cancellation can interrupt network waits without losing it.
this.#stopController.signal.addEventListener(
"abort",
() => this.#client.requestStop(),
{ once: true },
);
if (this.#stopController.signal.aborted) this.#client.requestStop();

for await (const [roundNum, round] of enumerate(
this.trainer.train(trainingDataset, validationDataset_),
)) {
Expand Down Expand Up @@ -314,6 +324,11 @@ export class Disco<D extends DataType, N extends Network> extends EventEmitter<{
this.#logger.success("Training finished");
}

/** Interrupt network waits while keeping the model available to the caller. */
requestStop(): void {
this.#stopController.abort();
}

/**
* Completely stops the ongoing training instance.
* Disposes all tensors including the model,
Expand Down
Loading