@fluidframework/container-runtime 2.0.0-internal.2.3.1 → 2.0.0-internal.3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/blobManager.d.ts +3 -1
  2. package/dist/blobManager.d.ts.map +1 -1
  3. package/dist/blobManager.js +35 -2
  4. package/dist/blobManager.js.map +1 -1
  5. package/dist/containerRuntime.d.ts +45 -42
  6. package/dist/containerRuntime.d.ts.map +1 -1
  7. package/dist/containerRuntime.js +89 -40
  8. package/dist/containerRuntime.js.map +1 -1
  9. package/dist/dataStoreContext.d.ts +1 -0
  10. package/dist/dataStoreContext.d.ts.map +1 -1
  11. package/dist/dataStoreContext.js +7 -2
  12. package/dist/dataStoreContext.js.map +1 -1
  13. package/dist/garbageCollection.d.ts +15 -7
  14. package/dist/garbageCollection.d.ts.map +1 -1
  15. package/dist/garbageCollection.js +96 -36
  16. package/dist/garbageCollection.js.map +1 -1
  17. package/dist/opLifecycle/outbox.d.ts.map +1 -1
  18. package/dist/opLifecycle/outbox.js +0 -1
  19. package/dist/opLifecycle/outbox.js.map +1 -1
  20. package/dist/packageVersion.d.ts +1 -1
  21. package/dist/packageVersion.js +1 -1
  22. package/dist/packageVersion.js.map +1 -1
  23. package/dist/pendingStateManager.d.ts +4 -13
  24. package/dist/pendingStateManager.d.ts.map +1 -1
  25. package/dist/pendingStateManager.js +130 -160
  26. package/dist/pendingStateManager.js.map +1 -1
  27. package/dist/summarizer.js.map +1 -1
  28. package/dist/summarizerClientElection.d.ts +1 -2
  29. package/dist/summarizerClientElection.d.ts.map +1 -1
  30. package/dist/summarizerClientElection.js +3 -30
  31. package/dist/summarizerClientElection.js.map +1 -1
  32. package/dist/summarizerTypes.d.ts +0 -4
  33. package/dist/summarizerTypes.d.ts.map +1 -1
  34. package/dist/summarizerTypes.js.map +1 -1
  35. package/lib/blobManager.d.ts +3 -1
  36. package/lib/blobManager.d.ts.map +1 -1
  37. package/lib/blobManager.js +35 -2
  38. package/lib/blobManager.js.map +1 -1
  39. package/lib/containerRuntime.d.ts +45 -42
  40. package/lib/containerRuntime.d.ts.map +1 -1
  41. package/lib/containerRuntime.js +89 -40
  42. package/lib/containerRuntime.js.map +1 -1
  43. package/lib/dataStoreContext.d.ts +1 -0
  44. package/lib/dataStoreContext.d.ts.map +1 -1
  45. package/lib/dataStoreContext.js +7 -2
  46. package/lib/dataStoreContext.js.map +1 -1
  47. package/lib/garbageCollection.d.ts +15 -7
  48. package/lib/garbageCollection.d.ts.map +1 -1
  49. package/lib/garbageCollection.js +97 -37
  50. package/lib/garbageCollection.js.map +1 -1
  51. package/lib/opLifecycle/outbox.d.ts.map +1 -1
  52. package/lib/opLifecycle/outbox.js +0 -1
  53. package/lib/opLifecycle/outbox.js.map +1 -1
  54. package/lib/packageVersion.d.ts +1 -1
  55. package/lib/packageVersion.js +1 -1
  56. package/lib/packageVersion.js.map +1 -1
  57. package/lib/pendingStateManager.d.ts +4 -13
  58. package/lib/pendingStateManager.d.ts.map +1 -1
  59. package/lib/pendingStateManager.js +130 -160
  60. package/lib/pendingStateManager.js.map +1 -1
  61. package/lib/summarizer.js.map +1 -1
  62. package/lib/summarizerClientElection.d.ts +1 -2
  63. package/lib/summarizerClientElection.d.ts.map +1 -1
  64. package/lib/summarizerClientElection.js +3 -30
  65. package/lib/summarizerClientElection.js.map +1 -1
  66. package/lib/summarizerTypes.d.ts +0 -4
  67. package/lib/summarizerTypes.d.ts.map +1 -1
  68. package/lib/summarizerTypes.js.map +1 -1
  69. package/package.json +55 -20
  70. package/src/blobManager.ts +41 -2
  71. package/src/containerRuntime.ts +118 -85
  72. package/src/dataStoreContext.ts +12 -6
  73. package/src/garbageCollection.ts +103 -34
  74. package/src/opLifecycle/outbox.ts +0 -2
  75. package/src/packageVersion.ts +1 -1
  76. package/src/pendingStateManager.ts +146 -187
  77. package/src/summarizer.ts +1 -1
  78. package/src/summarizerClientElection.ts +1 -30
  79. package/src/summarizerTypes.ts +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"garbageCollection.js","sourceRoot":"","sources":["../src/garbageCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;;;;;;AAGH,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAE1E,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7G,OAAO,EACH,WAAW,EACX,2BAA2B,EAC3B,qBAAqB,EAErB,oBAAoB,EACpB,kBAAkB,GACrB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAiB,WAAW,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EACH,SAAS,EACT,YAAY,EACZ,kBAAkB,GAUrB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACH,UAAU,EACV,8BAA8B,EAG9B,kBAAkB,GACrB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACH,WAAW,EACX,aAAa,EACb,yBAAyB,EAEzB,gBAAgB,EAChB,gBAAgB,GACnB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAqB,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EACH,gBAAgB,EAChB,wBAAwB,EACxB,8BAA8B,EAC9B,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,EACvB,aAAa,EACb,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACnB,WAAW,EACX,eAAe,EACf,eAAe,EAClB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,EACH,YAAY,EAGZ,gBAAgB,EAEhB,2BAA2B,GAG9B,MAAM,iBAAiB,CAAC;AAwBzB,uDAAuD;AACvD,M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C3F,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAHzD,aAAQ,GAAR,QAAQ,CAAY;IAIzC,CAAC;IAED,KAAK,CAAC,SAAiB;QACnB,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,CAAC,SAAiB;QACrB,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC5C,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { assert, LazyPromise, Timer } from \"@fluidframework/common-utils\";\nimport { ICriticalContainerError } from \"@fluidframework/container-definitions\";\nimport { ClientSessionExpiredError, DataProcessingError, UsageError } from \"@fluidframework/container-utils\";\nimport { IRequestHeader } from \"@fluidframework/core-interfaces\";\nimport {\n cloneGCData,\n concatGarbageCollectionData,\n getGCDataFromSnapshot,\n IGCResult,\n runGarbageCollection,\n trimLeadingSlashes,\n} from \"@fluidframework/garbage-collector\";\nimport { ISnapshotTree, SummaryType } from \"@fluidframework/protocol-definitions\";\nimport {\n gcTreeKey,\n gcBlobPrefix,\n gcTombstoneBlobKey,\n IGarbageCollectionData,\n IGarbageCollectionDetailsBase,\n IGarbageCollectionSnapshotData,\n IGarbageCollectionState,\n ISummarizeResult,\n ITelemetryContext,\n IGarbageCollectionNodeData,\n IGarbageCollectionSummaryDetailsLegacy,\n ISummaryTreeWithStats,\n} from \"@fluidframework/runtime-definitions\";\nimport {\n mergeStats,\n packagePathToTelemetryProperty,\n ReadAndParseBlob,\n RefreshSummaryResult,\n SummaryTreeBuilder,\n} from \"@fluidframework/runtime-utils\";\nimport {\n ChildLogger,\n generateStack,\n loggerToMonitoringContext,\n MonitoringContext,\n PerformanceEvent,\n TelemetryDataTag,\n} from \"@fluidframework/telemetry-utils\";\n\nimport { IGCRuntimeOptions, RuntimeHeaders } from \"./containerRuntime\";\nimport { getSummaryForDatastores } from \"./dataStores\";\nimport {\n currentGCVersion,\n defaultInactiveTimeoutMs,\n defaultSessionExpiryDurationMs,\n disableSweepLogKey,\n disableTombstoneKey,\n gcVersionUpgradeToV2Key,\n gcTestModeKey,\n oneDayMs,\n runGCKey,\n runSessionExpiryKey,\n runSweepKey,\n stableGCVersion,\n trackGCStateKey\n} from \"./garbageCollectionConstants\";\nimport { sendGCTombstoneEvent } from \"./garbageCollectionTombstoneUtils\";\nimport { SweepReadyUsageDetectionHandler } from \"./gcSweepReadyUsageDetection\";\nimport {\n getGCVersion,\n GCVersion,\n IContainerRuntimeMetadata,\n metadataBlobName,\n ReadFluidDataStoreAttributes,\n dataStoreAttributesBlobName,\n IGCMetadata,\n ICreateContainerMetadata,\n} from \"./summaryFormat\";\n\n/** The statistics of the system state after a garbage collection run. */\nexport interface IGCStats {\n /** The number of nodes in the container. */\n nodeCount: number;\n /** The number of data stores in the container. */\n dataStoreCount: number;\n /** The number of attachment blobs in the container. */\n attachmentBlobCount: number;\n /** The number of unreferenced nodes in the container. */\n unrefNodeCount: number;\n /** The number of unreferenced data stores in the container. */\n unrefDataStoreCount: number;\n /** The number of unreferenced attachment blobs in the container. */\n unrefAttachmentBlobCount: number;\n /** The number of nodes whose reference state updated since last GC run. */\n updatedNodeCount: number;\n /** The number of data stores whose reference state updated since last GC run. */\n updatedDataStoreCount: number;\n /** The number of attachment blobs whose reference state updated since last GC run. */\n updatedAttachmentBlobCount: number;\n}\n\n/** The types of GC nodes in the GC reference graph. */\nexport const GCNodeType = {\n // Nodes that are for data stores.\n DataStore: \"DataStore\",\n // Nodes that are within a data store. For example, DDS nodes.\n SubDataStore: \"SubDataStore\",\n // Nodes that are for attachment blobs, i.e., blobs uploaded via BlobManager.\n Blob: \"Blob\",\n // Nodes that are neither of the above. For example, root node.\n Other: \"Other\",\n};\nexport type GCNodeType = typeof GCNodeType[keyof typeof GCNodeType];\n\n/** Defines the APIs for the runtime object to be passed to the garbage collector. */\nexport interface IGarbageCollectionRuntime {\n /** Before GC runs, called to notify the runtime to update any pending GC state. */\n updateStateBeforeGC(): Promise<void>;\n /** Returns the garbage collection data of the runtime. */\n getGCData(fullGC?: boolean): Promise<IGarbageCollectionData>;\n /** After GC has run, called to notify the runtime of routes that are used in it. */\n updateUsedRoutes(usedRoutes: string[]): void;\n /** After GC has run, called to notify the runtime of routes that are unused in it. */\n updateUnusedRoutes(unusedRoutes: string[]): void;\n /** Called to notify the runtime of routes that are tombstones. */\n updateTombstonedRoutes(tombstoneRoutes: string[]): void;\n /** Returns a referenced timestamp to be used to track unreferenced nodes. */\n getCurrentReferenceTimestampMs(): number | undefined;\n /** Returns the type of the GC node. */\n getNodeType(nodePath: string): GCNodeType;\n /** Called when the runtime should close because of an error. */\n closeFn: (error?: ICriticalContainerError) => void;\n}\n\n/** Defines the contract for the garbage collector. */\nexport interface IGarbageCollector {\n /** Tells whether GC should run or not. */\n readonly shouldRunGC: boolean;\n /** Tells whether the GC state in summary needs to be reset in the next summary. */\n readonly summaryStateNeedsReset: boolean;\n readonly trackGCState: boolean;\n /** Initialize the state from the base snapshot after its creation. */\n initializeBaseState(): Promise<void>;\n /** Run garbage collection and update the reference / used state of the system. */\n collectGarbage(\n options: { logger?: ITelemetryLogger; runSweep?: boolean; fullGC?: boolean; },\n ): Promise<IGCStats | undefined>;\n /** Summarizes the GC data and returns it as a summary tree. */\n summarize(\n fullTree: boolean,\n trackState: boolean,\n telemetryContext?: ITelemetryContext,\n ): ISummarizeResult | undefined;\n /** Returns the garbage collector specific metadata to be written into the summary. */\n getMetadata(): IGCMetadata;\n /** Returns the GC details generated from the base snapshot. */\n getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase>;\n /** Called when the latest summary of the system has been refreshed. */\n refreshLatestSummary(\n result: RefreshSummaryResult,\n proposalHandle: string | undefined,\n summaryRefSeq: number,\n readAndParseBlob: ReadAndParseBlob,\n ): Promise<void>;\n /** Called when a node is updated. Used to detect and log when an inactive node is changed or loaded. */\n nodeUpdated(\n nodePath: string,\n reason: \"Loaded\" | \"Changed\",\n timestampMs?: number,\n packagePath?: readonly string[],\n requestHeaders?: IRequestHeader,\n ): void;\n /** Called when a reference is added to a node. Used to identify nodes that were referenced between summaries. */\n addedOutboundReference(fromNodePath: string, toNodePath: string): void;\n setConnectionState(connected: boolean, clientId?: string): void;\n dispose(): void;\n}\n\n/** Parameters necessary for creating a GarbageCollector. */\nexport interface IGarbageCollectorCreateParams {\n readonly runtime: IGarbageCollectionRuntime;\n readonly gcOptions: IGCRuntimeOptions;\n readonly baseLogger: ITelemetryLogger;\n readonly existing: boolean;\n readonly metadata: IContainerRuntimeMetadata | undefined;\n readonly createContainerMetadata: ICreateContainerMetadata;\n readonly baseSnapshot: ISnapshotTree | undefined;\n readonly isSummarizerClient: boolean;\n readonly getNodePackagePath: (nodePath: string) => Promise<readonly string[] | undefined>;\n readonly getLastSummaryTimestampMs: () => number | undefined;\n readonly readAndParseBlob: ReadAndParseBlob;\n readonly activeConnection: () => boolean;\n readonly getContainerDiagnosticId: () => string;\n}\n\n/** The state of node that is unreferenced. */\nexport const UnreferencedState = {\n /** The node is active, i.e., it can become referenced again. */\n Active: \"Active\",\n /** The node is inactive, i.e., it should not become referenced. */\n Inactive: \"Inactive\",\n /** The node is ready to be deleted by the sweep phase. */\n SweepReady: \"SweepReady\",\n} as const;\nexport type UnreferencedState = typeof UnreferencedState[keyof typeof UnreferencedState];\n\n/** The event that is logged when unreferenced node is used after a certain time. */\ninterface IUnreferencedEventProps {\n usageType: \"Changed\" | \"Loaded\" | \"Revived\";\n state: UnreferencedState;\n id: string;\n type: GCNodeType;\n unrefTime: number;\n age: number;\n completedGCRuns: number;\n fromId?: string;\n timeout?: number;\n lastSummaryTime?: number;\n externalRequest?: boolean;\n viaHandle?: boolean;\n}\n\n/**\n * The GC data that is tracked for a summary that is submitted.\n */\ninterface IGCSummaryTrackingData {\n serializedGCState: string | undefined;\n serializedTombstones: string | undefined;\n}\n\n/**\n * Helper class that tracks the state of an unreferenced node such as the time it was unreferenced and if it can\n * be deleted by the sweep phase.\n */\nexport class UnreferencedStateTracker {\n private _state: UnreferencedState = UnreferencedState.Active;\n public get state(): UnreferencedState {\n return this._state;\n }\n\n /** Timer to indicate when an unreferenced object is considered Inactive */\n private readonly inactiveTimer: TimerWithNoDefaultTimeout;\n /** Timer to indicate when an unreferenced object is Sweep-Ready */\n private readonly sweepTimer: TimerWithNoDefaultTimeout;\n\n constructor(\n public readonly unreferencedTimestampMs: number,\n /** The time after which node transitions to Inactive state. */\n private readonly inactiveTimeoutMs: number,\n /** The current reference timestamp used to track how long this node has been unreferenced for. */\n currentReferenceTimestampMs: number,\n /** The time after which node transitions to SweepReady state; undefined if session expiry is disabled. */\n private readonly sweepTimeoutMs: number | undefined,\n ) {\n if (this.sweepTimeoutMs !== undefined) {\n assert(this.inactiveTimeoutMs <= this.sweepTimeoutMs,\n 0x3b0 /* inactive timeout must not be greater than the sweep timeout */);\n }\n\n this.sweepTimer = new TimerWithNoDefaultTimeout(\n () => {\n this._state = UnreferencedState.SweepReady;\n assert(!this.inactiveTimer.hasTimer, 0x3b1 /* inactiveTimer still running after sweepTimer fired! */);\n },\n );\n\n this.inactiveTimer = new TimerWithNoDefaultTimeout(() => {\n this._state = UnreferencedState.Inactive;\n\n // After the node becomes inactive, start the sweep timer after which the node will be ready for sweep.\n if (this.sweepTimeoutMs !== undefined) {\n this.sweepTimer.restart(this.sweepTimeoutMs - this.inactiveTimeoutMs);\n }\n });\n this.updateTracking(currentReferenceTimestampMs);\n }\n\n /* Updates the unreferenced state based on the provided timestamp. */\n public updateTracking(currentReferenceTimestampMs: number) {\n const unreferencedDurationMs = currentReferenceTimestampMs - this.unreferencedTimestampMs;\n\n // If the node has been unreferenced for sweep timeout amount of time, update the state to SweepReady.\n if (this.sweepTimeoutMs !== undefined && unreferencedDurationMs >= this.sweepTimeoutMs) {\n this._state = UnreferencedState.SweepReady;\n this.clearTimers();\n return;\n }\n\n // If the node has been unreferenced for inactive timeoutMs amount of time, update the state to inactive.\n // Also, start a timer for the sweep timeout.\n if (unreferencedDurationMs >= this.inactiveTimeoutMs) {\n this._state = UnreferencedState.Inactive;\n this.inactiveTimer.clear();\n\n if (this.sweepTimeoutMs !== undefined) {\n this.sweepTimer.restart(this.sweepTimeoutMs - unreferencedDurationMs);\n }\n return;\n }\n\n // The node is still active. Ensure the inactive timer is running with the proper remaining duration.\n this.inactiveTimer.restart(this.inactiveTimeoutMs - unreferencedDurationMs);\n }\n\n private clearTimers() {\n this.inactiveTimer.clear();\n this.sweepTimer.clear();\n }\n\n /** Stop tracking this node. Reset the unreferenced timers and state, if any. */\n public stopTracking() {\n this.clearTimers();\n this._state = UnreferencedState.Active;\n }\n}\n\n/**\n * The garbage collector for the container runtime. It consolidates the garbage collection functionality and maintains\n * its state across summaries.\n *\n * Node - represented as nodeId, it's a node on the GC graph\n *\n * Outbound Route - a path from one node to another node, think `nodeA` -\\> `nodeB`\n *\n * Graph - all nodes with their respective routes\n *\n * ```\n * GC Graph\n *\n * Node\n * NodeId = \"datastore1\"\n * / \\\\\n * OutboundRoute OutboundRoute\n * / \\\\\n * Node Node\n * NodeId = \"dds1\" NodeId = \"dds2\"\n * ```\n */\nexport class GarbageCollector implements IGarbageCollector {\n public static create(createParams: IGarbageCollectorCreateParams): IGarbageCollector {\n return new GarbageCollector(createParams);\n }\n\n /**\n * Tells whether the GC state needs to be reset in the next summary. We need to do this if:\n *\n * 1. GC was enabled and is now disabled. The GC state needs to be removed and everything becomes referenced.\n *\n * 2. GC was disabled and is now enabled. The GC state needs to be regenerated and added to summary.\n *\n * 3. GC is enabled and the latest summary state is refreshed from a snapshot that had GC disabled and vice-versa.\n *\n * 4. The GC version in the latest summary is different from the current GC version. This can happen if:\n *\n * 4.1. The summary this client loaded with has data from a different GC version.\n *\n * 4.2. This client's latest summary was updated from a snapshot that has a different GC version.\n */\n public get summaryStateNeedsReset(): boolean {\n return this.gcStateNeedsReset ||\n (this.shouldRunGC && this.latestSummaryGCVersion !== this.currentGCVersion);\n }\n\n /**\n * Tracks if GC is enabled for this document. This is specified during document creation and doesn't change\n * throughout its lifetime.\n */\n private readonly gcEnabled: boolean;\n /**\n * Tracks if sweep phase is enabled for this document. This is specified during document creation and doesn't change\n * throughout its lifetime.\n */\n private readonly sweepEnabled: boolean;\n\n /**\n * Tracks if GC should run or not. Even if GC is enabled for a document (see gcEnabled), it can be explicitly\n * disabled via runtime options or feature flags.\n */\n public readonly shouldRunGC: boolean;\n /**\n * Tracks if sweep phase should run or not. Even if the sweep phase is enabled for a document (see sweepEnabled), it\n * can be explicitly disabled via feature flags. It also won't run if session expiry is not enabled.\n */\n private readonly shouldRunSweep: boolean;\n\n public readonly trackGCState: boolean;\n\n private readonly testMode: boolean;\n private readonly tombstoneMode: boolean;\n private readonly mc: MonitoringContext;\n\n /**\n * Tells whether the GC state needs to be reset. This can happen under 3 conditions:\n *\n * 1. The base snapshot contains GC state but GC is disabled. This will happen the first time GC is disabled after\n * it was enabled before. GC state needs to be removed from summary and all nodes should be marked referenced.\n *\n * 2. The base snapshot does not have GC state but GC is enabled. This will happen the very first time GC runs on\n * a document and the first time GC is enabled after is was disabled before.\n *\n * 3. GC is enabled and the latest summary state is refreshed from a snapshot that had GC disabled and vice-versa.\n *\n * Note that the state will be reset only once for the first summary generated after this returns true. After that,\n * this will return false.\n */\n private get gcStateNeedsReset(): boolean {\n return this.wasGCRunInLatestSummary !== this.shouldRunGC;\n }\n // Tracks whether there was GC was run in latest summary being tracked.\n private wasGCRunInLatestSummary: boolean;\n\n // The current GC version that this container is running.\n private readonly currentGCVersion: GCVersion;\n // This is the version of GC data in the latest summary being tracked.\n private latestSummaryGCVersion: GCVersion;\n\n // Keeps track of the GC state from the last run.\n private gcDataFromLastRun: IGarbageCollectionData | undefined;\n // Keeps a list of references (edges in the GC graph) between GC runs. Each entry has a node id and a list of\n // outbound routes from that node.\n private readonly newReferencesSinceLastRun: Map<string, string[]> = new Map();\n private tombstones: string[] = [];\n\n /**\n * Keeps track of the GC data from the latest summary successfully submitted to and acked from the server.\n */\n private latestSummaryData: IGCSummaryTrackingData | undefined;\n /**\n * Keeps track of the GC data from the last summary submitted to the server but not yet acked.\n */\n private pendingSummaryData: IGCSummaryTrackingData | undefined;\n\n // Promise when resolved returns the GC data data in the base snapshot.\n private readonly baseSnapshotDataP: Promise<IGarbageCollectionSnapshotData | undefined>;\n // Promise when resolved initializes the GC state from the data in the base snapshot.\n private readonly initializeGCStateFromBaseSnapshotP: Promise<void>;\n // The GC details generated from the base snapshot.\n private readonly baseGCDetailsP: Promise<IGarbageCollectionDetailsBase>;\n // Map of node ids to their unreferenced state tracker.\n private readonly unreferencedNodesState: Map<string, UnreferencedStateTracker> = new Map();\n // The Timer responsible for closing the container when the session has expired\n private sessionExpiryTimer: Timer | undefined;\n\n // Keeps track of unreferenced events that are logged for a node. This is used to limit the log generation to one\n // per event per node.\n private readonly loggedUnreferencedEvents: Set<string> = new Set();\n // Queue for unreferenced events that should be logged the next time GC runs.\n private pendingEventsQueue: IUnreferencedEventProps[] = [];\n\n // The number of times GC has successfully completed on this instance of GarbageCollector.\n private completedRuns = 0;\n\n private readonly runtime: IGarbageCollectionRuntime;\n private readonly createContainerMetadata: ICreateContainerMetadata;\n private readonly gcOptions: IGCRuntimeOptions;\n private readonly isSummarizerClient: boolean;\n\n /** The time in ms to expire a session for a client for gc. */\n private readonly sessionExpiryTimeoutMs: number | undefined;\n /** The time after which an unreferenced node is inactive. */\n private readonly inactiveTimeoutMs: number;\n /** The time after which an unreferenced node is ready to be swept. */\n private readonly sweepTimeoutMs: number | undefined;\n\n /** For a given node path, returns the node's package path. */\n private readonly getNodePackagePath: (nodePath: string) => Promise<readonly string[] | undefined>;\n /** Returns the timestamp of the last summary generated for this container. */\n private readonly getLastSummaryTimestampMs: () => number | undefined;\n /** Returns true if connection is active, i.e. it's \"write\" connection and the runtime is connected. */\n private readonly activeConnection: () => boolean;\n\n /** Returns a list of all the configurations for garbage collection. */\n private get configs() {\n return {\n gcEnabled: this.gcEnabled,\n sweepEnabled: this.sweepEnabled,\n runGC: this.shouldRunGC,\n runSweep: this.shouldRunSweep,\n testMode: this.testMode,\n tombstoneMode: this.tombstoneMode,\n sessionExpiry: this.sessionExpiryTimeoutMs,\n sweepTimeout: this.sweepTimeoutMs,\n inactiveTimeout: this.inactiveTimeoutMs,\n trackGCState: this.trackGCState,\n ...this.gcOptions,\n };\n }\n\n /** Handler to respond to when a SweepReady object is used */\n private readonly sweepReadyUsageHandler: SweepReadyUsageDetectionHandler;\n\n protected constructor(createParams: IGarbageCollectorCreateParams) {\n this.runtime = createParams.runtime;\n this.isSummarizerClient = createParams.isSummarizerClient;\n this.gcOptions = createParams.gcOptions;\n this.createContainerMetadata = createParams.createContainerMetadata;\n this.getNodePackagePath = createParams.getNodePackagePath;\n this.getLastSummaryTimestampMs = createParams.getLastSummaryTimestampMs;\n this.activeConnection = createParams.activeConnection;\n\n const baseSnapshot = createParams.baseSnapshot;\n const metadata = createParams.metadata;\n const readAndParseBlob = createParams.readAndParseBlob;\n\n this.mc = loggerToMonitoringContext(ChildLogger.create(\n createParams.baseLogger, \"GarbageCollector\", { all: { completedGCRuns: () => this.completedRuns } },\n ));\n\n // If version upgrade is not enabled, fall back to the stable GC version.\n this.currentGCVersion =\n this.mc.config.getBoolean(gcVersionUpgradeToV2Key) === true ? currentGCVersion : stableGCVersion;\n\n this.sweepReadyUsageHandler = new SweepReadyUsageDetectionHandler(\n createParams.getContainerDiagnosticId(),\n this.mc,\n this.runtime.closeFn,\n );\n\n let prevSummaryGCVersion: number | undefined;\n\n /**\n * Sweep timeout is the time after which unreferenced content can be swept.\n * Sweep timeout = session expiry timeout + snapshot cache expiry timeout + one day buffer.\n *\n * The snapshot cache expiry timeout cannot be known precisely but the upper bound is 5 days.\n * The buffer is added to account for any clock skew or other edge cases.\n * We use server timestamps throughout so the skew should be minimal but make it 1 day to be safe.\n */\n function computeSweepTimeout(sessionExpiryTimeoutMs: number | undefined) {\n const maxSnapshotCacheExpiryMs = 5 * oneDayMs;\n const bufferMs = oneDayMs;\n return sessionExpiryTimeoutMs &&\n (sessionExpiryTimeoutMs + maxSnapshotCacheExpiryMs + bufferMs);\n }\n\n /**\n * The following GC state is enabled during container creation and cannot be changed throughout its lifetime:\n * 1. Whether running GC mark phase is allowed or not.\n * 2. Whether running GC sweep phase is allowed or not.\n * 3. Whether GC session expiry is enabled or not.\n * For existing containers, we get this information from the metadata blob of its summary.\n */\n if (createParams.existing) {\n prevSummaryGCVersion = getGCVersion(metadata);\n // Existing documents which did not have metadata blob or had GC disabled have version as 0. For all\n // other existing documents, GC is enabled.\n this.gcEnabled = prevSummaryGCVersion > 0;\n this.sweepEnabled = metadata?.sweepEnabled ?? false;\n this.sessionExpiryTimeoutMs = metadata?.sessionExpiryTimeoutMs;\n this.sweepTimeoutMs =\n metadata?.sweepTimeoutMs\n ?? computeSweepTimeout(this.sessionExpiryTimeoutMs); // Backfill old documents that didn't persist this\n } else {\n // Sweep should not be enabled without enabling GC mark phase. We could silently disable sweep in this\n // scenario but explicitly failing makes it clearer and promotes correct usage.\n if (this.gcOptions.sweepAllowed && this.gcOptions.gcAllowed === false) {\n throw new UsageError(\"GC sweep phase cannot be enabled without enabling GC mark phase\");\n }\n\n // This Test Override only applies for new containers\n const testOverrideSweepTimeoutMs =\n this.mc.config.getNumber(\"Fluid.GarbageCollection.TestOverride.SweepTimeoutMs\");\n\n // For new documents, GC is enabled by default. It can be explicitly disabled by setting the gcAllowed\n // flag in GC options to false.\n this.gcEnabled = this.gcOptions.gcAllowed !== false;\n // The sweep phase has to be explicitly enabled by setting the sweepAllowed flag in GC options to true.\n // ...unless we're using the TestOverride\n this.sweepEnabled = this.gcOptions.sweepAllowed === true || testOverrideSweepTimeoutMs !== undefined;\n\n // Set the Session Expiry only if the flag is enabled and GC is enabled.\n if (this.mc.config.getBoolean(runSessionExpiryKey) && this.gcEnabled) {\n this.sessionExpiryTimeoutMs = this.gcOptions.sessionExpiryTimeoutMs ?? defaultSessionExpiryDurationMs;\n }\n this.sweepTimeoutMs =\n testOverrideSweepTimeoutMs\n ?? computeSweepTimeout(this.sessionExpiryTimeoutMs);\n }\n\n // If session expiry is enabled, we need to close the container when the session expiry timeout expires.\n if (this.sessionExpiryTimeoutMs !== undefined) {\n // If Test Override config is set, override Session Expiry timeout.\n const overrideSessionExpiryTimeoutMs =\n this.mc.config.getNumber(\"Fluid.GarbageCollection.TestOverride.SessionExpiryMs\");\n const timeoutMs = overrideSessionExpiryTimeoutMs ?? this.sessionExpiryTimeoutMs;\n\n this.sessionExpiryTimer = new Timer(\n timeoutMs,\n () => { this.runtime.closeFn(new ClientSessionExpiredError(`Client session expired.`, timeoutMs)); },\n );\n this.sessionExpiryTimer.start();\n }\n\n // For existing document, the latest summary is the one that we loaded from. So, use its GC version as the\n // latest tracked GC version. For new documents, we will be writing the first summary with the current version.\n this.latestSummaryGCVersion = prevSummaryGCVersion ?? this.currentGCVersion;\n\n /**\n * Whether GC should run or not. The following conditions have to be met to run sweep:\n *\n * 1. GC should be enabled for this container.\n *\n * 2. GC should not be disabled via disableGC GC option.\n *\n * These conditions can be overridden via runGCKey feature flag.\n */\n this.shouldRunGC = this.mc.config.getBoolean(runGCKey) ?? (\n // GC must be enabled for the document.\n this.gcEnabled\n // GC must not be disabled via GC options.\n && !this.gcOptions.disableGC\n );\n\n /**\n * Whether sweep should run or not. The following conditions have to be met to run sweep:\n *\n * 1. Overall GC or mark phase must be enabled (this.shouldRunGC).\n * 2. Sweep timeout should be available. Without this, we wouldn't know when an object should be deleted.\n * 3. The driver must implement the policy limiting the age of snapshots used for loading. Otherwise\n * the Sweep Timeout calculation is not valid. We use the persisted value to ensure consistency over time.\n * 4. Sweep should be enabled for this container (this.sweepEnabled). This can be overridden via runSweep\n * feature flag.\n */\n this.shouldRunSweep =\n this.shouldRunGC\n && this.sweepTimeoutMs !== undefined\n && (this.mc.config.getBoolean(runSweepKey) ?? this.sweepEnabled);\n\n this.trackGCState = this.mc.config.getBoolean(trackGCStateKey) === true;\n\n // Override inactive timeout if test config or gc options to override it is set.\n this.inactiveTimeoutMs = this.mc.config.getNumber(\"Fluid.GarbageCollection.TestOverride.InactiveTimeoutMs\") ??\n this.gcOptions.inactiveTimeoutMs ??\n defaultInactiveTimeoutMs;\n\n // Inactive timeout must be greater than sweep timeout since a node goes from active -> inactive -> sweep ready.\n if (this.sweepTimeoutMs !== undefined && this.inactiveTimeoutMs > this.sweepTimeoutMs) {\n throw new UsageError(\"inactive timeout should not be greater than the sweep timeout\");\n }\n\n // Whether we are running in test mode. In this mode, unreferenced nodes are immediately deleted.\n this.testMode = this.mc.config.getBoolean(gcTestModeKey) ?? this.gcOptions.runGCInTestMode === true;\n // Whether we are running in tombstone mode. This is true by default unless disabled via feature flags.\n this.tombstoneMode = this.mc.config.getBoolean(disableTombstoneKey) !== true;\n\n // If GC ran in the container that generated the base snapshot, it will have a GC tree.\n this.wasGCRunInLatestSummary = baseSnapshot?.trees[gcTreeKey] !== undefined;\n\n // Get the GC data from the base snapshot. Use LazyPromise because we only want to do this once since it\n // it involves fetching blobs from storage which is expensive.\n this.baseSnapshotDataP = new LazyPromise<IGarbageCollectionSnapshotData | undefined>(async () => {\n if (baseSnapshot === undefined) {\n return undefined;\n }\n\n try {\n // For newer documents, GC data should be present in the GC tree in the root of the snapshot.\n const gcSnapshotTree = baseSnapshot.trees[gcTreeKey];\n if (gcSnapshotTree !== undefined) {\n return getGCDataFromSnapshot(\n gcSnapshotTree,\n readAndParseBlob,\n );\n }\n\n // back-compat - Older documents will have the GC blobs in each data store's summary tree. Get them and\n // consolidate into IGarbageCollectionState format.\n // Add a node for the root node that is not present in older snapshot format.\n const gcState: IGarbageCollectionState = { gcNodes: { \"/\": { outboundRoutes: [] } } };\n const dataStoreSnapshotTree = getSummaryForDatastores(baseSnapshot, metadata);\n assert(dataStoreSnapshotTree !== undefined,\n 0x2a8 /* \"Expected data store snapshot tree in base snapshot\" */);\n for (const [dsId, dsSnapshotTree] of Object.entries(dataStoreSnapshotTree.trees)) {\n const blobId = dsSnapshotTree.blobs[gcTreeKey];\n if (blobId === undefined) {\n continue;\n }\n\n const gcSummaryDetails = await readAndParseBlob<IGarbageCollectionSummaryDetailsLegacy>(blobId);\n // If there are no nodes for this data store, skip it.\n if (gcSummaryDetails.gcData?.gcNodes === undefined) {\n continue;\n }\n\n const dsRootId = `/${dsId}`;\n // Since we used to write GC data at data store level, we won't have an entry for the root (\"/\").\n // Construct that entry by adding root data store ids to its outbound routes.\n const initialSnapshotDetails = await readAndParseBlob<ReadFluidDataStoreAttributes>(\n dsSnapshotTree.blobs[dataStoreAttributesBlobName],\n );\n if (initialSnapshotDetails.isRootDataStore) {\n gcState.gcNodes[\"/\"].outboundRoutes.push(dsRootId);\n }\n\n for (const [id, outboundRoutes] of Object.entries(gcSummaryDetails.gcData.gcNodes)) {\n // Prefix the data store id to the GC node ids to make them relative to the root from being\n // relative to the data store. Similar to how its done in DataStore::getGCData.\n const rootId = id === \"/\" ? dsRootId : `${dsRootId}${id}`;\n gcState.gcNodes[rootId] = { outboundRoutes: Array.from(outboundRoutes) };\n }\n assert(gcState.gcNodes[dsRootId] !== undefined,\n 0x2a9 /* GC nodes for data store not in GC blob */);\n gcState.gcNodes[dsRootId].unreferencedTimestampMs = gcSummaryDetails.unrefTimestamp;\n }\n // If there is only one node (root node just added above), either GC is disabled or we are loading from\n // the first summary generated by detached container. In both cases, GC was not run - return undefined.\n return Object.keys(gcState.gcNodes).length === 1 ? undefined : { gcState, tombstones: undefined };\n } catch (error) {\n const dpe = DataProcessingError.wrapIfUnrecognized(\n error,\n \"FailedToInitializeGC\",\n );\n dpe.addTelemetryProperties({ gcConfigs: JSON.stringify(this.configs) });\n throw dpe;\n }\n });\n\n /**\n * Set up the initializer which initializes the GC state from the data in base snapshot. This is done when\n * connected in write mode or when GC runs the first time. It sets up all unreferenced nodes from the base\n * GC state and updates their inactive or sweep ready state.\n */\n this.initializeGCStateFromBaseSnapshotP = new LazyPromise<void>(async () => {\n /**\n * If there is no current reference timestamp, skip initialization. We need the current timestamp to track\n * how long objects have been unreferenced and if they can be deleted.\n *\n * Note that the only scenario where there is no reference timestamp is when no ops have ever been processed\n * for this container and it is in read mode. In this scenario, there is no point in running GC anyway\n * because references in the container do not change without any ops, i.e., there is nothing to collect.\n */\n const currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs();\n if (currentReferenceTimestampMs === undefined) {\n // Log an event so we can evaluate how often we run into this scenario.\n this.mc.logger.sendErrorEvent({\n eventName: \"GarbageCollectorInitializedWithoutTimestamp\",\n gcConfigs: JSON.stringify(this.configs),\n });\n return;\n }\n /**\n * The base snapshot data will not be present if the container is loaded from:\n * 1. The first summary created by the detached container.\n * 2. A summary that was generated with GC disabled.\n * 3. A summary that was generated before GC even existed.\n */\n const baseSnapshotData = await this.baseSnapshotDataP;\n if (baseSnapshotData === undefined) {\n return;\n }\n this.updateStateFromSnapshotData(baseSnapshotData, currentReferenceTimestampMs);\n });\n\n // Get the GC details from the GC state in the base summary. This is returned in getBaseGCDetails which is\n // used to initialize the GC state of all the nodes in the container.\n this.baseGCDetailsP = new LazyPromise<IGarbageCollectionDetailsBase>(async () => {\n const baseSnapshotData = await this.baseSnapshotDataP;\n if (baseSnapshotData === undefined) {\n return {};\n }\n\n const gcNodes: { [id: string]: string[]; } = {};\n for (const [nodeId, nodeData] of Object.entries(baseSnapshotData.gcState.gcNodes)) {\n gcNodes[nodeId] = Array.from(nodeData.outboundRoutes);\n }\n // Run GC on the nodes in the base summary to get the routes used in each node in the container.\n // This is an optimization for space (vs performance) wherein we don't need to store the used routes of\n // each node in the summary.\n const usedRoutes = runGarbageCollection(gcNodes, [\"/\"]).referencedNodeIds;\n\n return { gcData: { gcNodes }, usedRoutes };\n });\n\n // Log all the GC options and the state determined by the garbage collector. This is interesting only for the\n // summarizer client since it is the only one that runs GC. It also helps keep the telemetry less noisy.\n if (this.isSummarizerClient) {\n this.mc.logger.sendTelemetryEvent({\n eventName: \"GarbageCollectorLoaded\",\n gcConfigs: JSON.stringify(this.configs),\n });\n }\n }\n\n /**\n * Called during container initialization. Initialize the tombstone state so that object are marked as tombstones\n * before they are loaded or used. This is important to get accurate information of whether tombstoned object are\n * in use or not.\n */\n public async initializeBaseState(): Promise<void> {\n const baseSnapshotData = await this.baseSnapshotDataP;\n /**\n * The base snapshot data or tombstone state will not be present if the container is loaded from:\n * 1. The first summary created by the detached container.\n * 2. A summary that was generated with GC disabled.\n * 3. A summary that was generated before GC even existed.\n * 4. A summary that was generated with tombstone feature disabled.\n */\n if (!this.tombstoneMode || baseSnapshotData?.tombstones === undefined) {\n return;\n }\n this.tombstones = Array.from(baseSnapshotData.tombstones);\n this.runtime.updateTombstonedRoutes(this.tombstones);\n }\n\n /**\n * Update state from the given snapshot data. This is done during load and during refreshing state from a snapshot.\n * All current tracking is reset and updated from the data in the snapshot.\n * @param snapshotData - The snapshot data to update state from. If this is undefined, all GC state and tracking\n * is reset.\n * @param currentReferenceTimestampMs - The current reference timestamp for marking unreferenced nodes' unreferenced\n * timestamp.\n */\n private updateStateFromSnapshotData(\n snapshotData: IGarbageCollectionSnapshotData | undefined,\n currentReferenceTimestampMs: number,\n ) {\n /**\n * Note: \"newReferencesSinceLastRun\" is not reset here. This is done because there may be references since the\n * snapshot that we are updating state from. For example, this client may have processed ops till seq#1000 and\n * its refreshing state from a summary that happened at seq#900. In this case, there may be references between\n * seq#901 and seq#1000 that we don't want to reset.\n * Unfortunately, there is no way to track the seq# of ops that add references, so we choose to not reset any\n * references here. This should be fine because, in the worst case, we may end up updating the unreferenced\n * timestamp of a node which will delay its deletion. Although not ideal, this will only happen in rare\n * scenarios, so it should be okay.\n */\n\n // Clear all existing unreferenced state tracking.\n for (const [, nodeStateTracker] of this.unreferencedNodesState) {\n nodeStateTracker.stopTracking();\n };\n this.unreferencedNodesState.clear();\n\n // If tombstone mode is enabled, update tombstone information and also update all tombstoned nodes in the\n // container as per the state in the snapshot data.\n if (this.tombstoneMode) {\n this.tombstones = snapshotData?.tombstones ? Array.from(snapshotData.tombstones) : [];\n this.runtime.updateTombstonedRoutes(this.tombstones);\n }\n\n // If there is no snapshot data, it means this snapshot was generated with GC disabled. Unset all GC state.\n if (snapshotData === undefined) {\n this.gcDataFromLastRun = undefined;\n this.latestSummaryData = undefined;\n return;\n }\n\n // Update unreferenced state tracking as per the GC state in the snapshot data and update gcDataFromLastRun\n // to the GC data from the snapshot data.\n const gcNodes: { [id: string]: string[]; } = {};\n for (const [nodeId, nodeData] of Object.entries(snapshotData.gcState.gcNodes)) {\n if (nodeData.unreferencedTimestampMs !== undefined) {\n this.unreferencedNodesState.set(\n nodeId,\n new UnreferencedStateTracker(\n nodeData.unreferencedTimestampMs,\n this.inactiveTimeoutMs,\n currentReferenceTimestampMs,\n this.sweepTimeoutMs,\n ),\n );\n }\n gcNodes[nodeId] = Array.from(nodeData.outboundRoutes);\n }\n this.gcDataFromLastRun = { gcNodes };\n\n // If tracking state across summaries, update latest summary data from the snapshot's GC data.\n if (this.trackGCState) {\n this.latestSummaryData = {\n serializedGCState: JSON.stringify(generateSortedGCState(snapshotData.gcState)),\n serializedTombstones: JSON.stringify(snapshotData.tombstones),\n };\n }\n }\n\n /**\n * Called when the connection state of the runtime changes, i.e., it connects or disconnects. GC subscribes to this\n * to initialize the base state for non-summarizer clients so that they can track inactive / sweep ready nodes.\n * @param connected - Whether the runtime connected / disconnected.\n * @param clientId - The clientId of this runtime.\n */\n public setConnectionState(connected: boolean, clientId?: string | undefined): void {\n /**\n * For all clients, initialize the base state when the container becomes active, i.e., it transitions\n * to \"write\" mode. This will ensure that the container's own join op is processed and there is a recent\n * reference timestamp that will be used to update the state of unreferenced nodes. Also, all trailing ops which\n * could affect the GC state will have been processed.\n *\n * If GC is up-to-date for the client and the summarizing client, there will be an doubling of both\n * InactiveObject_Loaded and SweepReady_Loaded errors, as there will be one from the sending client and one from\n * the receiving summarizer client.\n *\n * Ideally, this initialization should only be done for summarizer client. However, we are currently rolling out\n * sweep in phases and we want to track when inactive and sweep ready objects are used in any client.\n */\n if (this.activeConnection() && this.shouldRunGC) {\n this.initializeGCStateFromBaseSnapshotP.catch((error) => {});\n }\n }\n\n /**\n * Runs garbage collection and updates the reference / used state of the nodes in the container.\n * @returns stats of the GC run or undefined if GC did not run.\n */\n public async collectGarbage(\n options: {\n /** Logger to use for logging GC events */\n logger?: ITelemetryLogger;\n /** True to run GC sweep phase after the mark phase */\n runSweep?: boolean;\n /** True to generate full GC data */\n fullGC?: boolean;\n },\n ): Promise<IGCStats | undefined> {\n const fullGC = options.fullGC ?? (this.gcOptions.runFullGC === true || this.summaryStateNeedsReset);\n const logger = options.logger\n ? ChildLogger.create(options.logger, undefined, { all: { completedGCRuns: () => this.completedRuns } })\n : this.mc.logger;\n\n /**\n * If there is no current reference timestamp, skip running GC. We need the current timestamp to track\n * how long objects have been unreferenced and if they should be deleted.\n *\n * Note that the only scenario where GC is called and there is no reference timestamp is when no ops have ever\n * been processed for this container and it is in read mode. In this scenario, there is no point in running GC\n * anyway because references in the container do not change without any ops, i.e., there is nothing to collect.\n */\n const currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs();\n if (currentReferenceTimestampMs === undefined) {\n // Log an event so we can evaluate how often we run into this scenario.\n logger.sendErrorEvent({\n eventName: \"CollectGarbageCalledWithoutTimestamp\",\n gcConfigs: JSON.stringify(this.configs),\n });\n return undefined;\n }\n\n return PerformanceEvent.timedExecAsync(logger, { eventName: \"GarbageCollection\" }, async (event) => {\n await this.runPreGCSteps();\n\n // Get the runtime's GC data and run GC on the reference graph in it.\n const gcData = await this.runtime.getGCData(fullGC);\n const gcResult = runGarbageCollection(gcData.gcNodes, [\"/\"]);\n\n const gcStats = await this.runPostGCSteps(gcData, gcResult, logger, currentReferenceTimestampMs);\n event.end({ ...gcStats, timestamp: currentReferenceTimestampMs });\n this.completedRuns++;\n return gcStats;\n }, { end: true, cancel: \"error\" });\n }\n\n private async runPreGCSteps() {\n // Ensure that state has been initialized from the base snapshot data.\n await this.initializeGCStateFromBaseSnapshotP;\n // Let the runtime update its pending state before GC runs.\n await this.runtime.updateStateBeforeGC();\n }\n\n private async runPostGCSteps(\n gcData: IGarbageCollectionData,\n gcResult: IGCResult,\n logger: ITelemetryLogger,\n currentReferenceTimestampMs: number,\n ): Promise<IGCStats> {\n // Generate statistics from the current run. This is done before updating the current state because it\n // generates some of its data based on previous state of the system.\n const gcStats = this.generateStats(gcResult);\n\n // Update the state since the last GC run. There can be nodes that were referenced between the last and\n // the current run. We need to identify than and update their unreferenced state if needed.\n this.updateStateSinceLastRun(gcData, logger);\n\n // Update the current state and update the runtime of all routes or ids that used as per the GC run.\n this.updateCurrentState(gcData, gcResult, currentReferenceTimestampMs);\n this.runtime.updateUsedRoutes(gcResult.referencedNodeIds);\n\n // Log events for objects that are ready to be deleted by sweep. When we have sweep enabled, we will\n // delete these objects here instead.\n this.logSweepEvents(logger, currentReferenceTimestampMs);\n\n // If we are running in GC test mode, delete objects for unused routes. This enables testing scenarios\n // involving access to deleted data.\n if (this.testMode) {\n this.runtime.updateUnusedRoutes(gcResult.deletedNodeIds);\n } else if (this.tombstoneMode) {\n // If we are running in GC tombstone mode, update tombstoned routes. This enables testing scenarios\n // involving access to \"deleted\" data without actually deleting the data from summaries.\n // Note: we will not tombstone in test mode.\n this.runtime.updateTombstonedRoutes(this.tombstones);\n }\n\n // Log pending unreferenced events such as a node being used after inactive. This is done after GC runs and\n // updates its state so that we don't send false positives based on intermediate state. For example, we may get\n // reference to an unreferenced node from another unreferenced node which means the node wasn't revived.\n await this.logUnreferencedEvents(logger);\n\n return gcStats;\n }\n\n /**\n * Summarizes the GC data and returns it as a summary tree.\n * We current write the entire GC state in a single blob. This can be modified later to write multiple\n * blobs. All the blob keys should start with `gcBlobPrefix`.\n */\n public summarize(\n fullTree: boolean,\n trackState: boolean,\n telemetryContext?: ITelemetryContext,\n ): ISummarizeResult | undefined {\n if (!this.shouldRunGC || this.gcDataFromLastRun === undefined) {\n return;\n }\n\n const gcState: IGarbageCollectionState = { gcNodes: {} };\n for (const [nodeId, outboundRoutes] of Object.entries(this.gcDataFromLastRun.gcNodes)) {\n gcState.gcNodes[nodeId] = {\n outboundRoutes,\n unreferencedTimestampMs: this.unreferencedNodesState.get(nodeId)?.unreferencedTimestampMs,\n };\n }\n\n const serializedGCState = JSON.stringify(generateSortedGCState(gcState));\n const serializedTombstones = this.tombstoneMode\n ? (this.tombstones.length > 0 ? JSON.stringify(this.tombstones.sort()) : undefined)\n : undefined;\n\n /**\n * Incremental summary of GC data - If any of the GC state or tombstone state hasn't changed since the last\n * summary, send summary handles for them. Otherwise, send the data in summary blobs.\n */\n if (this.trackGCState) {\n this.pendingSummaryData = { serializedGCState, serializedTombstones };\n if (trackState && !fullTree && this.latestSummaryData !== undefined) {\n // If neither GC state or tombstone state changed, send a summary handle for the entire GC data.\n if (this.latestSummaryData.serializedGCState === serializedGCState\n && this.latestSummaryData.serializedTombstones === serializedTombstones) {\n const stats = mergeStats();\n stats.handleNodeCount++;\n return {\n summary: {\n type: SummaryType.Handle,\n handle: `/${gcTreeKey}`,\n handleType: SummaryType.Tree,\n },\n stats,\n };\n }\n\n // If either or both of GC state or tombstone state changed, build a GC summary tree.\n return this.buildGCSummaryTree(serializedGCState, serializedTombstones, true /* trackState */);\n }\n }\n // If not tracking GC state, build a GC summary tree without any summary handles.\n return this.buildGCSummaryTree(serializedGCState, serializedTombstones, false /* trackState */);\n }\n\n /**\n * Builds the GC summary tree which contains GC state and tombstone state.\n * If trackState is false, both GC state and tombstone state are written as summary blobs.\n * If trackState is true, summary blob is written for GC state or tombstone state if they changed.\n * @param serializedGCState - The GC state serialized as string.\n * @param serializedTombstones - THe tombstone state serialized as string.\n * @param trackState - Whether we are tracking GC state across summaries.\n * @returns the GC summary tree.\n */\n private buildGCSummaryTree(\n serializedGCState: string,\n serializedTombstones: string | undefined,\n trackState: boolean,\n ): ISummaryTreeWithStats {\n const gcStateBlobKey = `${gcBlobPrefix}_root`;\n const builder = new SummaryTreeBuilder();\n\n // If the GC state hasn't changed, write a summary handle, else write a summary blob for it.\n if (this.latestSummaryData?.serializedGCState === serializedGCState && trackState) {\n builder.addHandle(gcStateBlobKey, SummaryType.Blob, `/${gcTreeKey}/${gcStateBlobKey}`);\n } else {\n builder.addBlob(gcStateBlobKey, serializedGCState);\n }\n\n // If there is no tombstone data, return only the GC state.\n if (serializedTombstones === undefined) {\n return builder.getSummaryTree();\n }\n\n // If the tombstone state hasn't changed, write a summary handle, else write a summary blob for it.\n if (this.latestSummaryData?.serializedTombstones === serializedTombstones && trackState) {\n builder.addHandle(gcTombstoneBlobKey, SummaryType.Blob, `/${gcTreeKey}/${gcTombstoneBlobKey}`);\n } else {\n builder.addBlob(gcTombstoneBlobKey, serializedTombstones);\n }\n return builder.getSummaryTree();\n }\n\n public getMetadata(): IGCMetadata {\n return {\n /**\n * If GC is enabled, the GC data is written using the current GC version and that is the gcFeature that goes\n * into the metadata blob. If GC is disabled, the gcFeature is 0.\n */\n gcFeature: this.gcEnabled ? this.currentGCVersion : 0,\n sessionExpiryTimeoutMs: this.sessionExpiryTimeoutMs,\n sweepEnabled: this.sweepEnabled,\n sweepTimeoutMs: this.sweepTimeoutMs,\n };\n }\n\n /**\n * Returns a the GC details generated from the base summary. This is used to initialize the GC state of the nodes\n * in the container.\n */\n public async getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase> {\n return this.baseGCDetailsP;\n }\n\n /**\n * Called to refresh the latest summary state. This happens when either a pending summary is acked or a snapshot\n * is downloaded and should be used to update the state.\n */\n public async refreshLatestSummary(\n result: RefreshSummaryResult,\n proposalHandle: string | undefined,\n summaryRefSeq: number,\n readAndParseBlob: ReadAndParseBlob,\n ): Promise<void> {\n // If the latest summary was updated and the summary was tracked, this client is the one that generated this\n // summary. So, update wasGCRunInLatestSummary.\n // Note that this has to be updated if GC did not run too. Otherwise, `gcStateNeedsReset` will always return\n // true in scenarios where GC is disabled but enabled in the snapshot we loaded from.\n if (result.latestSummaryUpdated && result.wasSummaryTracked) {\n this.wasGCRunInLatestSummary = this.shouldRunGC;\n }\n\n if (!result.latestSummaryUpdated || !this.shouldRunGC) {\n return;\n }\n\n // If the summary was tracked by this client, it was the one that generated the summary in the first place.\n // Update latest state from pending.\n if (result.wasSummaryTracked) {\n this.latestSummaryGCVersion = this.currentGCVersion;\n if (this.trackGCState) {\n this.latestSummaryData = this.pendingSummaryData;\n this.pendingSummaryData = undefined;\n }\n return;\n }\n\n // If the summary was not tracked by this client, the state should be updated from the downloaded snapshot.\n const snapshot = result.snapshot;\n const metadataBlobId = snapshot.blobs[metadataBlobName];\n if (metadataBlobId) {\n const metadata = await readAndParseBlob<IContainerRuntimeMetadata>(metadataBlobId);\n this.latestSummaryGCVersion = getGCVersion(metadata);\n }\n\n // The current reference timestamp should be available if we are refreshing state from a snapshot. There has\n // to be at least one op (summary op / ack, if nothing else) if a snapshot was taken.\n const currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs();\n if (currentReferenceTimestampMs === undefined) {\n throw DataProcessingError.create(\n \"No reference timestamp when updating GC state from snapshot\",\n \"refreshLatestSummary\",\n undefined,\n { proposalHandle, summaryRefSeq, details: JSON.stringify(this.configs) },\n );\n }\n const gcSnapshotTree = snapshot.trees[gcTreeKey];\n // If GC ran in the container that generated this snapshot, it will have a GC tree.\n this.wasGCRunInLatestSummary = gcSnapshotTree !== undefined;\n let latestGCData: IGarbageCollectionSnapshotData | undefined;\n if (gcSnapshotTree !== undefined) {\n latestGCData = await getGCDataFromSnapshot(\n gcSnapshotTree,\n readAndParseBlob,\n );\n }\n this.updateStateFromSnapshotData(latestGCData, currentReferenceTimestampMs);\n this.pendingSummaryData = undefined;\n }\n\n /**\n * Called when a node with the given id is updated. If the node is inactive, log an error.\n * @param nodePath - The id of the node that changed.\n * @param reason - Whether the node was loaded or changed.\n * @param timestampMs - The timestamp when the node changed.\n * @param packagePath - The package path of the node. This may not be available if the node hasn't been loaded yet.\n * @param requestHeaders - If the node was loaded via request path, the headers in the request.\n */\n public nodeUpdated(\n nodePath: string,\n reason: \"Loaded\" | \"Changed\",\n timestampMs?: number,\n packagePath?: readonly string[],\n requestHeaders?: IRequestHeader,\n ) {\n if (!this.shouldRunGC) {\n return;\n }\n\n const nodeStateTracker = this.unreferencedNodesState.get(nodePath);\n if (nodeStateTracker && nodeStateTracker.state !== UnreferencedState.Active) {\n this.inactiveNodeUsed(\n reason,\n nodePath,\n nodeStateTracker,\n undefined /* fromNodeId */,\n packagePath,\n timestampMs,\n requestHeaders,\n );\n }\n }\n\n /**\n * Called when an outbound reference is added to a node. This is used to identify all nodes that have been\n * referenced between summaries so that their unreferenced timestamp can be reset.\n *\n * @param fromNodePath - The node from which the reference is added.\n * @param toNodePath - The node to which the reference is added.\n */\n public addedOutboundReference(fromNodePath: string, toNodePath: string) {\n if (!this.shouldRunGC) {\n return;\n }\n\n const outboundRoutes = this.newReferencesSinceLastRun.get(fromNodePath) ?? [];\n outboundRoutes.push(toNodePath);\n this.newReferencesSinceLastRun.set(fromNodePath, outboundRoutes);\n\n const nodeStateTracker = this.unreferencedNodesState.get(toNodePath);\n if (nodeStateTracker && nodeStateTracker.state !== UnreferencedState.Active) {\n this.inactiveNodeUsed(\"Revived\", toNodePath, nodeStateTracker, fromNodePath);\n }\n\n if (this.tombstones.includes(toNodePath)) {\n const nodeType = this.runtime.getNodeType(toNodePath)\n\n let eventName = \"GC_Tombstone_SubDatastore_Revived\";\n if (nodeType === GCNodeType.DataStore) {\n eventName = \"GC_Tombstone_Datastore_Revived\";\n } else if (nodeType === GCNodeType.Blob) {\n eventName = \"GC_Tombstone_Blob_Revived\";\n }\n\n sendGCTombstoneEvent(\n this.mc,\n {\n eventName,\n category: \"generic\",\n isSummarizerClient: this.isSummarizerClient,\n url: trimLeadingSlashes(toNodePath),\n nodeType,\n },\n undefined /* packagePath */,\n );\n }\n }\n\n public dispose(): void {\n this.sessionExpiryTimer?.clear();\n this.sessionExpiryTimer = undefined;\n }\n\n /**\n * Updates the state of the system as per the current GC run. It does the following:\n * 1. Sets up the current GC state as per the gcData.\n * 2. Starts tracking for nodes that have become unreferenced in this run.\n * 3. Clears tracking for nodes that were unreferenced but became referenced in this run.\n * @param gcData - The data representing the reference graph on which GC is run.\n * @param gcResult - The result of the GC run on the gcData.\n * @param currentReferenceTimestampMs - The timestamp to be used for unreferenced nodes' timestamp.\n */\n private updateCurrentState(\n gcData: IGarbageCollectionData,\n gcResult: IGCResult,\n currentReferenceTimestampMs: number,\n ) {\n this.gcDataFromLastRun = cloneGCData(gcData);\n this.tombstones = [];\n this.newReferencesSinceLastRun.clear();\n\n // Iterate through the referenced nodes and stop tracking if they were unreferenced before.\n for (const nodeId of gcResult.referencedNodeIds) {\n const nodeStateTracker = this.unreferencedNodesState.get(nodeId);\n if (nodeStateTracker !== undefined) {\n // Stop tracking so as to clear out any running timers.\n nodeStateTracker.stopTracking();\n // Delete the node as we don't need to track it any more.\n this.unreferencedNodesState.delete(nodeId);\n }\n }\n\n /**\n * If a node became unreferenced in this run, start tracking it.\n * If a node was already unreferenced, update its tracking information. Since the current reference time is\n * from the ops seen, this will ensure that we keep updating the unreferenced state as time moves forward.\n */\n for (const nodeId of gcResult.deletedNodeIds) {\n const nodeStateTracker = this.unreferencedNodesState.get(nodeId);\n if (nodeStateTracker === undefined) {\n this.unreferencedNodesState.set(\n nodeId,\n new UnreferencedStateTracker(\n currentReferenceTimestampMs,\n this.inactiveTimeoutMs,\n currentReferenceTimestampMs,\n this.sweepTimeoutMs,\n ),\n );\n } else {\n nodeStateTracker.updateTracking(currentReferenceTimestampMs);\n if (this.tombstoneMode && nodeStateTracker.state === UnreferencedState.SweepReady) {\n const nodeType = this.runtime.getNodeType(nodeId);\n if (nodeType === GCNodeType.DataStore || nodeType === GCNodeType.Blob) {\n this.tombstones.push(nodeId);\n }\n }\n }\n }\n }\n\n /**\n * Since GC runs periodically, the GC data that is generated only tells us the state of the world at that point in\n * time. There can be nodes that were referenced in between two runs and their unreferenced state needs to be\n * updated. For example, in the following scenarios not updating the unreferenced timestamp can lead to deletion of\n * these objects while there can be in-memory referenced to it:\n * 1. A node transitions from `unreferenced -> referenced -> unreferenced` between two runs. When the reference is\n * added, the object may have been accessed and in-memory reference to it added.\n * 2. A reference is added from one unreferenced node to one or more unreferenced nodes. Even though the node[s] were\n * unreferenced, they could have been accessed and in-memory reference to them added.\n *\n * This function identifies nodes that were referenced since last run and removes their unreferenced state, if any.\n * If these nodes are currently unreferenced, they will be assigned new unreferenced state by the current run.\n */\n private updateStateSinceLastRun(currentGCData: IGarbageCollectionData, logger: ITelemetryLogger) {\n // If we haven't run GC before there is nothing to do.\n if (this.gcDataFromLastRun === undefined) {\n return;\n }\n\n // Find any references that haven't been identified correctly.\n const missingExplicitReferences = this.findMissingExplicitReferences(\n currentGCData,\n this.gcDataFromLastRun,\n this.newReferencesSinceLastRun,\n );\n\n if (missingExplicitReferences.length > 0) {\n missingExplicitReferences.forEach((missingExplicitReference) => {\n logger.sendErrorEvent({\n eventName: \"gcUnknownOutboundReferences\",\n gcNodeId: missingExplicitReference[0],\n gcRoutes: JSON.stringify(missingExplicitReference[1]),\n });\n });\n }\n\n // No references were added since the last run so we don't have to update reference states of any unreferenced\n // nodes\n if (this.newReferencesSinceLastRun.size === 0) {\n return;\n }\n\n /**\n * Generate a super set of the GC data that contains the nodes and edges from last run, plus any new node and\n * edges that have been added since then. To do this, combine the GC data from the last run and the current\n * run, and then add the references since last run.\n *\n * Note on why we need to combine the data from previous run, current run and all references in between -\n * 1. We need data from last run because some of its references may have been deleted since then. If those\n * references added new outbound references before they were deleted, we need to detect them.\n *\n * 2. We need new outbound references since last run because some of them may have been deleted later. If those\n * references added new outbound references before they were deleted, we need to detect them.\n *\n * 3. We need data from the current run because currently we may not detect when DDSes are referenced:\n * - We don't require DDSes handles to be stored in a referenced DDS.\n * - A new data store may have \"root\" DDSes already created and we don't detect them today.\n */\n const gcDataSuperSet = concatGarbageCollectionData(this.gcDataFromLastRun, currentGCData);\n const newOutboundRoutesSinceLastRun: string[] = [];\n this.newReferencesSinceLastRun.forEach((outboundRoutes: string[], sourceNodeId: string) => {\n if (gcDataSuperSet.gcNodes[sourceNodeId] === undefined) {\n gcDataSuperSet.gcNodes[sourceNodeId] = outboundRoutes;\n } else {\n gcDataSuperSet.gcNodes[sourceNodeId].push(...outboundRoutes);\n }\n newOutboundRoutesSinceLastRun.push(...outboundRoutes);\n });\n\n /**\n * Run GC on the above reference graph starting with root and all new outbound routes. This will generate a\n * list of all nodes that could have been referenced since the last run. If any of these nodes are unreferenced,\n * unreferenced, stop tracking them and remove from unreferenced list.\n * Note that some of these nodes may be unreferenced now and if so, the current run will mark them as\n * unreferenced and add unreferenced state.\n */\n const gcResult = runGarbageCollection(gcDataSuperSet.gcNodes, [\"/\", ...newOutboundRoutesSinceLastRun]);\n for (const nodeId of gcResult.referencedNodeIds) {\n const nodeStateTracker = this.unreferencedNodesState.get(nodeId);\n if (nodeStateTracker !== undefined) {\n // Stop tracking so as to clear out any running timers.\n nodeStateTracker.stopTracking();\n // Delete the unreferenced state as we don't need to track it any more.\n this.unreferencedNodesState.delete(nodeId);\n }\n }\n }\n\n /**\n * Finds all new references or outbound routes in the current graph that haven't been explicitly notified to GC.\n * The principle is that every new reference or outbound route must be notified to GC via the\n * addedOutboundReference method. It it hasn't, its a bug and we want to identify these scenarios.\n *\n * In more simple terms:\n * Missing Explicit References = Current References - Previous References - Explicitly Added References;\n *\n * @param currentGCData - The GC data (reference graph) from the current GC run.\n * @param previousGCData - The GC data (reference graph) from the previous GC run.\n * @param explicitReferences - New references added explicity between the previous and the current run.\n * @returns - a list of missing explicit references\n */\n private findMissingExplicitReferences(\n currentGCData: IGarbageCollectionData,\n previousGCData: IGarbageCollectionData,\n explicitReferences: Map<string, string[]>,\n ): [string, string[]][] {\n assert(\n previousGCData !== undefined,\n 0x2b7, /* \"Can't validate correctness without GC data from last run\" */\n );\n\n const currentGraph = Object.entries(currentGCData.gcNodes);\n const missingExplicitReferences: [string, string[]][] = [];\n currentGraph.forEach(([nodeId, currentOutboundRoutes]) => {\n const previousRoutes = previousGCData.gcNodes[nodeId] ?? [];\n const explicitRoutes = explicitReferences.get(nodeId) ?? [];\n const missingExplicitRoutes: string[] = [];\n\n /**\n * 1. For routes in the current GC data, routes that were not present in previous GC data and did not have\n * explicit references should be added to missing explicit routes list.\n * 2. Only include data store and blob routes since GC only works for these two.\n * Note: Due to a bug with de-duped blobs, only adding data store routes for now.\n * 3. Ignore DDS routes to their parent datastores since those were added implicitly. So, there won't be\n * explicit routes to them.\n */\n currentOutboundRoutes.forEach((route) => {\n const nodeType = this.runtime.getNodeType(route);\n if ((nodeType === GCNodeType.DataStore || nodeType === GCNodeType.Blob)\n && !nodeId.startsWith(route)\n && (!previousRoutes.includes(route) && !explicitRoutes.includes(route))) {\n missingExplicitRoutes.push(route);\n }\n });\n if (missingExplicitRoutes.length > 0) {\n missingExplicitReferences.push([nodeId, missingExplicitRoutes]);\n }\n });\n\n // Ideally missingExplicitReferences should always have a size 0\n return missingExplicitReferences;\n }\n\n /**\n * Generates the stats of a garbage collection run from the given results of the run.\n * @param gcResult - The result of a GC run.\n * @returns the GC stats of the GC run.\n */\n private generateStats(gcResult: IGCResult): IGCStats {\n const gcStats: IGCStats = {\n nodeCount: 0,\n dataStoreCount: 0,\n attachmentBlobCount: 0,\n unrefNodeCount: 0,\n unrefDataStoreCount: 0,\n unrefAttachmentBlobCount: 0,\n updatedNodeCount: 0,\n updatedDataStoreCount: 0,\n updatedAttachmentBlobCount: 0,\n };\n\n const updateNodeStats = (nodeId: string, referenced: boolean) => {\n gcStats.nodeCount++;\n // If there is no previous GC data, every node's state is generated and is considered as updated.\n // Otherwise, find out if any node went from referenced to unreferenced or vice-versa.\n const stateUpdated = this.gcDataFromLastRun === undefined ||\n this.unreferencedNodesState.has(nodeId) === referenced;\n if (stateUpdated) {\n gcStats.updatedNodeCount++;\n }\n if (!referenced) {\n gcStats.unrefNodeCount++;\n }\n\n if (this.runtime.getNodeType(nodeId) === GCNodeType.DataStore) {\n gcStats.dataStoreCount++;\n if (stateUpdated) {\n gcStats.updatedDataStoreCount++;\n }\n if (!referenced) {\n gcStats.unrefDataStoreCount++;\n }\n }\n if (this.runtime.getNodeType(nodeId) === GCNodeType.Blob) {\n gcStats.attachmentBlobCount++;\n if (stateUpdated) {\n gcStats.updatedAttachmentBlobCount++;\n }\n if (!referenced) {\n gcStats.unrefAttachmentBlobCount++;\n }\n }\n };\n\n for (const nodeId of gcResult.referencedNodeIds) {\n updateNodeStats(nodeId, true /* referenced */);\n }\n\n for (const nodeId of gcResult.deletedNodeIds) {\n updateNodeStats(nodeId, false /* referenced */);\n }\n\n return gcStats;\n }\n\n /**\n * For nodes that are ready to sweep, log an event for now. Until we start running sweep which deletes objects,\n * this will give us a view into how much deleted content a container has.\n */\n private logSweepEvents(logger: ITelemetryLogger, currentReferenceTimestampMs: number) {\n if (this.mc.config.getBoolean(disableSweepLogKey) === true || this.sweepTimeoutMs === undefined) {\n return;\n }\n\n this.unreferencedNodesState.forEach((nodeStateTracker, nodeId) => {\n if (nodeStateTracker.state !== UnreferencedState.SweepReady) {\n return;\n }\n\n const nodeType = this.runtime.getNodeType(nodeId);\n if (nodeType !== GCNodeType.DataStore && nodeType !== GCNodeType.Blob) {\n return;\n }\n\n // Log deleted event for each node only once to reduce noise in telemetry.\n const uniqueEventId = `Deleted-${nodeId}`;\n if (this.loggedUnreferencedEvents.has(uniqueEventId)) {\n return;\n }\n this.loggedUnreferencedEvents.add(uniqueEventId);\n logger.sendTelemetryEvent({\n eventName: \"GCObjectDeleted\",\n id: nodeId,\n type: nodeType,\n age: currentReferenceTimestampMs - nodeStateTracker.unreferencedTimestampMs,\n timeout: this.sweepTimeoutMs,\n completedGCRuns: this.completedRuns,\n lastSummaryTime: this.getLastSummaryTimestampMs(),\n });\n });\n }\n\n /**\n * Called when an inactive node is used after. Queue up an event that will be logged next time GC runs.\n */\n private inactiveNodeUsed(\n usageType: \"Changed\" | \"Loaded\" | \"Revived\",\n nodeId: string,\n nodeStateTracker: UnreferencedStateTracker,\n fromNodeId?: string,\n packagePath?: readonly string[],\n currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs(),\n requestHeaders?: IRequestHeader,\n ) {\n // If there is no reference timestamp to work with, no ops have been processed after creation. If so, skip\n // logging as nothing interesting would have happened worth logging.\n // If the node is active, skip logging.\n if (currentReferenceTimestampMs === undefined || nodeStateTracker.state === UnreferencedState.Active) {\n return;\n }\n\n // We only care about data stores and attachment blobs for this telemetry since GC only marks these objects\n // as unreferenced. Also, if an inactive DDS is used, the corresponding data store store will also be used.\n const nodeType = this.runtime.getNodeType(nodeId);\n if (nodeType !== GCNodeType.DataStore && nodeType !== GCNodeType.Blob) {\n return;\n }\n\n const state = nodeStateTracker.state;\n const uniqueEventId = `${state}-${nodeId}-${usageType}`;\n if (this.loggedUnreferencedEvents.has(uniqueEventId)) {\n return;\n }\n this.loggedUnreferencedEvents.add(uniqueEventId);\n\n const propsToLog = {\n id: nodeId,\n type: nodeType,\n unrefTime: nodeStateTracker.unreferencedTimestampMs,\n age: currentReferenceTimestampMs - nodeStateTracker.unreferencedTimestampMs,\n timeout: nodeStateTracker.state === UnreferencedState.Inactive\n ? this.inactiveTimeoutMs\n : this.sweepTimeoutMs,\n completedGCRuns: this.completedRuns,\n lastSummaryTime: this.getLastSummaryTimestampMs(),\n ...this.createContainerMetadata,\n externalRequest: requestHeaders?.[RuntimeHeaders.externalRequest],\n viaHandle: requestHeaders?.[RuntimeHeaders.viaHandle],\n fromId: fromNodeId,\n };\n\n // For summarizer client, queue the event so it is logged the next time GC runs if the event is still valid.\n // For non-summarizer client, log the event now since GC won't run on it. This may result in false positives\n // but it's a good signal nonetheless and we can consume it with a grain of salt.\n // Inactive errors are usages of Objects that are unreferenced for at least a period of 7 days.\n // SweepReady errors are usages of Objects that will be deleted by GC Sweep!\n if (this.isSummarizerClient) {\n this.pendingEventsQueue.push({ ...propsToLog, usageType, state });\n } else {\n // For non-summarizer clients, only log \"Loaded\" type events since these objects may not be loaded in the\n // summarizer clients if they are based off of user actions (such as scrolling to content for these objects)\n // Events generated:\n // InactiveObject_Loaded, SweepReadyObject_Loaded\n if (usageType === \"Loaded\") {\n const event = {\n ...propsToLog,\n eventName: `${state}Object_${usageType}`,\n pkg: packagePathToTelemetryProperty(packagePath),\n stack: generateStack(),\n };\n\n // Do not log the inactive object x events as error events as they are not the best signal for\n // detecting something wrong with GC either from the partner or from the runtime itself.\n if (state === UnreferencedState.Inactive) {\n this.mc.logger.sendTelemetryEvent(event);\n } else {\n this.mc.logger.sendErrorEvent(event);\n }\n }\n\n // If SweepReady Usage Detection is enabed, the handler may close the interactive container.\n // Once Sweep is fully implemented, this will be removed since the objects will be gone\n // and errors will arise elsewhere in the runtime\n if (state === UnreferencedState.SweepReady) {\n this.sweepReadyUsageHandler.usageDetectedInInteractiveClient({ ...propsToLog, usageType });\n }\n }\n }\n\n private async logUnreferencedEvents(logger: ITelemetryLogger) {\n // Events sent come only from the summarizer client. In between summaries, events are pushed to a queue and at\n // summary time they are then logged.\n // Events generated:\n // InactiveObject_Loaded, InactiveObject_Changed, InactiveObject_Revived\n // SweepReadyObject_Loaded, SweepReadyObject_Changed, SweepReadyObject_Revived\n for (const eventProps of this.pendingEventsQueue) {\n const { usageType, state, ...propsToLog } = eventProps;\n /**\n * Revived event is logged only if the node is active. If the node is not active, the reference to it was\n * from another unreferenced node and this scenario is not interesting to log.\n * Loaded and Changed events are logged only if the node is not active. If the node is active, it was\n * revived and a Revived event will be logged for it.\n */\n const nodeStateTracker = this.unreferencedNodesState.get(eventProps.id);\n const active = nodeStateTracker === undefined || nodeStateTracker.state === UnreferencedState.Active;\n if ((usageType === \"Revived\") === active) {\n const pkg = await this.getNodePackagePath(eventProps.id);\n const fromPkg = eventProps.fromId ? await this.getNodePackagePath(eventProps.fromId) : undefined;\n const event = {\n ...propsToLog,\n eventName: `${state}Object_${usageType}`,\n pkg: pkg ? { value: pkg.join(\"/\"), tag: TelemetryDataTag.CodeArtifact } : undefined,\n fromPkg: fromPkg ? { value: fromPkg.join(\"/\"), tag: TelemetryDataTag.CodeArtifact } : undefined,\n }\n\n if (state === UnreferencedState.Inactive) {\n logger.sendTelemetryEvent(event);\n } else {\n logger.sendErrorEvent(event);\n }\n }\n }\n this.pendingEventsQueue = [];\n }\n}\n\nfunction generateSortedGCState(gcState: IGarbageCollectionState): IGarbageCollectionState {\n const sortableArray: [string, IGarbageCollectionNodeData][] = Object.entries(gcState.gcNodes);\n sortableArray.sort(([a], [b]) => a.localeCompare(b));\n const sortedGCState: IGarbageCollectionState = { gcNodes: {} };\n for (const [nodeId, nodeData] of sortableArray) {\n nodeData.outboundRoutes.sort();\n sortedGCState.gcNodes[nodeId] = nodeData;\n }\n return sortedGCState;\n}\n\n/** A wrapper around common-utils Timer that requires the timeout when calling start/restart */\nclass TimerWithNoDefaultTimeout extends Timer {\n constructor(\n private readonly callback: () => void,\n ) {\n // The default timeout/handlers will never be used since start/restart pass overrides below\n super(0, () => { throw new Error(\"DefaultHandler should not be used\"); });\n }\n\n start(timeoutMs: number) {\n super.start(timeoutMs, this.callback);\n }\n\n restart(timeoutMs: number): void {\n super.restart(timeoutMs, this.callback);\n }\n}\n"]}
1
+ {"version":3,"file":"garbageCollection.js","sourceRoot":"","sources":["../src/garbageCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;;;;;;;;;;;;AAGH,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAE1E,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7G,OAAO,EACH,WAAW,EACX,2BAA2B,EAC3B,qBAAqB,EAErB,oBAAoB,EACpB,kBAAk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AAE;QAC5C,QAAQ,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;QAC/B,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;KAC5C;IACD,OAAO,aAAa,CAAC;AACzB,CAAC;AAED,+FAA+F;AAC/F,MAAM,yBAA0B,SAAQ,KAAK;IACzC,YACqB,QAAoB;QAErC,2FAA2F;QAC3F,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAHzD,aAAQ,GAAR,QAAQ,CAAY;IAIzC,CAAC;IAED,KAAK,CAAC,SAAiB;QACnB,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,CAAC,SAAiB;QACrB,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC5C,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { assert, LazyPromise, Timer } from \"@fluidframework/common-utils\";\nimport { ICriticalContainerError } from \"@fluidframework/container-definitions\";\nimport { ClientSessionExpiredError, DataProcessingError, UsageError } from \"@fluidframework/container-utils\";\nimport { IRequestHeader } from \"@fluidframework/core-interfaces\";\nimport {\n cloneGCData,\n concatGarbageCollectionData,\n getGCDataFromSnapshot,\n IGCResult,\n runGarbageCollection,\n trimLeadingSlashes,\n} from \"@fluidframework/garbage-collector\";\nimport { ISnapshotTree, SummaryType } from \"@fluidframework/protocol-definitions\";\nimport {\n gcTreeKey,\n gcBlobPrefix,\n gcTombstoneBlobKey,\n IGarbageCollectionData,\n IGarbageCollectionDetailsBase,\n IGarbageCollectionSnapshotData,\n IGarbageCollectionState,\n ISummarizeResult,\n ITelemetryContext,\n IGarbageCollectionNodeData,\n IGarbageCollectionSummaryDetailsLegacy,\n ISummaryTreeWithStats,\n gcDeletedBlobKey,\n} from \"@fluidframework/runtime-definitions\";\nimport {\n mergeStats,\n packagePathToTelemetryProperty,\n ReadAndParseBlob,\n RefreshSummaryResult,\n SummaryTreeBuilder,\n} from \"@fluidframework/runtime-utils\";\nimport {\n ChildLogger,\n generateStack,\n loggerToMonitoringContext,\n MonitoringContext,\n PerformanceEvent,\n TelemetryDataTag,\n} from \"@fluidframework/telemetry-utils\";\n\nimport { IGCRuntimeOptions, RuntimeHeaders } from \"./containerRuntime\";\nimport { getSummaryForDatastores } from \"./dataStores\";\nimport {\n currentGCVersion,\n defaultInactiveTimeoutMs,\n defaultSessionExpiryDurationMs,\n disableSweepLogKey,\n disableTombstoneKey,\n gcVersionUpgradeToV2Key,\n gcTestModeKey,\n oneDayMs,\n runGCKey,\n runSessionExpiryKey,\n runSweepKey,\n stableGCVersion,\n trackGCStateKey\n} from \"./garbageCollectionConstants\";\nimport { sendGCTombstoneEvent } from \"./garbageCollectionTombstoneUtils\";\nimport { SweepReadyUsageDetectionHandler } from \"./gcSweepReadyUsageDetection\";\nimport {\n getGCVersion,\n GCVersion,\n IContainerRuntimeMetadata,\n metadataBlobName,\n ReadFluidDataStoreAttributes,\n dataStoreAttributesBlobName,\n IGCMetadata,\n ICreateContainerMetadata,\n} from \"./summaryFormat\";\n\n/** The statistics of the system state after a garbage collection run. */\nexport interface IGCStats {\n /** The number of nodes in the container. */\n nodeCount: number;\n /** The number of data stores in the container. */\n dataStoreCount: number;\n /** The number of attachment blobs in the container. */\n attachmentBlobCount: number;\n /** The number of unreferenced nodes in the container. */\n unrefNodeCount: number;\n /** The number of unreferenced data stores in the container. */\n unrefDataStoreCount: number;\n /** The number of unreferenced attachment blobs in the container. */\n unrefAttachmentBlobCount: number;\n /** The number of nodes whose reference state updated since last GC run. */\n updatedNodeCount: number;\n /** The number of data stores whose reference state updated since last GC run. */\n updatedDataStoreCount: number;\n /** The number of attachment blobs whose reference state updated since last GC run. */\n updatedAttachmentBlobCount: number;\n}\n\n/** The types of GC nodes in the GC reference graph. */\nexport const GCNodeType = {\n // Nodes that are for data stores.\n DataStore: \"DataStore\",\n // Nodes that are within a data store. For example, DDS nodes.\n SubDataStore: \"SubDataStore\",\n // Nodes that are for attachment blobs, i.e., blobs uploaded via BlobManager.\n Blob: \"Blob\",\n // Nodes that are neither of the above. For example, root node.\n Other: \"Other\",\n};\nexport type GCNodeType = typeof GCNodeType[keyof typeof GCNodeType];\n\n/** Defines the APIs for the runtime object to be passed to the garbage collector. */\nexport interface IGarbageCollectionRuntime {\n /** Before GC runs, called to notify the runtime to update any pending GC state. */\n updateStateBeforeGC(): Promise<void>;\n /** Returns the garbage collection data of the runtime. */\n getGCData(fullGC?: boolean): Promise<IGarbageCollectionData>;\n /** After GC has run, called to notify the runtime of routes that are used in it. */\n updateUsedRoutes(usedRoutes: string[]): void;\n /** After GC has run, called to notify the runtime of routes that are unused in it. */\n updateUnusedRoutes(unusedRoutes: string[]): void;\n /** Called to notify the runtime of routes that are tombstones. */\n updateTombstonedRoutes(tombstoneRoutes: string[]): void;\n /** Returns a referenced timestamp to be used to track unreferenced nodes. */\n getCurrentReferenceTimestampMs(): number | undefined;\n /** Returns the type of the GC node. */\n getNodeType(nodePath: string): GCNodeType;\n /** Called when the runtime should close because of an error. */\n closeFn: (error?: ICriticalContainerError) => void;\n}\n\n/** Defines the contract for the garbage collector. */\nexport interface IGarbageCollector {\n /** Tells whether GC should run or not. */\n readonly shouldRunGC: boolean;\n /** Tells whether the GC state in summary needs to be reset in the next summary. */\n readonly summaryStateNeedsReset: boolean;\n readonly trackGCState: boolean;\n /** Initialize the state from the base snapshot after its creation. */\n initializeBaseState(): Promise<void>;\n /** Run garbage collection and update the reference / used state of the system. */\n collectGarbage(\n options: { logger?: ITelemetryLogger; runSweep?: boolean; fullGC?: boolean; },\n ): Promise<IGCStats | undefined>;\n /** Summarizes the GC data and returns it as a summary tree. */\n summarize(\n fullTree: boolean,\n trackState: boolean,\n telemetryContext?: ITelemetryContext,\n ): ISummarizeResult | undefined;\n /** Returns the garbage collector specific metadata to be written into the summary. */\n getMetadata(): IGCMetadata;\n /** Returns the GC details generated from the base snapshot. */\n getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase>;\n /** Called when the latest summary of the system has been refreshed. */\n refreshLatestSummary(\n result: RefreshSummaryResult,\n proposalHandle: string | undefined,\n summaryRefSeq: number,\n readAndParseBlob: ReadAndParseBlob,\n ): Promise<void>;\n /** Called when a node is updated. Used to detect and log when an inactive node is changed or loaded. */\n nodeUpdated(\n nodePath: string,\n reason: \"Loaded\" | \"Changed\",\n timestampMs?: number,\n packagePath?: readonly string[],\n requestHeaders?: IRequestHeader,\n ): void;\n /** Called when a reference is added to a node. Used to identify nodes that were referenced between summaries. */\n addedOutboundReference(fromNodePath: string, toNodePath: string): void;\n /** Returns true if this node has been deleted by GC during sweep phase. */\n isNodeDeleted(nodePath: string): boolean;\n setConnectionState(connected: boolean, clientId?: string): void;\n dispose(): void;\n}\n\n/** Parameters necessary for creating a GarbageCollector. */\nexport interface IGarbageCollectorCreateParams {\n readonly runtime: IGarbageCollectionRuntime;\n readonly gcOptions: IGCRuntimeOptions;\n readonly baseLogger: ITelemetryLogger;\n readonly existing: boolean;\n readonly metadata: IContainerRuntimeMetadata | undefined;\n readonly createContainerMetadata: ICreateContainerMetadata;\n readonly baseSnapshot: ISnapshotTree | undefined;\n readonly isSummarizerClient: boolean;\n readonly getNodePackagePath: (nodePath: string) => Promise<readonly string[] | undefined>;\n readonly getLastSummaryTimestampMs: () => number | undefined;\n readonly readAndParseBlob: ReadAndParseBlob;\n readonly activeConnection: () => boolean;\n readonly getContainerDiagnosticId: () => string;\n}\n\n/** The state of node that is unreferenced. */\nexport const UnreferencedState = {\n /** The node is active, i.e., it can become referenced again. */\n Active: \"Active\",\n /** The node is inactive, i.e., it should not become referenced. */\n Inactive: \"Inactive\",\n /** The node is ready to be deleted by the sweep phase. */\n SweepReady: \"SweepReady\",\n} as const;\nexport type UnreferencedState = typeof UnreferencedState[keyof typeof UnreferencedState];\n\n/** The event that is logged when unreferenced node is used after a certain time. */\ninterface IUnreferencedEventProps {\n usageType: \"Changed\" | \"Loaded\" | \"Revived\";\n state: UnreferencedState;\n id: string;\n type: GCNodeType;\n unrefTime: number;\n age: number;\n completedGCRuns: number;\n fromId?: string;\n timeout?: number;\n lastSummaryTime?: number;\n externalRequest?: boolean;\n viaHandle?: boolean;\n}\n\n/**\n * The GC data that is tracked for a summary that is submitted.\n */\ninterface IGCSummaryTrackingData {\n serializedGCState: string | undefined;\n serializedTombstones: string | undefined;\n serializedDeletedNodes: string | undefined;\n}\n\n/**\n * Helper class that tracks the state of an unreferenced node such as the time it was unreferenced and if it can\n * be deleted by the sweep phase.\n */\nexport class UnreferencedStateTracker {\n private _state: UnreferencedState = UnreferencedState.Active;\n public get state(): UnreferencedState {\n return this._state;\n }\n\n /** Timer to indicate when an unreferenced object is considered Inactive */\n private readonly inactiveTimer: TimerWithNoDefaultTimeout;\n /** Timer to indicate when an unreferenced object is Sweep-Ready */\n private readonly sweepTimer: TimerWithNoDefaultTimeout;\n\n constructor(\n public readonly unreferencedTimestampMs: number,\n /** The time after which node transitions to Inactive state. */\n private readonly inactiveTimeoutMs: number,\n /** The current reference timestamp used to track how long this node has been unreferenced for. */\n currentReferenceTimestampMs: number,\n /** The time after which node transitions to SweepReady state; undefined if session expiry is disabled. */\n private readonly sweepTimeoutMs: number | undefined,\n ) {\n if (this.sweepTimeoutMs !== undefined) {\n assert(this.inactiveTimeoutMs <= this.sweepTimeoutMs,\n 0x3b0 /* inactive timeout must not be greater than the sweep timeout */);\n }\n\n this.sweepTimer = new TimerWithNoDefaultTimeout(\n () => {\n this._state = UnreferencedState.SweepReady;\n assert(!this.inactiveTimer.hasTimer, 0x3b1 /* inactiveTimer still running after sweepTimer fired! */);\n },\n );\n\n this.inactiveTimer = new TimerWithNoDefaultTimeout(() => {\n this._state = UnreferencedState.Inactive;\n\n // After the node becomes inactive, start the sweep timer after which the node will be ready for sweep.\n if (this.sweepTimeoutMs !== undefined) {\n this.sweepTimer.restart(this.sweepTimeoutMs - this.inactiveTimeoutMs);\n }\n });\n this.updateTracking(currentReferenceTimestampMs);\n }\n\n /* Updates the unreferenced state based on the provided timestamp. */\n public updateTracking(currentReferenceTimestampMs: number) {\n const unreferencedDurationMs = currentReferenceTimestampMs - this.unreferencedTimestampMs;\n\n // If the node has been unreferenced for sweep timeout amount of time, update the state to SweepReady.\n if (this.sweepTimeoutMs !== undefined && unreferencedDurationMs >= this.sweepTimeoutMs) {\n this._state = UnreferencedState.SweepReady;\n this.clearTimers();\n return;\n }\n\n // If the node has been unreferenced for inactive timeoutMs amount of time, update the state to inactive.\n // Also, start a timer for the sweep timeout.\n if (unreferencedDurationMs >= this.inactiveTimeoutMs) {\n this._state = UnreferencedState.Inactive;\n this.inactiveTimer.clear();\n\n if (this.sweepTimeoutMs !== undefined) {\n this.sweepTimer.restart(this.sweepTimeoutMs - unreferencedDurationMs);\n }\n return;\n }\n\n // The node is still active. Ensure the inactive timer is running with the proper remaining duration.\n this.inactiveTimer.restart(this.inactiveTimeoutMs - unreferencedDurationMs);\n }\n\n private clearTimers() {\n this.inactiveTimer.clear();\n this.sweepTimer.clear();\n }\n\n /** Stop tracking this node. Reset the unreferenced timers and state, if any. */\n public stopTracking() {\n this.clearTimers();\n this._state = UnreferencedState.Active;\n }\n}\n\n/**\n * The garbage collector for the container runtime. It consolidates the garbage collection functionality and maintains\n * its state across summaries.\n *\n * Node - represented as nodeId, it's a node on the GC graph\n *\n * Outbound Route - a path from one node to another node, think `nodeA` -\\> `nodeB`\n *\n * Graph - all nodes with their respective routes\n *\n * ```\n * GC Graph\n *\n * Node\n * NodeId = \"datastore1\"\n * / \\\\\n * OutboundRoute OutboundRoute\n * / \\\\\n * Node Node\n * NodeId = \"dds1\" NodeId = \"dds2\"\n * ```\n */\nexport class GarbageCollector implements IGarbageCollector {\n public static create(createParams: IGarbageCollectorCreateParams): IGarbageCollector {\n return new GarbageCollector(createParams);\n }\n\n /**\n * Tells whether the GC state needs to be reset in the next summary. We need to do this if:\n *\n * 1. GC was enabled and is now disabled. The GC state needs to be removed and everything becomes referenced.\n *\n * 2. GC was disabled and is now enabled. The GC state needs to be regenerated and added to summary.\n *\n * 3. GC is enabled and the latest summary state is refreshed from a snapshot that had GC disabled and vice-versa.\n *\n * 4. The GC version in the latest summary is different from the current GC version. This can happen if:\n *\n * 4.1. The summary this client loaded with has data from a different GC version.\n *\n * 4.2. This client's latest summary was updated from a snapshot that has a different GC version.\n */\n public get summaryStateNeedsReset(): boolean {\n return this.gcStateNeedsReset ||\n (this.shouldRunGC && this.latestSummaryGCVersion !== this.currentGCVersion);\n }\n\n /**\n * Tracks if GC is enabled for this document. This is specified during document creation and doesn't change\n * throughout its lifetime.\n */\n private readonly gcEnabled: boolean;\n /**\n * Tracks if sweep phase is enabled for this document. This is specified during document creation and doesn't change\n * throughout its lifetime.\n */\n private readonly sweepEnabled: boolean;\n\n /**\n * Tracks if GC should run or not. Even if GC is enabled for a document (see gcEnabled), it can be explicitly\n * disabled via runtime options or feature flags.\n */\n public readonly shouldRunGC: boolean;\n /**\n * Tracks if sweep phase should run or not. Even if the sweep phase is enabled for a document (see sweepEnabled), it\n * can be explicitly disabled via feature flags. It also won't run if session expiry is not enabled.\n */\n private readonly shouldRunSweep: boolean;\n\n public readonly trackGCState: boolean;\n\n private readonly testMode: boolean;\n private readonly tombstoneMode: boolean;\n private readonly mc: MonitoringContext;\n\n /**\n * Tells whether the GC state needs to be reset. This can happen under 3 conditions:\n *\n * 1. The base snapshot contains GC state but GC is disabled. This will happen the first time GC is disabled after\n * it was enabled before. GC state needs to be removed from summary and all nodes should be marked referenced.\n *\n * 2. The base snapshot does not have GC state but GC is enabled. This will happen the very first time GC runs on\n * a document and the first time GC is enabled after is was disabled before.\n *\n * 3. GC is enabled and the latest summary state is refreshed from a snapshot that had GC disabled and vice-versa.\n *\n * Note that the state will be reset only once for the first summary generated after this returns true. After that,\n * this will return false.\n */\n private get gcStateNeedsReset(): boolean {\n return this.wasGCRunInLatestSummary !== this.shouldRunGC;\n }\n // Tracks whether there was GC was run in latest summary being tracked.\n private wasGCRunInLatestSummary: boolean;\n\n // The current GC version that this container is running.\n private readonly currentGCVersion: GCVersion;\n // This is the version of GC data in the latest summary being tracked.\n private latestSummaryGCVersion: GCVersion;\n\n // Keeps track of the GC state from the last run.\n private gcDataFromLastRun: IGarbageCollectionData | undefined;\n // Keeps a list of references (edges in the GC graph) between GC runs. Each entry has a node id and a list of\n // outbound routes from that node.\n private readonly newReferencesSinceLastRun: Map<string, string[]> = new Map();\n // A list of nodes that have been tombstoned.\n private tombstones: string[] = [];\n // A list of nodes that have been deleted during sweep phase.\n private deletedNodes: Set<string> = new Set();\n\n /**\n * Keeps track of the GC data from the latest summary successfully submitted to and acked from the server.\n */\n private latestSummaryData: IGCSummaryTrackingData | undefined;\n /**\n * Keeps track of the GC data from the last summary submitted to the server but not yet acked.\n */\n private pendingSummaryData: IGCSummaryTrackingData | undefined;\n\n // Promise when resolved returns the GC data data in the base snapshot.\n private readonly baseSnapshotDataP: Promise<IGarbageCollectionSnapshotData | undefined>;\n // Promise when resolved initializes the GC state from the data in the base snapshot.\n private readonly initializeGCStateFromBaseSnapshotP: Promise<void>;\n // The GC details generated from the base snapshot.\n private readonly baseGCDetailsP: Promise<IGarbageCollectionDetailsBase>;\n // Map of node ids to their unreferenced state tracker.\n private readonly unreferencedNodesState: Map<string, UnreferencedStateTracker> = new Map();\n // The Timer responsible for closing the container when the session has expired\n private sessionExpiryTimer: Timer | undefined;\n\n // Keeps track of unreferenced events that are logged for a node. This is used to limit the log generation to one\n // per event per node.\n private readonly loggedUnreferencedEvents: Set<string> = new Set();\n // Queue for unreferenced events that should be logged the next time GC runs.\n private pendingEventsQueue: IUnreferencedEventProps[] = [];\n\n // The number of times GC has successfully completed on this instance of GarbageCollector.\n private completedRuns = 0;\n\n private readonly runtime: IGarbageCollectionRuntime;\n private readonly createContainerMetadata: ICreateContainerMetadata;\n private readonly gcOptions: IGCRuntimeOptions;\n private readonly isSummarizerClient: boolean;\n\n /** The time in ms to expire a session for a client for gc. */\n private readonly sessionExpiryTimeoutMs: number | undefined;\n /** The time after which an unreferenced node is inactive. */\n private readonly inactiveTimeoutMs: number;\n /** The time after which an unreferenced node is ready to be swept. */\n private readonly sweepTimeoutMs: number | undefined;\n\n /** For a given node path, returns the node's package path. */\n private readonly getNodePackagePath: (nodePath: string) => Promise<readonly string[] | undefined>;\n /** Returns the timestamp of the last summary generated for this container. */\n private readonly getLastSummaryTimestampMs: () => number | undefined;\n /** Returns true if connection is active, i.e. it's \"write\" connection and the runtime is connected. */\n private readonly activeConnection: () => boolean;\n\n /** Returns a list of all the configurations for garbage collection. */\n private get configs() {\n return {\n gcEnabled: this.gcEnabled,\n sweepEnabled: this.sweepEnabled,\n runGC: this.shouldRunGC,\n runSweep: this.shouldRunSweep,\n testMode: this.testMode,\n tombstoneMode: this.tombstoneMode,\n sessionExpiry: this.sessionExpiryTimeoutMs,\n sweepTimeout: this.sweepTimeoutMs,\n inactiveTimeout: this.inactiveTimeoutMs,\n trackGCState: this.trackGCState,\n ...this.gcOptions,\n };\n }\n\n /** Handler to respond to when a SweepReady object is used */\n private readonly sweepReadyUsageHandler: SweepReadyUsageDetectionHandler;\n\n protected constructor(createParams: IGarbageCollectorCreateParams) {\n this.runtime = createParams.runtime;\n this.isSummarizerClient = createParams.isSummarizerClient;\n this.gcOptions = createParams.gcOptions;\n this.createContainerMetadata = createParams.createContainerMetadata;\n this.getNodePackagePath = createParams.getNodePackagePath;\n this.getLastSummaryTimestampMs = createParams.getLastSummaryTimestampMs;\n this.activeConnection = createParams.activeConnection;\n\n const baseSnapshot = createParams.baseSnapshot;\n const metadata = createParams.metadata;\n const readAndParseBlob = createParams.readAndParseBlob;\n\n this.mc = loggerToMonitoringContext(ChildLogger.create(\n createParams.baseLogger, \"GarbageCollector\", { all: { completedGCRuns: () => this.completedRuns } },\n ));\n\n // If version upgrade is not enabled, fall back to the stable GC version.\n this.currentGCVersion =\n this.mc.config.getBoolean(gcVersionUpgradeToV2Key) === true ? currentGCVersion : stableGCVersion;\n\n this.sweepReadyUsageHandler = new SweepReadyUsageDetectionHandler(\n createParams.getContainerDiagnosticId(),\n this.mc,\n this.runtime.closeFn,\n );\n\n let prevSummaryGCVersion: number | undefined;\n\n /**\n * Sweep timeout is the time after which unreferenced content can be swept.\n * Sweep timeout = session expiry timeout + snapshot cache expiry timeout + one day buffer.\n *\n * The snapshot cache expiry timeout cannot be known precisely but the upper bound is 5 days.\n * The buffer is added to account for any clock skew or other edge cases.\n * We use server timestamps throughout so the skew should be minimal but make it 1 day to be safe.\n */\n function computeSweepTimeout(sessionExpiryTimeoutMs: number | undefined) {\n const maxSnapshotCacheExpiryMs = 5 * oneDayMs;\n const bufferMs = oneDayMs;\n return sessionExpiryTimeoutMs &&\n (sessionExpiryTimeoutMs + maxSnapshotCacheExpiryMs + bufferMs);\n }\n\n /**\n * The following GC state is enabled during container creation and cannot be changed throughout its lifetime:\n * 1. Whether running GC mark phase is allowed or not.\n * 2. Whether running GC sweep phase is allowed or not.\n * 3. Whether GC session expiry is enabled or not.\n * For existing containers, we get this information from the metadata blob of its summary.\n */\n if (createParams.existing) {\n prevSummaryGCVersion = getGCVersion(metadata);\n // Existing documents which did not have metadata blob or had GC disabled have version as 0. For all\n // other existing documents, GC is enabled.\n this.gcEnabled = prevSummaryGCVersion > 0;\n this.sweepEnabled = metadata?.sweepEnabled ?? false;\n this.sessionExpiryTimeoutMs = metadata?.sessionExpiryTimeoutMs;\n this.sweepTimeoutMs =\n metadata?.sweepTimeoutMs\n ?? computeSweepTimeout(this.sessionExpiryTimeoutMs); // Backfill old documents that didn't persist this\n } else {\n // Sweep should not be enabled without enabling GC mark phase. We could silently disable sweep in this\n // scenario but explicitly failing makes it clearer and promotes correct usage.\n if (this.gcOptions.sweepAllowed && this.gcOptions.gcAllowed === false) {\n throw new UsageError(\"GC sweep phase cannot be enabled without enabling GC mark phase\");\n }\n\n // This Test Override only applies for new containers\n const testOverrideSweepTimeoutMs =\n this.mc.config.getNumber(\"Fluid.GarbageCollection.TestOverride.SweepTimeoutMs\");\n\n // For new documents, GC is enabled by default. It can be explicitly disabled by setting the gcAllowed\n // flag in GC options to false.\n this.gcEnabled = this.gcOptions.gcAllowed !== false;\n // The sweep phase has to be explicitly enabled by setting the sweepAllowed flag in GC options to true.\n this.sweepEnabled = this.gcOptions.sweepAllowed === true;\n\n // Set the Session Expiry only if the flag is enabled and GC is enabled.\n if (this.mc.config.getBoolean(runSessionExpiryKey) && this.gcEnabled) {\n this.sessionExpiryTimeoutMs = this.gcOptions.sessionExpiryTimeoutMs ?? defaultSessionExpiryDurationMs;\n }\n this.sweepTimeoutMs =\n testOverrideSweepTimeoutMs\n ?? computeSweepTimeout(this.sessionExpiryTimeoutMs);\n }\n\n // If session expiry is enabled, we need to close the container when the session expiry timeout expires.\n if (this.sessionExpiryTimeoutMs !== undefined) {\n // If Test Override config is set, override Session Expiry timeout.\n const overrideSessionExpiryTimeoutMs =\n this.mc.config.getNumber(\"Fluid.GarbageCollection.TestOverride.SessionExpiryMs\");\n const timeoutMs = overrideSessionExpiryTimeoutMs ?? this.sessionExpiryTimeoutMs;\n\n this.sessionExpiryTimer = new Timer(\n timeoutMs,\n () => { this.runtime.closeFn(new ClientSessionExpiredError(`Client session expired.`, timeoutMs)); },\n );\n this.sessionExpiryTimer.start();\n }\n\n // For existing document, the latest summary is the one that we loaded from. So, use its GC version as the\n // latest tracked GC version. For new documents, we will be writing the first summary with the current version.\n this.latestSummaryGCVersion = prevSummaryGCVersion ?? this.currentGCVersion;\n\n /**\n * Whether GC should run or not. The following conditions have to be met to run sweep:\n *\n * 1. GC should be enabled for this container.\n *\n * 2. GC should not be disabled via disableGC GC option.\n *\n * These conditions can be overridden via runGCKey feature flag.\n */\n this.shouldRunGC = this.mc.config.getBoolean(runGCKey) ?? (\n // GC must be enabled for the document.\n this.gcEnabled\n // GC must not be disabled via GC options.\n && !this.gcOptions.disableGC\n );\n\n /**\n * Whether sweep should run or not. The following conditions have to be met to run sweep:\n *\n * 1. Overall GC or mark phase must be enabled (this.shouldRunGC).\n * 2. Sweep timeout should be available. Without this, we wouldn't know when an object should be deleted.\n * 3. The driver must implement the policy limiting the age of snapshots used for loading. Otherwise\n * the Sweep Timeout calculation is not valid. We use the persisted value to ensure consistency over time.\n * 4. Sweep should be enabled for this container (this.sweepEnabled). This can be overridden via runSweep\n * feature flag.\n */\n this.shouldRunSweep =\n this.shouldRunGC\n && this.sweepTimeoutMs !== undefined\n && (this.mc.config.getBoolean(runSweepKey) ?? this.sweepEnabled);\n\n this.trackGCState = this.mc.config.getBoolean(trackGCStateKey) === true;\n\n // Override inactive timeout if test config or gc options to override it is set.\n this.inactiveTimeoutMs = this.mc.config.getNumber(\"Fluid.GarbageCollection.TestOverride.InactiveTimeoutMs\") ??\n this.gcOptions.inactiveTimeoutMs ??\n defaultInactiveTimeoutMs;\n\n // Inactive timeout must be greater than sweep timeout since a node goes from active -> inactive -> sweep ready.\n if (this.sweepTimeoutMs !== undefined && this.inactiveTimeoutMs > this.sweepTimeoutMs) {\n throw new UsageError(\"inactive timeout should not be greater than the sweep timeout\");\n }\n\n // Whether we are running in test mode. In this mode, unreferenced nodes are immediately deleted.\n this.testMode = this.mc.config.getBoolean(gcTestModeKey) ?? this.gcOptions.runGCInTestMode === true;\n // Whether we are running in tombstone mode. This is enabled by default if sweep won't run. It can be disabled\n // via feature flags.\n this.tombstoneMode = !this.shouldRunSweep && this.mc.config.getBoolean(disableTombstoneKey) !== true;\n\n // If GC ran in the container that generated the base snapshot, it will have a GC tree.\n this.wasGCRunInLatestSummary = baseSnapshot?.trees[gcTreeKey] !== undefined;\n\n // Get the GC data from the base snapshot. Use LazyPromise because we only want to do this once since it\n // it involves fetching blobs from storage which is expensive.\n this.baseSnapshotDataP = new LazyPromise<IGarbageCollectionSnapshotData | undefined>(async () => {\n if (baseSnapshot === undefined) {\n return undefined;\n }\n\n try {\n // For newer documents, GC data should be present in the GC tree in the root of the snapshot.\n const gcSnapshotTree = baseSnapshot.trees[gcTreeKey];\n if (gcSnapshotTree !== undefined) {\n return getGCDataFromSnapshot(\n gcSnapshotTree,\n readAndParseBlob,\n );\n }\n\n // back-compat - Older documents will have the GC blobs in each data store's summary tree. Get them and\n // consolidate into IGarbageCollectionState format.\n // Add a node for the root node that is not present in older snapshot format.\n const gcState: IGarbageCollectionState = { gcNodes: { \"/\": { outboundRoutes: [] } } };\n const dataStoreSnapshotTree = getSummaryForDatastores(baseSnapshot, metadata);\n assert(dataStoreSnapshotTree !== undefined,\n 0x2a8 /* \"Expected data store snapshot tree in base snapshot\" */);\n for (const [dsId, dsSnapshotTree] of Object.entries(dataStoreSnapshotTree.trees)) {\n const blobId = dsSnapshotTree.blobs[gcTreeKey];\n if (blobId === undefined) {\n continue;\n }\n\n const gcSummaryDetails = await readAndParseBlob<IGarbageCollectionSummaryDetailsLegacy>(blobId);\n // If there are no nodes for this data store, skip it.\n if (gcSummaryDetails.gcData?.gcNodes === undefined) {\n continue;\n }\n\n const dsRootId = `/${dsId}`;\n // Since we used to write GC data at data store level, we won't have an entry for the root (\"/\").\n // Construct that entry by adding root data store ids to its outbound routes.\n const initialSnapshotDetails = await readAndParseBlob<ReadFluidDataStoreAttributes>(\n dsSnapshotTree.blobs[dataStoreAttributesBlobName],\n );\n if (initialSnapshotDetails.isRootDataStore) {\n gcState.gcNodes[\"/\"].outboundRoutes.push(dsRootId);\n }\n\n for (const [id, outboundRoutes] of Object.entries(gcSummaryDetails.gcData.gcNodes)) {\n // Prefix the data store id to the GC node ids to make them relative to the root from being\n // relative to the data store. Similar to how its done in DataStore::getGCData.\n const rootId = id === \"/\" ? dsRootId : `${dsRootId}${id}`;\n gcState.gcNodes[rootId] = { outboundRoutes: Array.from(outboundRoutes) };\n }\n assert(gcState.gcNodes[dsRootId] !== undefined,\n 0x2a9 /* GC nodes for data store not in GC blob */);\n gcState.gcNodes[dsRootId].unreferencedTimestampMs = gcSummaryDetails.unrefTimestamp;\n }\n // If there is only one node (root node just added above), either GC is disabled or we are loading from\n // the first summary generated by detached container. In both cases, GC was not run - return undefined.\n return Object.keys(gcState.gcNodes).length === 1\n ? undefined\n : { gcState, tombstones: undefined, deletedNodes: undefined };\n } catch (error) {\n const dpe = DataProcessingError.wrapIfUnrecognized(\n error,\n \"FailedToInitializeGC\",\n );\n dpe.addTelemetryProperties({ gcConfigs: JSON.stringify(this.configs) });\n throw dpe;\n }\n });\n\n /**\n * Set up the initializer which initializes the GC state from the data in base snapshot. This is done when\n * connected in write mode or when GC runs the first time. It sets up all unreferenced nodes from the base\n * GC state and updates their inactive or sweep ready state.\n */\n this.initializeGCStateFromBaseSnapshotP = new LazyPromise<void>(async () => {\n /**\n * If there is no current reference timestamp, skip initialization. We need the current timestamp to track\n * how long objects have been unreferenced and if they can be deleted.\n *\n * Note that the only scenario where there is no reference timestamp is when no ops have ever been processed\n * for this container and it is in read mode. In this scenario, there is no point in running GC anyway\n * because references in the container do not change without any ops, i.e., there is nothing to collect.\n */\n const currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs();\n if (currentReferenceTimestampMs === undefined) {\n // Log an event so we can evaluate how often we run into this scenario.\n this.mc.logger.sendErrorEvent({\n eventName: \"GarbageCollectorInitializedWithoutTimestamp\",\n gcConfigs: JSON.stringify(this.configs),\n });\n return;\n }\n /**\n * The base snapshot data will not be present if the container is loaded from:\n * 1. The first summary created by the detached container.\n * 2. A summary that was generated with GC disabled.\n * 3. A summary that was generated before GC even existed.\n */\n const baseSnapshotData = await this.baseSnapshotDataP;\n if (baseSnapshotData === undefined) {\n return;\n }\n this.updateStateFromSnapshotData(baseSnapshotData, currentReferenceTimestampMs);\n });\n\n // Get the GC details from the GC state in the base summary. This is returned in getBaseGCDetails which is\n // used to initialize the GC state of all the nodes in the container.\n this.baseGCDetailsP = new LazyPromise<IGarbageCollectionDetailsBase>(async () => {\n const baseSnapshotData = await this.baseSnapshotDataP;\n if (baseSnapshotData === undefined) {\n return {};\n }\n\n const gcNodes: { [id: string]: string[]; } = {};\n for (const [nodeId, nodeData] of Object.entries(baseSnapshotData.gcState.gcNodes)) {\n gcNodes[nodeId] = Array.from(nodeData.outboundRoutes);\n }\n // Run GC on the nodes in the base summary to get the routes used in each node in the container.\n // This is an optimization for space (vs performance) wherein we don't need to store the used routes of\n // each node in the summary.\n const usedRoutes = runGarbageCollection(gcNodes, [\"/\"]).referencedNodeIds;\n\n return { gcData: { gcNodes }, usedRoutes };\n });\n\n // Log all the GC options and the state determined by the garbage collector. This is interesting only for the\n // summarizer client since it is the only one that runs GC. It also helps keep the telemetry less noisy.\n if (this.isSummarizerClient) {\n this.mc.logger.sendTelemetryEvent({\n eventName: \"GarbageCollectorLoaded\",\n gcConfigs: JSON.stringify(this.configs),\n });\n }\n }\n\n /**\n * Called during container initialization. Initialize from the tombstone state in the base snapshot. This is done\n * during initialization so that deleted or tombstoned objects are marked as such before they are loaded or used.\n */\n public async initializeBaseState(): Promise<void> {\n const baseSnapshotData = await this.baseSnapshotDataP;\n /**\n * The base snapshot data will not be present if the container is loaded from:\n * 1. The first summary created by the detached container.\n * 2. A summary that was generated with GC disabled.\n * 3. A summary that was generated before GC even existed.\n */\n if (baseSnapshotData === undefined) {\n return;\n }\n\n // Initialize the deleted nodes from the snapshot. This is done irrespective of whether sweep is enabled or not\n // to identify deleted nodes' usage.\n if (baseSnapshotData.deletedNodes !== undefined) {\n this.deletedNodes = new Set(baseSnapshotData.deletedNodes);\n }\n\n // If running in tombstone mode, initialize the tombstone state from the snapshot. Also, notify the runtime of\n // tombstone routes.\n if (this.tombstoneMode && baseSnapshotData.tombstones !== undefined) {\n this.tombstones = Array.from(baseSnapshotData.tombstones);\n this.runtime.updateTombstonedRoutes(this.tombstones);\n }\n }\n\n /**\n * Update state from the given snapshot data. This is done during load and during refreshing state from a snapshot.\n * All current tracking is reset and updated from the data in the snapshot.\n * @param snapshotData - The snapshot data to update state from. If this is undefined, all GC state and tracking\n * is reset.\n * @param currentReferenceTimestampMs - The current reference timestamp for marking unreferenced nodes' unreferenced\n * timestamp.\n */\n private updateStateFromSnapshotData(\n snapshotData: IGarbageCollectionSnapshotData | undefined,\n currentReferenceTimestampMs: number,\n ) {\n /**\n * Note: \"newReferencesSinceLastRun\" is not reset here. This is done because there may be references since the\n * snapshot that we are updating state from. For example, this client may have processed ops till seq#1000 and\n * its refreshing state from a summary that happened at seq#900. In this case, there may be references between\n * seq#901 and seq#1000 that we don't want to reset.\n * Unfortunately, there is no way to track the seq# of ops that add references, so we choose to not reset any\n * references here. This should be fine because, in the worst case, we may end up updating the unreferenced\n * timestamp of a node which will delay its deletion. Although not ideal, this will only happen in rare\n * scenarios, so it should be okay.\n */\n\n // Clear all existing unreferenced state tracking.\n for (const [, nodeStateTracker] of this.unreferencedNodesState) {\n nodeStateTracker.stopTracking();\n };\n this.unreferencedNodesState.clear();\n\n // If running sweep, the tombstone state represents the list of nodes that have been deleted during sweep.\n // If running in tombstone mode, the tombstone state represents the list of nodes that have been marked as\n // tombstones.\n // If this call is because we are refreshing from a snapshot due to an ack, it is likely that the GC state\n // in the snapshot is newer than this client's. And so, the deleted / tombstone nodes need to be updated.\n if (this.shouldRunSweep) {\n const snapshotDeletedNodes = snapshotData?.tombstones ? new Set(snapshotData.tombstones) : undefined;\n // If the snapshot contains deleted nodes that are not yet deleted by this client, ask the runtime to\n // delete them.\n if (snapshotDeletedNodes !== undefined) {\n const newDeletedNodes: string[] = [];\n for (const nodeId of snapshotDeletedNodes) {\n if (!this.deletedNodes.has(nodeId)) {\n newDeletedNodes.push(nodeId);\n }\n }\n if (newDeletedNodes.length > 0) {\n // Call container runtime to delete these nodes and add deleted nodes to this.deletedNodes.\n }\n }\n } else if (this.tombstoneMode) {\n // The snapshot may contain more or fewer tombstone nodes than this client. Update tombstone state and\n // notify the runtime to update its state as well.\n this.tombstones = snapshotData?.tombstones ? Array.from(snapshotData.tombstones) : [];\n this.runtime.updateTombstonedRoutes(this.tombstones);\n }\n\n // If there is no snapshot data, it means this snapshot was generated with GC disabled. Unset all GC state.\n if (snapshotData === undefined) {\n this.gcDataFromLastRun = undefined;\n this.latestSummaryData = undefined;\n return;\n }\n\n // Update unreferenced state tracking as per the GC state in the snapshot data and update gcDataFromLastRun\n // to the GC data from the snapshot data.\n const gcNodes: { [id: string]: string[]; } = {};\n for (const [nodeId, nodeData] of Object.entries(snapshotData.gcState.gcNodes)) {\n if (nodeData.unreferencedTimestampMs !== undefined) {\n this.unreferencedNodesState.set(\n nodeId,\n new UnreferencedStateTracker(\n nodeData.unreferencedTimestampMs,\n this.inactiveTimeoutMs,\n currentReferenceTimestampMs,\n this.sweepTimeoutMs,\n ),\n );\n }\n gcNodes[nodeId] = Array.from(nodeData.outboundRoutes);\n }\n this.gcDataFromLastRun = { gcNodes };\n\n // If tracking state across summaries, update latest summary data from the snapshot's GC data.\n if (this.trackGCState) {\n this.latestSummaryData = {\n serializedGCState: JSON.stringify(generateSortedGCState(snapshotData.gcState)),\n serializedTombstones: JSON.stringify(snapshotData.tombstones),\n serializedDeletedNodes: JSON.stringify(snapshotData.deletedNodes),\n };\n }\n }\n\n /**\n * Called when the connection state of the runtime changes, i.e., it connects or disconnects. GC subscribes to this\n * to initialize the base state for non-summarizer clients so that they can track inactive / sweep ready nodes.\n * @param connected - Whether the runtime connected / disconnected.\n * @param clientId - The clientId of this runtime.\n */\n public setConnectionState(connected: boolean, clientId?: string | undefined): void {\n /**\n * For all clients, initialize the base state when the container becomes active, i.e., it transitions\n * to \"write\" mode. This will ensure that the container's own join op is processed and there is a recent\n * reference timestamp that will be used to update the state of unreferenced nodes. Also, all trailing ops which\n * could affect the GC state will have been processed.\n *\n * If GC is up-to-date for the client and the summarizing client, there will be an doubling of both\n * InactiveObject_Loaded and SweepReady_Loaded errors, as there will be one from the sending client and one from\n * the receiving summarizer client.\n *\n * Ideally, this initialization should only be done for summarizer client. However, we are currently rolling out\n * sweep in phases and we want to track when inactive and sweep ready objects are used in any client.\n */\n if (this.activeConnection() && this.shouldRunGC) {\n this.initializeGCStateFromBaseSnapshotP.catch((error) => {});\n }\n }\n\n /**\n * Runs garbage collection and updates the reference / used state of the nodes in the container.\n * @returns stats of the GC run or undefined if GC did not run.\n */\n public async collectGarbage(\n options: {\n /** Logger to use for logging GC events */\n logger?: ITelemetryLogger;\n /** True to run GC sweep phase after the mark phase */\n runSweep?: boolean;\n /** True to generate full GC data */\n fullGC?: boolean;\n },\n ): Promise<IGCStats | undefined> {\n const fullGC = options.fullGC ?? (this.gcOptions.runFullGC === true || this.summaryStateNeedsReset);\n const logger = options.logger\n ? ChildLogger.create(options.logger, undefined, { all: { completedGCRuns: () => this.completedRuns } })\n : this.mc.logger;\n\n /**\n * If there is no current reference timestamp, skip running GC. We need the current timestamp to track\n * how long objects have been unreferenced and if they should be deleted.\n *\n * Note that the only scenario where GC is called and there is no reference timestamp is when no ops have ever\n * been processed for this container and it is in read mode. In this scenario, there is no point in running GC\n * anyway because references in the container do not change without any ops, i.e., there is nothing to collect.\n */\n const currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs();\n if (currentReferenceTimestampMs === undefined) {\n // Log an event so we can evaluate how often we run into this scenario.\n logger.sendErrorEvent({\n eventName: \"CollectGarbageCalledWithoutTimestamp\",\n gcConfigs: JSON.stringify(this.configs),\n });\n return undefined;\n }\n\n return PerformanceEvent.timedExecAsync(logger, { eventName: \"GarbageCollection\" }, async (event) => {\n await this.runPreGCSteps();\n\n // Get the runtime's GC data and run GC on the reference graph in it.\n const gcData = await this.runtime.getGCData(fullGC);\n const gcResult = runGarbageCollection(gcData.gcNodes, [\"/\"]);\n\n const gcStats = await this.runPostGCSteps(gcData, gcResult, logger, currentReferenceTimestampMs);\n event.end({ ...gcStats, timestamp: currentReferenceTimestampMs });\n this.completedRuns++;\n return gcStats;\n }, { end: true, cancel: \"error\" });\n }\n\n private async runPreGCSteps() {\n // Ensure that state has been initialized from the base snapshot data.\n await this.initializeGCStateFromBaseSnapshotP;\n // Let the runtime update its pending state before GC runs.\n await this.runtime.updateStateBeforeGC();\n }\n\n private async runPostGCSteps(\n gcData: IGarbageCollectionData,\n gcResult: IGCResult,\n logger: ITelemetryLogger,\n currentReferenceTimestampMs: number,\n ): Promise<IGCStats> {\n // Generate statistics from the current run. This is done before updating the current state because it\n // generates some of its data based on previous state of the system.\n const gcStats = this.generateStats(gcResult);\n\n // Update the state since the last GC run. There can be nodes that were referenced between the last and\n // the current run. We need to identify than and update their unreferenced state if needed.\n this.updateStateSinceLastRun(gcData, logger);\n\n // Update the current state and update the runtime of all routes or ids that used as per the GC run.\n this.updateCurrentState(gcData, gcResult, currentReferenceTimestampMs);\n this.runtime.updateUsedRoutes(gcResult.referencedNodeIds);\n\n // Log events for objects that are ready to be deleted by sweep. When we have sweep enabled, we will\n // delete these objects here instead.\n this.logSweepEvents(logger, currentReferenceTimestampMs);\n\n // If we are running in GC test mode, delete objects for unused routes. This enables testing scenarios\n // involving access to deleted data.\n if (this.testMode) {\n this.runtime.updateUnusedRoutes(gcResult.deletedNodeIds);\n } else if (this.tombstoneMode) {\n // If we are running in GC tombstone mode, update tombstoned routes. This enables testing scenarios\n // involving access to \"deleted\" data without actually deleting the data from summaries.\n // Note: we will not tombstone in test mode.\n this.runtime.updateTombstonedRoutes(this.tombstones);\n }\n\n // Log pending unreferenced events such as a node being used after inactive. This is done after GC runs and\n // updates its state so that we don't send false positives based on intermediate state. For example, we may get\n // reference to an unreferenced node from another unreferenced node which means the node wasn't revived.\n await this.logUnreferencedEvents(logger);\n\n return gcStats;\n }\n\n /**\n * Summarizes the GC data and returns it as a summary tree.\n * We current write the entire GC state in a single blob. This can be modified later to write multiple\n * blobs. All the blob keys should start with `gcBlobPrefix`.\n */\n public summarize(\n fullTree: boolean,\n trackState: boolean,\n telemetryContext?: ITelemetryContext,\n ): ISummarizeResult | undefined {\n if (!this.shouldRunGC || this.gcDataFromLastRun === undefined) {\n return;\n }\n\n const gcState: IGarbageCollectionState = { gcNodes: {} };\n for (const [nodeId, outboundRoutes] of Object.entries(this.gcDataFromLastRun.gcNodes)) {\n gcState.gcNodes[nodeId] = {\n outboundRoutes,\n unreferencedTimestampMs: this.unreferencedNodesState.get(nodeId)?.unreferencedTimestampMs,\n };\n }\n\n const serializedGCState = JSON.stringify(generateSortedGCState(gcState));\n // Serialize and write deleted nodes, if any. This is done irrespective of whether sweep is enabled or not so\n // to identify deleted nodes' usage.\n const serializedDeletedNodes = this.deletedNodes.size > 0\n ? JSON.stringify(Array.from(this.deletedNodes).sort())\n : undefined;\n // If running in tombstone mode, serialize and write tombstones, if any.\n const serializedTombstones = this.tombstoneMode\n ? (this.tombstones.length > 0 ? JSON.stringify(this.tombstones.sort()) : undefined)\n : undefined;\n\n /**\n * Incremental summary of GC data - If none of GC state, deleted nodes or tombstones changed since last summary,\n * write summary handle instead of summary tree for GC.\n * Otherwise, write the GC summary tree. In the tree, for each of these that changed, write a summary blob and\n * for each of these that did not change, write a summary handle.\n */\n if (this.trackGCState) {\n this.pendingSummaryData = { serializedGCState, serializedTombstones, serializedDeletedNodes };\n if (trackState && !fullTree && this.latestSummaryData !== undefined) {\n // If nothing changed since last summary, send a summary handle for the entire GC data.\n if (this.latestSummaryData.serializedGCState === serializedGCState\n && this.latestSummaryData.serializedTombstones === serializedTombstones) {\n const stats = mergeStats();\n stats.handleNodeCount++;\n return {\n summary: {\n type: SummaryType.Handle,\n handle: `/${gcTreeKey}`,\n handleType: SummaryType.Tree,\n },\n stats,\n };\n }\n\n // If some state changed, build a GC summary tree.\n return this.buildGCSummaryTree(\n serializedGCState, serializedTombstones, serializedDeletedNodes, true /* trackState */);\n }\n }\n // If not tracking GC state, build a GC summary tree without any summary handles.\n return this.buildGCSummaryTree(\n serializedGCState, serializedTombstones, serializedDeletedNodes, false /* trackState */);\n }\n\n /**\n * Builds the GC summary tree which contains GC state, deleted nodes and tombstones.\n * If trackState is false, all of GC state, deleted nodes and tombstones are written as summary blobs.\n * If trackState is true, only states that changed are written. Rest are written as handles.\n * @param serializedGCState - The GC state serialized as string.\n * @param serializedTombstones - The tombstone state serialized as string.\n * @param serializedDeletedNodes - Deleted nodes serialized as string.\n * @param trackState - Whether we are tracking GC state across summaries.\n * @returns the GC summary tree.\n */\n private buildGCSummaryTree(\n serializedGCState: string,\n serializedTombstones: string | undefined,\n serializedDeletedNodes: string | undefined,\n trackState: boolean,\n ): ISummaryTreeWithStats {\n const gcStateBlobKey = `${gcBlobPrefix}_root`;\n const builder = new SummaryTreeBuilder();\n\n // If the GC state hasn't changed, write a summary handle, else write a summary blob for it.\n if (this.latestSummaryData?.serializedGCState === serializedGCState && trackState) {\n builder.addHandle(gcStateBlobKey, SummaryType.Blob, `/${gcTreeKey}/${gcStateBlobKey}`);\n } else {\n builder.addBlob(gcStateBlobKey, serializedGCState);\n }\n\n // If tombstones exist, write a summary handle if it hasn't changed. If it has changed, write a\n // summary blob.\n if (serializedTombstones !== undefined) {\n if (this.latestSummaryData?.serializedTombstones === serializedTombstones && trackState) {\n builder.addHandle(gcTombstoneBlobKey, SummaryType.Blob, `/${gcTreeKey}/${gcTombstoneBlobKey}`);\n } else {\n builder.addBlob(gcTombstoneBlobKey, serializedTombstones);\n }\n }\n\n // If there are no deleted nodes, return the summary tree.\n if (serializedDeletedNodes === undefined) {\n return builder.getSummaryTree();\n }\n\n // If the deleted nodes hasn't changed, write a summary handle, else write a summary blob for it.\n if (this.latestSummaryData?.serializedDeletedNodes === serializedDeletedNodes && trackState) {\n builder.addHandle(gcDeletedBlobKey, SummaryType.Blob, `/${gcTreeKey}/${gcDeletedBlobKey}`);\n } else {\n builder.addBlob(gcDeletedBlobKey, serializedDeletedNodes);\n }\n return builder.getSummaryTree();\n }\n\n public getMetadata(): IGCMetadata {\n return {\n /**\n * If GC is enabled, the GC data is written using the current GC version and that is the gcFeature that goes\n * into the metadata blob. If GC is disabled, the gcFeature is 0.\n */\n gcFeature: this.gcEnabled ? this.currentGCVersion : 0,\n sessionExpiryTimeoutMs: this.sessionExpiryTimeoutMs,\n sweepEnabled: this.sweepEnabled,\n sweepTimeoutMs: this.sweepTimeoutMs,\n };\n }\n\n /**\n * Returns a the GC details generated from the base summary. This is used to initialize the GC state of the nodes\n * in the container.\n */\n public async getBaseGCDetails(): Promise<IGarbageCollectionDetailsBase> {\n return this.baseGCDetailsP;\n }\n\n /**\n * Called to refresh the latest summary state. This happens when either a pending summary is acked or a snapshot\n * is downloaded and should be used to update the state.\n */\n public async refreshLatestSummary(\n result: RefreshSummaryResult,\n proposalHandle: string | undefined,\n summaryRefSeq: number,\n readAndParseBlob: ReadAndParseBlob,\n ): Promise<void> {\n // If the latest summary was updated and the summary was tracked, this client is the one that generated this\n // summary. So, update wasGCRunInLatestSummary.\n // Note that this has to be updated if GC did not run too. Otherwise, `gcStateNeedsReset` will always return\n // true in scenarios where GC is disabled but enabled in the snapshot we loaded from.\n if (result.latestSummaryUpdated && result.wasSummaryTracked) {\n this.wasGCRunInLatestSummary = this.shouldRunGC;\n }\n\n if (!result.latestSummaryUpdated || !this.shouldRunGC) {\n return;\n }\n\n // If the summary was tracked by this client, it was the one that generated the summary in the first place.\n // Update latest state from pending.\n if (result.wasSummaryTracked) {\n this.latestSummaryGCVersion = this.currentGCVersion;\n if (this.trackGCState) {\n this.latestSummaryData = this.pendingSummaryData;\n this.pendingSummaryData = undefined;\n }\n return;\n }\n\n // If the summary was not tracked by this client, the state should be updated from the downloaded snapshot.\n const snapshot = result.snapshot;\n const metadataBlobId = snapshot.blobs[metadataBlobName];\n if (metadataBlobId) {\n const metadata = await readAndParseBlob<IContainerRuntimeMetadata>(metadataBlobId);\n this.latestSummaryGCVersion = getGCVersion(metadata);\n }\n\n // The current reference timestamp should be available if we are refreshing state from a snapshot. There has\n // to be at least one op (summary op / ack, if nothing else) if a snapshot was taken.\n const currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs();\n if (currentReferenceTimestampMs === undefined) {\n throw DataProcessingError.create(\n \"No reference timestamp when updating GC state from snapshot\",\n \"refreshLatestSummary\",\n undefined,\n { proposalHandle, summaryRefSeq, details: JSON.stringify(this.configs) },\n );\n }\n const gcSnapshotTree = snapshot.trees[gcTreeKey];\n // If GC ran in the container that generated this snapshot, it will have a GC tree.\n this.wasGCRunInLatestSummary = gcSnapshotTree !== undefined;\n let latestGCData: IGarbageCollectionSnapshotData | undefined;\n if (gcSnapshotTree !== undefined) {\n latestGCData = await getGCDataFromSnapshot(\n gcSnapshotTree,\n readAndParseBlob,\n );\n }\n this.updateStateFromSnapshotData(latestGCData, currentReferenceTimestampMs);\n this.pendingSummaryData = undefined;\n }\n\n /**\n * Called when a node with the given id is updated. If the node is inactive, log an error.\n * @param nodePath - The id of the node that changed.\n * @param reason - Whether the node was loaded or changed.\n * @param timestampMs - The timestamp when the node changed.\n * @param packagePath - The package path of the node. This may not be available if the node hasn't been loaded yet.\n * @param requestHeaders - If the node was loaded via request path, the headers in the request.\n */\n public nodeUpdated(\n nodePath: string,\n reason: \"Loaded\" | \"Changed\",\n timestampMs?: number,\n packagePath?: readonly string[],\n requestHeaders?: IRequestHeader,\n ) {\n if (!this.shouldRunGC) {\n return;\n }\n\n const nodeStateTracker = this.unreferencedNodesState.get(nodePath);\n if (nodeStateTracker && nodeStateTracker.state !== UnreferencedState.Active) {\n this.inactiveNodeUsed(\n reason,\n nodePath,\n nodeStateTracker,\n undefined /* fromNodeId */,\n packagePath,\n timestampMs,\n requestHeaders,\n );\n }\n }\n\n /**\n * Called when an outbound reference is added to a node. This is used to identify all nodes that have been\n * referenced between summaries so that their unreferenced timestamp can be reset.\n *\n * @param fromNodePath - The node from which the reference is added.\n * @param toNodePath - The node to which the reference is added.\n */\n public addedOutboundReference(fromNodePath: string, toNodePath: string) {\n if (!this.shouldRunGC) {\n return;\n }\n\n const outboundRoutes = this.newReferencesSinceLastRun.get(fromNodePath) ?? [];\n outboundRoutes.push(toNodePath);\n this.newReferencesSinceLastRun.set(fromNodePath, outboundRoutes);\n\n const nodeStateTracker = this.unreferencedNodesState.get(toNodePath);\n if (nodeStateTracker && nodeStateTracker.state !== UnreferencedState.Active) {\n this.inactiveNodeUsed(\"Revived\", toNodePath, nodeStateTracker, fromNodePath);\n }\n\n if (this.tombstones.includes(toNodePath)) {\n const nodeType = this.runtime.getNodeType(toNodePath)\n\n let eventName = \"GC_Tombstone_SubDatastore_Revived\";\n if (nodeType === GCNodeType.DataStore) {\n eventName = \"GC_Tombstone_Datastore_Revived\";\n } else if (nodeType === GCNodeType.Blob) {\n eventName = \"GC_Tombstone_Blob_Revived\";\n }\n\n sendGCTombstoneEvent(\n this.mc,\n {\n eventName,\n category: \"generic\",\n isSummarizerClient: this.isSummarizerClient,\n url: trimLeadingSlashes(toNodePath),\n nodeType,\n },\n undefined /* packagePath */,\n );\n }\n }\n\n /**\n * Returns whether a node with the given path has been deleted or not. This can be used by the runtime to identify\n * cases where objects are used after they are deleted and throw / log errors accordingly.\n */\n public isNodeDeleted(nodePath: string): boolean {\n return this.deletedNodes.has(nodePath);\n }\n\n public dispose(): void {\n this.sessionExpiryTimer?.clear();\n this.sessionExpiryTimer = undefined;\n }\n\n /**\n * Updates the state of the system as per the current GC run. It does the following:\n * 1. Sets up the current GC state as per the gcData.\n * 2. Starts tracking for nodes that have become unreferenced in this run.\n * 3. Clears tracking for nodes that were unreferenced but became referenced in this run.\n * @param gcData - The data representing the reference graph on which GC is run.\n * @param gcResult - The result of the GC run on the gcData.\n * @param currentReferenceTimestampMs - The timestamp to be used for unreferenced nodes' timestamp.\n */\n private updateCurrentState(\n gcData: IGarbageCollectionData,\n gcResult: IGCResult,\n currentReferenceTimestampMs: number,\n ) {\n this.gcDataFromLastRun = cloneGCData(gcData);\n this.tombstones = [];\n this.newReferencesSinceLastRun.clear();\n\n // Iterate through the referenced nodes and stop tracking if they were unreferenced before.\n for (const nodeId of gcResult.referencedNodeIds) {\n const nodeStateTracker = this.unreferencedNodesState.get(nodeId);\n if (nodeStateTracker !== undefined) {\n // Stop tracking so as to clear out any running timers.\n nodeStateTracker.stopTracking();\n // Delete the node as we don't need to track it any more.\n this.unreferencedNodesState.delete(nodeId);\n }\n }\n\n /**\n * If a node became unreferenced in this run, start tracking it.\n * If a node was already unreferenced, update its tracking information. Since the current reference time is\n * from the ops seen, this will ensure that we keep updating the unreferenced state as time moves forward.\n */\n for (const nodeId of gcResult.deletedNodeIds) {\n const nodeStateTracker = this.unreferencedNodesState.get(nodeId);\n if (nodeStateTracker === undefined) {\n this.unreferencedNodesState.set(\n nodeId,\n new UnreferencedStateTracker(\n currentReferenceTimestampMs,\n this.inactiveTimeoutMs,\n currentReferenceTimestampMs,\n this.sweepTimeoutMs,\n ),\n );\n } else {\n nodeStateTracker.updateTracking(currentReferenceTimestampMs);\n if (this.tombstoneMode && nodeStateTracker.state === UnreferencedState.SweepReady) {\n const nodeType = this.runtime.getNodeType(nodeId);\n if (nodeType === GCNodeType.DataStore || nodeType === GCNodeType.Blob) {\n this.tombstones.push(nodeId);\n }\n }\n }\n }\n }\n\n /**\n * Since GC runs periodically, the GC data that is generated only tells us the state of the world at that point in\n * time. There can be nodes that were referenced in between two runs and their unreferenced state needs to be\n * updated. For example, in the following scenarios not updating the unreferenced timestamp can lead to deletion of\n * these objects while there can be in-memory referenced to it:\n * 1. A node transitions from `unreferenced -> referenced -> unreferenced` between two runs. When the reference is\n * added, the object may have been accessed and in-memory reference to it added.\n * 2. A reference is added from one unreferenced node to one or more unreferenced nodes. Even though the node[s] were\n * unreferenced, they could have been accessed and in-memory reference to them added.\n *\n * This function identifies nodes that were referenced since last run and removes their unreferenced state, if any.\n * If these nodes are currently unreferenced, they will be assigned new unreferenced state by the current run.\n */\n private updateStateSinceLastRun(currentGCData: IGarbageCollectionData, logger: ITelemetryLogger) {\n // If we haven't run GC before there is nothing to do.\n if (this.gcDataFromLastRun === undefined) {\n return;\n }\n\n // Find any references that haven't been identified correctly.\n const missingExplicitReferences = this.findMissingExplicitReferences(\n currentGCData,\n this.gcDataFromLastRun,\n this.newReferencesSinceLastRun,\n );\n\n if (missingExplicitReferences.length > 0) {\n missingExplicitReferences.forEach((missingExplicitReference) => {\n logger.sendErrorEvent({\n eventName: \"gcUnknownOutboundReferences\",\n gcNodeId: missingExplicitReference[0],\n gcRoutes: JSON.stringify(missingExplicitReference[1]),\n });\n });\n }\n\n // No references were added since the last run so we don't have to update reference states of any unreferenced\n // nodes\n if (this.newReferencesSinceLastRun.size === 0) {\n return;\n }\n\n /**\n * Generate a super set of the GC data that contains the nodes and edges from last run, plus any new node and\n * edges that have been added since then. To do this, combine the GC data from the last run and the current\n * run, and then add the references since last run.\n *\n * Note on why we need to combine the data from previous run, current run and all references in between -\n * 1. We need data from last run because some of its references may have been deleted since then. If those\n * references added new outbound references before they were deleted, we need to detect them.\n *\n * 2. We need new outbound references since last run because some of them may have been deleted later. If those\n * references added new outbound references before they were deleted, we need to detect them.\n *\n * 3. We need data from the current run because currently we may not detect when DDSes are referenced:\n * - We don't require DDSes handles to be stored in a referenced DDS.\n * - A new data store may have \"root\" DDSes already created and we don't detect them today.\n */\n const gcDataSuperSet = concatGarbageCollectionData(this.gcDataFromLastRun, currentGCData);\n const newOutboundRoutesSinceLastRun: string[] = [];\n this.newReferencesSinceLastRun.forEach((outboundRoutes: string[], sourceNodeId: string) => {\n if (gcDataSuperSet.gcNodes[sourceNodeId] === undefined) {\n gcDataSuperSet.gcNodes[sourceNodeId] = outboundRoutes;\n } else {\n gcDataSuperSet.gcNodes[sourceNodeId].push(...outboundRoutes);\n }\n newOutboundRoutesSinceLastRun.push(...outboundRoutes);\n });\n\n /**\n * Run GC on the above reference graph starting with root and all new outbound routes. This will generate a\n * list of all nodes that could have been referenced since the last run. If any of these nodes are unreferenced,\n * unreferenced, stop tracking them and remove from unreferenced list.\n * Note that some of these nodes may be unreferenced now and if so, the current run will mark them as\n * unreferenced and add unreferenced state.\n */\n const gcResult = runGarbageCollection(gcDataSuperSet.gcNodes, [\"/\", ...newOutboundRoutesSinceLastRun]);\n for (const nodeId of gcResult.referencedNodeIds) {\n const nodeStateTracker = this.unreferencedNodesState.get(nodeId);\n if (nodeStateTracker !== undefined) {\n // Stop tracking so as to clear out any running timers.\n nodeStateTracker.stopTracking();\n // Delete the unreferenced state as we don't need to track it any more.\n this.unreferencedNodesState.delete(nodeId);\n }\n }\n }\n\n /**\n * Finds all new references or outbound routes in the current graph that haven't been explicitly notified to GC.\n * The principle is that every new reference or outbound route must be notified to GC via the\n * addedOutboundReference method. It it hasn't, its a bug and we want to identify these scenarios.\n *\n * In more simple terms:\n * Missing Explicit References = Current References - Previous References - Explicitly Added References;\n *\n * @param currentGCData - The GC data (reference graph) from the current GC run.\n * @param previousGCData - The GC data (reference graph) from the previous GC run.\n * @param explicitReferences - New references added explicity between the previous and the current run.\n * @returns - a list of missing explicit references\n */\n private findMissingExplicitReferences(\n currentGCData: IGarbageCollectionData,\n previousGCData: IGarbageCollectionData,\n explicitReferences: Map<string, string[]>,\n ): [string, string[]][] {\n assert(\n previousGCData !== undefined,\n 0x2b7, /* \"Can't validate correctness without GC data from last run\" */\n );\n\n const currentGraph = Object.entries(currentGCData.gcNodes);\n const missingExplicitReferences: [string, string[]][] = [];\n currentGraph.forEach(([nodeId, currentOutboundRoutes]) => {\n const previousRoutes = previousGCData.gcNodes[nodeId] ?? [];\n const explicitRoutes = explicitReferences.get(nodeId) ?? [];\n const missingExplicitRoutes: string[] = [];\n\n /**\n * 1. For routes in the current GC data, routes that were not present in previous GC data and did not have\n * explicit references should be added to missing explicit routes list.\n * 2. Only include data store and blob routes since GC only works for these two.\n * Note: Due to a bug with de-duped blobs, only adding data store routes for now.\n * 3. Ignore DDS routes to their parent datastores since those were added implicitly. So, there won't be\n * explicit routes to them.\n */\n currentOutboundRoutes.forEach((route) => {\n const nodeType = this.runtime.getNodeType(route);\n if ((nodeType === GCNodeType.DataStore || nodeType === GCNodeType.Blob)\n && !nodeId.startsWith(route)\n && (!previousRoutes.includes(route) && !explicitRoutes.includes(route))) {\n missingExplicitRoutes.push(route);\n }\n });\n if (missingExplicitRoutes.length > 0) {\n missingExplicitReferences.push([nodeId, missingExplicitRoutes]);\n }\n });\n\n // Ideally missingExplicitReferences should always have a size 0\n return missingExplicitReferences;\n }\n\n /**\n * Generates the stats of a garbage collection run from the given results of the run.\n * @param gcResult - The result of a GC run.\n * @returns the GC stats of the GC run.\n */\n private generateStats(gcResult: IGCResult): IGCStats {\n const gcStats: IGCStats = {\n nodeCount: 0,\n dataStoreCount: 0,\n attachmentBlobCount: 0,\n unrefNodeCount: 0,\n unrefDataStoreCount: 0,\n unrefAttachmentBlobCount: 0,\n updatedNodeCount: 0,\n updatedDataStoreCount: 0,\n updatedAttachmentBlobCount: 0,\n };\n\n const updateNodeStats = (nodeId: string, referenced: boolean) => {\n gcStats.nodeCount++;\n // If there is no previous GC data, every node's state is generated and is considered as updated.\n // Otherwise, find out if any node went from referenced to unreferenced or vice-versa.\n const stateUpdated = this.gcDataFromLastRun === undefined ||\n this.unreferencedNodesState.has(nodeId) === referenced;\n if (stateUpdated) {\n gcStats.updatedNodeCount++;\n }\n if (!referenced) {\n gcStats.unrefNodeCount++;\n }\n\n if (this.runtime.getNodeType(nodeId) === GCNodeType.DataStore) {\n gcStats.dataStoreCount++;\n if (stateUpdated) {\n gcStats.updatedDataStoreCount++;\n }\n if (!referenced) {\n gcStats.unrefDataStoreCount++;\n }\n }\n if (this.runtime.getNodeType(nodeId) === GCNodeType.Blob) {\n gcStats.attachmentBlobCount++;\n if (stateUpdated) {\n gcStats.updatedAttachmentBlobCount++;\n }\n if (!referenced) {\n gcStats.unrefAttachmentBlobCount++;\n }\n }\n };\n\n for (const nodeId of gcResult.referencedNodeIds) {\n updateNodeStats(nodeId, true /* referenced */);\n }\n\n for (const nodeId of gcResult.deletedNodeIds) {\n updateNodeStats(nodeId, false /* referenced */);\n }\n\n return gcStats;\n }\n\n /**\n * For nodes that are ready to sweep, log an event for now. Until we start running sweep which deletes objects,\n * this will give us a view into how much deleted content a container has.\n */\n private logSweepEvents(logger: ITelemetryLogger, currentReferenceTimestampMs: number) {\n if (this.mc.config.getBoolean(disableSweepLogKey) === true || this.sweepTimeoutMs === undefined) {\n return;\n }\n\n this.unreferencedNodesState.forEach((nodeStateTracker, nodeId) => {\n if (nodeStateTracker.state !== UnreferencedState.SweepReady) {\n return;\n }\n\n const nodeType = this.runtime.getNodeType(nodeId);\n if (nodeType !== GCNodeType.DataStore && nodeType !== GCNodeType.Blob) {\n return;\n }\n\n // Log deleted event for each node only once to reduce noise in telemetry.\n const uniqueEventId = `Deleted-${nodeId}`;\n if (this.loggedUnreferencedEvents.has(uniqueEventId)) {\n return;\n }\n this.loggedUnreferencedEvents.add(uniqueEventId);\n logger.sendTelemetryEvent({\n eventName: \"GCObjectDeleted\",\n id: nodeId,\n type: nodeType,\n age: currentReferenceTimestampMs - nodeStateTracker.unreferencedTimestampMs,\n timeout: this.sweepTimeoutMs,\n completedGCRuns: this.completedRuns,\n lastSummaryTime: this.getLastSummaryTimestampMs(),\n });\n });\n }\n\n /**\n * Called when an inactive node is used after. Queue up an event that will be logged next time GC runs.\n */\n private inactiveNodeUsed(\n usageType: \"Changed\" | \"Loaded\" | \"Revived\",\n nodeId: string,\n nodeStateTracker: UnreferencedStateTracker,\n fromNodeId?: string,\n packagePath?: readonly string[],\n currentReferenceTimestampMs = this.runtime.getCurrentReferenceTimestampMs(),\n requestHeaders?: IRequestHeader,\n ) {\n // If there is no reference timestamp to work with, no ops have been processed after creation. If so, skip\n // logging as nothing interesting would have happened worth logging.\n // If the node is active, skip logging.\n if (currentReferenceTimestampMs === undefined || nodeStateTracker.state === UnreferencedState.Active) {\n return;\n }\n\n // We only care about data stores and attachment blobs for this telemetry since GC only marks these objects\n // as unreferenced. Also, if an inactive DDS is used, the corresponding data store store will also be used.\n const nodeType = this.runtime.getNodeType(nodeId);\n if (nodeType !== GCNodeType.DataStore && nodeType !== GCNodeType.Blob) {\n return;\n }\n\n const state = nodeStateTracker.state;\n const uniqueEventId = `${state}-${nodeId}-${usageType}`;\n if (this.loggedUnreferencedEvents.has(uniqueEventId)) {\n return;\n }\n this.loggedUnreferencedEvents.add(uniqueEventId);\n\n const propsToLog = {\n id: nodeId,\n type: nodeType,\n unrefTime: nodeStateTracker.unreferencedTimestampMs,\n age: currentReferenceTimestampMs - nodeStateTracker.unreferencedTimestampMs,\n timeout: nodeStateTracker.state === UnreferencedState.Inactive\n ? this.inactiveTimeoutMs\n : this.sweepTimeoutMs,\n completedGCRuns: this.completedRuns,\n lastSummaryTime: this.getLastSummaryTimestampMs(),\n ...this.createContainerMetadata,\n externalRequest: requestHeaders?.[RuntimeHeaders.externalRequest],\n viaHandle: requestHeaders?.[RuntimeHeaders.viaHandle],\n fromId: fromNodeId,\n };\n\n // For summarizer client, queue the event so it is logged the next time GC runs if the event is still valid.\n // For non-summarizer client, log the event now since GC won't run on it. This may result in false positives\n // but it's a good signal nonetheless and we can consume it with a grain of salt.\n // Inactive errors are usages of Objects that are unreferenced for at least a period of 7 days.\n // SweepReady errors are usages of Objects that will be deleted by GC Sweep!\n if (this.isSummarizerClient) {\n this.pendingEventsQueue.push({ ...propsToLog, usageType, state });\n } else {\n // For non-summarizer clients, only log \"Loaded\" type events since these objects may not be loaded in the\n // summarizer clients if they are based off of user actions (such as scrolling to content for these objects)\n // Events generated:\n // InactiveObject_Loaded, SweepReadyObject_Loaded\n if (usageType === \"Loaded\") {\n const event = {\n ...propsToLog,\n eventName: `${state}Object_${usageType}`,\n pkg: packagePathToTelemetryProperty(packagePath),\n stack: generateStack(),\n };\n\n // Do not log the inactive object x events as error events as they are not the best signal for\n // detecting something wrong with GC either from the partner or from the runtime itself.\n if (state === UnreferencedState.Inactive) {\n this.mc.logger.sendTelemetryEvent(event);\n } else {\n this.mc.logger.sendErrorEvent(event);\n }\n }\n\n // If SweepReady Usage Detection is enabled, the handler may close the interactive container.\n // Once Sweep is fully implemented, this will be removed since the objects will be gone\n // and errors will arise elsewhere in the runtime\n if (state === UnreferencedState.SweepReady) {\n this.sweepReadyUsageHandler.usageDetectedInInteractiveClient({ ...propsToLog, usageType });\n }\n }\n }\n\n private async logUnreferencedEvents(logger: ITelemetryLogger) {\n // Events sent come only from the summarizer client. In between summaries, events are pushed to a queue and at\n // summary time they are then logged.\n // Events generated:\n // InactiveObject_Loaded, InactiveObject_Changed, InactiveObject_Revived\n // SweepReadyObject_Loaded, SweepReadyObject_Changed, SweepReadyObject_Revived\n for (const eventProps of this.pendingEventsQueue) {\n const { usageType, state, ...propsToLog } = eventProps;\n /**\n * Revived event is logged only if the node is active. If the node is not active, the reference to it was\n * from another unreferenced node and this scenario is not interesting to log.\n * Loaded and Changed events are logged only if the node is not active. If the node is active, it was\n * revived and a Revived event will be logged for it.\n */\n const nodeStateTracker = this.unreferencedNodesState.get(eventProps.id);\n const active = nodeStateTracker === undefined || nodeStateTracker.state === UnreferencedState.Active;\n if ((usageType === \"Revived\") === active) {\n const pkg = await this.getNodePackagePath(eventProps.id);\n const fromPkg = eventProps.fromId ? await this.getNodePackagePath(eventProps.fromId) : undefined;\n const event = {\n ...propsToLog,\n eventName: `${state}Object_${usageType}`,\n pkg: pkg ? { value: pkg.join(\"/\"), tag: TelemetryDataTag.CodeArtifact } : undefined,\n fromPkg: fromPkg ? { value: fromPkg.join(\"/\"), tag: TelemetryDataTag.CodeArtifact } : undefined,\n }\n\n if (state === UnreferencedState.Inactive) {\n logger.sendTelemetryEvent(event);\n } else {\n logger.sendErrorEvent(event);\n }\n }\n }\n this.pendingEventsQueue = [];\n }\n}\n\nfunction generateSortedGCState(gcState: IGarbageCollectionState): IGarbageCollectionState {\n const sortableArray: [string, IGarbageCollectionNodeData][] = Object.entries(gcState.gcNodes);\n sortableArray.sort(([a], [b]) => a.localeCompare(b));\n const sortedGCState: IGarbageCollectionState = { gcNodes: {} };\n for (const [nodeId, nodeData] of sortableArray) {\n nodeData.outboundRoutes.sort();\n sortedGCState.gcNodes[nodeId] = nodeData;\n }\n return sortedGCState;\n}\n\n/** A wrapper around common-utils Timer that requires the timeout when calling start/restart */\nclass TimerWithNoDefaultTimeout extends Timer {\n constructor(\n private readonly callback: () => void,\n ) {\n // The default timeout/handlers will never be used since start/restart pass overrides below\n super(0, () => { throw new Error(\"DefaultHandler should not be used\"); });\n }\n\n start(timeoutMs: number) {\n super.start(timeoutMs, this.callback);\n }\n\n restart(timeoutMs: number): void {\n super.restart(timeoutMs, this.callback);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../src/opLifecycle/outbox.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAEtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAG1E,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE7D,OAAO,EAAE,YAAY,EAAU,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,WAAW,aAAa;IAC1B,QAAQ,CAAC,kBAAkB,EAAE,0BAA0B,CAAC;IAExD,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAC3C;AAED,MAAM,WAAW,iBAAiB;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,OAAO,CAAC;IACnC,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;IAClD,QAAQ,CAAC,gBAAgB,EAAE,iBAAiB,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,UAAU,EAAE,YAAY,CAAC;IAClC,QAA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,iBAAiB;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,OAAO,CAAC;IACnC,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;IAClD,QAAQ,CAAC,gBAAgB,EAAE,iBAAiB,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,UAAU,EAAE,YAAY,CAAC;IAClC,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC;CACrC;AAED,qBAAa,MAAM;IAKH,OAAO,CAAC,QAAQ,CAAC,MAAM;IAJnC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAe;IAC/C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAe;IACzC,OAAO,CAAC,QAAQ,CAAC,iCAAiC,CAAa;gBAElC,MAAM,EAAE,iBAAiB;IAiBtD,IAAW,OAAO,IAAI,OAAO,CAE5B;IAEM,MAAM,CAAC,OAAO,EAAE,YAAY;IAa5B,YAAY,CAAC,OAAO,EAAE,YAAY;IA4BlC,KAAK;IAKZ,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,aAAa;IA8BrB;;;;;;OAMG;IACH,OAAO,CAAC,SAAS;IA2CjB,OAAO,CAAC,YAAY;IAkBb,UAAU;;;;CAMpB"}
@@ -147,7 +147,6 @@ export class Outbox {
147
147
  this.params.pendingStateManager.onSubmitMessage(message.deserializedContent.type, clientSequenceNumber, message.referenceSequenceNumber, message.deserializedContent.contents, message.localOpMetadata, message.metadata);
148
148
  clientSequenceNumber++;
149
149
  }
150
- this.params.pendingStateManager.onFlush();
151
150
  }
152
151
  checkpoint() {
153
152
  return {