Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions packages/beacon-node/src/chain/reprocess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ export class ReprocessController {
* @returns true if blockFound
*/
waitForBlockOfAttestation(slot: Slot, root: RootHex): Promise<boolean> {
this.metrics?.reprocessAttestations.total.inc();
this.metrics?.reprocessApiAttestations.total.inc();

if (this.awaitingPromisesCount >= MAXIMUM_QUEUED_ATTESTATIONS) {
this.metrics?.reprocessAttestations.reject.inc({reason: ReprocessStatus.reached_limit});
this.metrics?.reprocessApiAttestations.reject.inc({reason: ReprocessStatus.reached_limit});
return Promise.resolve(false);
}

Expand Down Expand Up @@ -116,8 +116,8 @@ export class ReprocessController {
const {resolve, addedTimeMs, awaitingAttestationsCount} = awaitingPromise;
resolve(true);
this.awaitingPromisesCount -= awaitingAttestationsCount;
this.metrics?.reprocessAttestations.resolve.inc(awaitingAttestationsCount);
this.metrics?.reprocessAttestations.waitTimeBeforeResolve.set((Date.now() - addedTimeMs) / 1000);
this.metrics?.reprocessApiAttestations.resolve.inc(awaitingAttestationsCount);
this.metrics?.reprocessApiAttestations.waitSecBeforeResolve.set((Date.now() - addedTimeMs) / 1000);
}

// prune
Expand All @@ -140,8 +140,8 @@ export class ReprocessController {
for (const awaitingPromise of awaitingPromisesByRoot.values()) {
const {resolve, addedTimeMs} = awaitingPromise;
resolve(false);
this.metrics?.reprocessAttestations.waitTimeBeforeReject.set((now - addedTimeMs) / 1000);
this.metrics?.reprocessAttestations.reject.inc({reason: ReprocessStatus.expired});
this.metrics?.reprocessApiAttestations.waitSecBeforeReject.set((now - addedTimeMs) / 1000);
this.metrics?.reprocessApiAttestations.reject.inc({reason: ReprocessStatus.expired});
}

// prune
Expand Down
35 changes: 32 additions & 3 deletions packages/beacon-node/src/metrics/metrics/lodestar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1221,7 +1221,7 @@ export function createLodestarMetrics(
},

// reprocess attestations
reprocessAttestations: {
reprocessApiAttestations: {
total: register.gauge({
name: "lodestar_reprocess_attestations_total",
help: "Total number of attestations waiting to reprocess",
Expand All @@ -1230,7 +1230,7 @@ export function createLodestarMetrics(
name: "lodestar_reprocess_attestations_resolve_total",
help: "Total number of attestations are reprocessed",
}),
waitTimeBeforeResolve: register.gauge({
waitSecBeforeResolve: register.gauge({
name: "lodestar_reprocess_attestations_wait_time_resolve_seconds",
help: "Time to wait for unknown block in seconds",
}),
Expand All @@ -1239,12 +1239,41 @@ export function createLodestarMetrics(
help: "Total number of attestations are rejected to reprocess",
labelNames: ["reason"],
}),
waitTimeBeforeReject: register.gauge<"reason">({
waitSecBeforeReject: register.gauge<"reason">({
name: "lodestar_reprocess_attestations_wait_time_reject_seconds",
help: "Time to wait for unknown block before being rejected",
}),
},

// reprocess gossip attestations
reprocessGossipAttestations: {
total: register.gauge({
name: "lodestar_reprocess_gossip_attestations_total",
help: "Total number of gossip attestations waiting to reprocess",
}),
countPerSlot: register.gauge({
name: "lodestar_reprocess_gossip_attestations_per_slot_total",
help: "Total number of gossip attestations waiting to reprocess pet slot",
}),
resolve: register.gauge({
name: "lodestar_reprocess_gossip_attestations_resolve_total",
help: "Total number of gossip attestations are reprocessed",
}),
waitSecBeforeResolve: register.gauge({
name: "lodestar_reprocess_gossip_attestations_wait_time_resolve_seconds",
help: "Time to wait for unknown block in seconds",
}),
reject: register.gauge<"reason">({
name: "lodestar_reprocess_gossip_attestations_reject_total",
help: "Total number of attestations are rejected to reprocess",
labelNames: ["reason"],
}),
waitSecBeforeReject: register.gauge<"reason">({
name: "lodestar_reprocess_gossip_attestations_wait_time_reject_seconds",
help: "Time to wait for unknown block before being rejected",
}),
},

lightclientServer: {
onSyncAggregate: register.gauge<"event">({
name: "lodestar_lightclient_server_on_sync_aggregate_event_total",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {SlotRootHex} from "@lodestar/types";
import {
getBlockRootFromAttestationSerialized,
getBlockRootFromSignedAggregateAndProofSerialized,
getSlotFromAttestationSerialized,
getSlotFromSignedAggregateAndProofSerialized,
Comment thread
twoeths marked this conversation as resolved.
Resolved
} from "../../util/sszBytes.js";
import {GossipType} from "../gossip/index.js";
import {ExtractSlotRootFns} from "./types.js";

/**
* Extract the slot and block root of a gossip message form serialized data.
* Only applicable for beacon_attestation and beacon_aggregate_and_proof topics.
*/
export function createExtractBlockSlotRootFns(): ExtractSlotRootFns {
return {
[GossipType.beacon_attestation]: (data: Uint8Array): SlotRootHex => {
return {
slot: getSlotFromAttestationSerialized(data),
root: getBlockRootFromAttestationSerialized(data),
};
},
[GossipType.beacon_aggregate_and_proof]: (data: Uint8Array): SlotRootHex => {
return {
slot: getSlotFromSignedAggregateAndProofSerialized(data),
root: getBlockRootFromSignedAggregateAndProofSerialized(data),
};
},
};
}
134 changes: 129 additions & 5 deletions packages/beacon-node/src/network/processor/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import {Logger, mapValues} from "@lodestar/utils";
import {Logger, MapDef, mapValues, sleep} from "@lodestar/utils";
import {RootHex, Slot} from "@lodestar/types";
import {routes} from "@lodestar/api";
import {IBeaconChain} from "../../chain/interface.js";
import {Metrics} from "../../metrics/metrics.js";
import {NetworkEvent, NetworkEventBus} from "../events.js";
import {GossipType} from "../gossip/interface.js";
import {ChainEvent} from "../../chain/emitter.js";
import {createGossipQueues} from "./gossipQueues.js";
import {NetworkWorker, NetworkWorkerModules} from "./worker.js";
import {PendingGossipsubMessage} from "./types.js";
import {ValidatorFnsModules, GossipHandlerOpts} from "./gossipHandlers.js";
import {createExtractBlockSlotRootFns} from "./extractSlotRootFns.js";

export type NetworkProcessorModules = NetworkWorkerModules &
ValidatorFnsModules & {
Expand All @@ -29,7 +33,6 @@ type WorkOpts = {
* in order to process the gossip object.
*/
const executeGossipWorkOrderObj: Record<GossipType, WorkOpts> = {
// gossip block verify signatures on main thread, hence we want to bypass the bls check
[GossipType.beacon_block]: {bypassQueue: true},
[GossipType.beacon_block_and_blobs_sidecar]: {bypassQueue: true},
[GossipType.beacon_aggregate_and_proof]: {},
Expand All @@ -48,6 +51,31 @@ const executeGossipWorkOrder = Object.keys(executeGossipWorkOrderObj) as (keyof
// TODO: Arbitrary constant, check metrics
const MAX_JOBS_SUBMITTED_PER_TICK = 128;

// How many attestations (aggregate + unaggregate) we keep before new ones get dropped.
const MAX_QUEUED_UNKNOWN_BLOCK_GOSSIP_OBJECTS = 16_384;

// We don't want to process too many attestations in a single tick
// As seen on mainnet, utilization rate for attestation topic is 80_000% (800x) - 90_000% (900x)
Comment thread
twoeths marked this conversation as resolved.
Resolved
// so make this constant go with that number
const MAX_UNKNOWN_BLOCK_GOSSIP_OBJECTS_PER_TICK = 1024;

// Same motivation to JobItemQueue, we don't want to block the vent loop
Comment thread
twoeths marked this conversation as resolved.
Resolved
const PROCESS_UNKNOWN_BLOCK_GOSSIP_OBJECTS_YIELD_EVERY_MS = 50;

/**
* Reprocess reject reason for metrics
*/
enum ReprocessRejectReason {
/**
* There are too many attestations that have unknown block root.
*/
reached_limit = "reached_limit",
/**
* The awaiting attestation is pruned per clock slot.
*/
expired = "expired",
}

/**
* Network processor handles the gossip queues and throtles processing to not overload the main thread
* - Decides when to process work and what to process
Expand All @@ -71,26 +99,40 @@ const MAX_JOBS_SUBMITTED_PER_TICK = 128;
export class NetworkProcessor {
private readonly worker: NetworkWorker;
private readonly chain: IBeaconChain;
private readonly events: NetworkEventBus;
private readonly logger: Logger;
private readonly metrics: Metrics | null;
private readonly gossipQueues = createGossipQueues<PendingGossipsubMessage>();
private readonly gossipTopicConcurrency = mapValues(this.gossipQueues, () => 0);
private readonly extractBlockSlotRootFns = createExtractBlockSlotRootFns();
// we may not receive the block for Attestation and SignedAggregateAndProof messages, in that case PendingGossipsubMessage needs
// to be stored in this Map and reprocessed once the block comes
private readonly awaitingGossipsubMessagesByRootBySlot: MapDef<Slot, MapDef<RootHex, Set<PendingGossipsubMessage>>>;
private unknownBlockGossipsubMessagesCount = 0;

constructor(modules: NetworkProcessorModules, private readonly opts: NetworkProcessorOpts) {
const {chain, events, logger, metrics} = modules;
this.chain = chain;
this.events = events;
this.metrics = metrics;
this.logger = logger;
this.worker = new NetworkWorker(modules, opts);

events.on(NetworkEvent.pendingGossipsubMessage, this.onPendingGossipsubMessage.bind(this));
this.chain.emitter.on(routes.events.EventType.block, this.onBlockProcessed.bind(this));
this.chain.emitter.on(ChainEvent.clockSlot, this.onClockSlot.bind(this));

this.awaitingGossipsubMessagesByRootBySlot = new MapDef(
() => new MapDef<RootHex, Set<PendingGossipsubMessage>>(() => new Set())
);

if (metrics) {
metrics.gossipValidationQueueLength.addCollect(() => {
for (const topic of executeGossipWorkOrder) {
metrics.gossipValidationQueueLength.set({topic}, this.gossipQueues[topic].length);
metrics.gossipValidationQueueConcurrency.set({topic}, this.gossipTopicConcurrency[topic]);
}
metrics.reprocessGossipAttestations.countPerSlot.set(this.unknownBlockGossipsubMessagesCount);
});
}

Expand All @@ -99,6 +141,12 @@ export class NetworkProcessor {
// this.regen.onAvailable(() => this.executeWork());
}

async stop(): Promise<void> {
this.events.off(NetworkEvent.pendingGossipsubMessage, this.onPendingGossipsubMessage);
this.chain.emitter.off(routes.events.EventType.block, this.onBlockProcessed);
this.chain.emitter.off(ChainEvent.clockSlot, this.onClockSlot);
}

dropAllJobs(): void {
for (const topic of executeGossipWorkOrder) {
this.gossipQueues[topic].clear();
Expand All @@ -114,17 +162,92 @@ export class NetworkProcessor {
return queue.getAll();
}

private onPendingGossipsubMessage(data: PendingGossipsubMessage): void {
const droppedJob = this.gossipQueues[data.topic.type].add(data);
private onPendingGossipsubMessage(message: PendingGossipsubMessage): void {
const extractBlockSlotRootFn = this.extractBlockSlotRootFns[message.topic.type];
// check block root of Attestation and SignedAggregateAndProof messages
if (extractBlockSlotRootFn) {
const {slot, root: rootHex} = extractBlockSlotRootFn(message.msg.data);
if (!this.chain.forkChoice.hasBlockHex(rootHex)) {
if (this.unknownBlockGossipsubMessagesCount > MAX_QUEUED_UNKNOWN_BLOCK_GOSSIP_OBJECTS) {
// TODO: Should report the dropped job to gossip? It will be eventually pruned from the mcache
this.metrics?.reprocessGossipAttestations.reject.inc({reason: ReprocessRejectReason.reached_limit});
return;
}

this.metrics?.reprocessGossipAttestations.total.inc();
const awaitingGossipsubMessagesByRoot = this.awaitingGossipsubMessagesByRootBySlot.getOrDefault(slot);
const awaitingGossipsubMessages = awaitingGossipsubMessagesByRoot.getOrDefault(rootHex);
awaitingGossipsubMessages.add(message);
this.unknownBlockGossipsubMessagesCount++;
}
}

// bypass the check for other messages
this.pushPendingGossipsubMessageToQueue(message);
}

private pushPendingGossipsubMessageToQueue(message: PendingGossipsubMessage): void {
const topicType = message.topic.type;
const droppedJob = this.gossipQueues[topicType].add(message);
if (droppedJob) {
// TODO: Should report the dropped job to gossip? It will be eventually pruned from the mcache
this.metrics?.gossipValidationQueueDroppedJobs.inc({topic: data.topic.type});
this.metrics?.gossipValidationQueueDroppedJobs.inc({topic: message.topic.type});
}

// Tentatively perform work
this.executeWork();
}

private async onBlockProcessed({
slot,
block: rootHex,
}: {
slot: Slot;
block: string;
executionOptimistic: boolean;
}): Promise<void> {
const byRootGossipsubMessages = this.awaitingGossipsubMessagesByRootBySlot.getOrDefault(slot);
const waitingGossipsubMessages = byRootGossipsubMessages.getOrDefault(rootHex);
if (waitingGossipsubMessages.size === 0) {
return;
}

this.metrics?.reprocessGossipAttestations.resolve.inc(waitingGossipsubMessages.size);
const nowSec = Date.now() / 1000;
let count = 0;
// TODO: we can group attestations to process in batches but since we have the SeenAttestationDatas
// cache, it may not be necessary at this time
for (const message of waitingGossipsubMessages) {
this.metrics?.reprocessGossipAttestations.waitSecBeforeResolve.set(nowSec - message.seenTimestampSec);
this.pushPendingGossipsubMessageToQueue(message);
count++;
// don't want to block the event loop, worse case it'd wait for 16_084 / 1024 * 50ms = 800ms which is not a big deal
if (count === MAX_UNKNOWN_BLOCK_GOSSIP_OBJECTS_PER_TICK) {
count = 0;
await sleep(PROCESS_UNKNOWN_BLOCK_GOSSIP_OBJECTS_YIELD_EVERY_MS);
}
}

byRootGossipsubMessages.delete(rootHex);
}

private onClockSlot(clockSlot: Slot): void {
const nowSec = Date.now() / 1000;
for (const [slot, gossipMessagesByRoot] of this.awaitingGossipsubMessagesByRootBySlot.entries()) {
if (slot < clockSlot) {
for (const gossipMessages of gossipMessagesByRoot.values()) {
for (const message of gossipMessages) {
this.metrics?.reprocessGossipAttestations.reject.inc({reason: ReprocessRejectReason.expired});
this.metrics?.reprocessGossipAttestations.waitSecBeforeReject.set(nowSec - message.seenTimestampSec);
// TODO: Should report the dropped job to gossip? It will be eventually pruned from the mcache
}
}
this.awaitingGossipsubMessagesByRootBySlot.delete(slot);
}
}
this.unknownBlockGossipsubMessagesCount = 0;
}

private executeWork(): void {
// TODO: Maybe de-bounce by timing the last time executeWork was run

Expand All @@ -134,6 +257,7 @@ export class NetworkProcessor {
job_loop: while (jobsSubmitted < MAX_JOBS_SUBMITTED_PER_TICK) {
// Check canAcceptWork before calling queue.next() since it consumes the items
const canAcceptWork = this.chain.blsThreadPoolCanAcceptWork() && this.chain.regenCanAcceptWork();

for (const topic of executeGossipWorkOrder) {
// beacon block is guaranteed to be processed immedately
if (!canAcceptWork && !executeGossipWorkOrderObj[topic]?.bypassQueue) {
Expand Down
7 changes: 6 additions & 1 deletion packages/beacon-node/src/network/processor/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {PeerId} from "@libp2p/interface-peer-id";
import {Message} from "@libp2p/interface-pubsub";
import {GossipTopic} from "../gossip/index.js";
import {SlotRootHex} from "@lodestar/types";
import {GossipTopic, GossipType} from "../gossip/index.js";

export type GossipAttestationsWork = {
messages: PendingGossipsubMessage[];
Expand All @@ -15,3 +16,7 @@ export type PendingGossipsubMessage = {
seenTimestampSec: number;
startProcessUnixSec: number | null;
};

export type ExtractSlotRootFns = {
[K in GossipType]?: (data: Uint8Array) => SlotRootHex;
};
2 changes: 2 additions & 0 deletions packages/beacon-node/src/util/sszBytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export function getBlockRootFromAttestationSerialized(data: Uint8Array): BlockRo
}

export function getAttDataHashFromAttestationSerialized(data: Uint8Array): AttDataHash {
Comment thread
twoeths marked this conversation as resolved.
Resolved
// base64 is a bit efficient than hex
return Buffer.from(data.slice(ATTESTATION_SLOT_OFFSET, ATTESTATION_SLOT_OFFSET + 128)).toString("base64");
}

Expand All @@ -60,6 +61,7 @@ export function getBlockRootFromSignedAggregateAndProofSerialized(data: Uint8Arr
}

export function getAttDataHashFromSignedAggregateAndProofSerialized(data: Uint8Array): AttDataHash {
// base64 is a bit efficient than hex
return Buffer.from(
data.slice(SIGNED_AGGREGATE_AND_PROOF_SLOT_OFFSET, SIGNED_AGGREGATE_AND_PROOF_SLOT_OFFSET + 128)
).toString("base64");
Expand Down
4 changes: 4 additions & 0 deletions packages/types/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {Slot} from "./primitive/types.js";

export * from "./primitive/types.js";
export {ts as phase0} from "./phase0/index.js";
export {ts as altair} from "./altair/index.js";
Expand All @@ -15,3 +17,5 @@ export enum BlockSource {
builder = "builder",
engine = "engine",
}

export type SlotRootHex = {slot: Slot; root: RootHex};