Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ElementR | backup: call expensive roomKeyCounts less often #4015

Merged
merged 16 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions spec/unit/rust-crypto/BackupKeyLoop.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { Mocked } from "jest-mock";
import fetchMock from "fetch-mock-jest";
import * as RustSdkCryptoJs from "@matrix-org/matrix-sdk-crypto-wasm";

import { CryptoEvent, HttpApiEvent, HttpApiEventHandlerMap, MatrixHttpApi, TypedEventEmitter } from "../../../src";
import { OutgoingRequestProcessor } from "../../../src/rust-crypto/OutgoingRequestProcessor";
import * as testData from "../../test-utils/test-data";
import * as TestData from "../../test-utils/test-data";
import { IKeyBackup } from "../../../src/crypto/backup";
import { IKeyBackupSession } from "../../../src/crypto/keybackup";
import { defer } from "../../../src/utils";
import { RustBackupManager } from "../../../src/rust-crypto/backup";

describe("PerSessionKeyBackupDownloader", () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this... doesn't seem to be testing PerSessionKeyBackupDownloader ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I'd suggest renaming this file to backup.spec.ts. It's a good idea to have the test files match the files that they are testing, otherwise we end up with tests split between two files, which is very confusing.

/** The backup manager under test */
let rustBackupManager: RustBackupManager;

let mockOlmMachine: Mocked<RustSdkCryptoJs.OlmMachine>;

let outgoingRequestProcessor: Mocked<OutgoingRequestProcessor>;

const httpAPi = new MatrixHttpApi(new TypedEventEmitter<HttpApiEvent, HttpApiEventHandlerMap>(), {
baseUrl: "http://server/",
prefix: "",
onlyData: true,
});

let idGenerator = 0;
function mockBackupRequest(keyCount: number): RustSdkCryptoJs.KeysBackupRequest {
const requestBody: IKeyBackup = {
rooms: {
"!room1:server": {
sessions: {},
},
},
};
for (let i = 0; i < keyCount; i++) {
requestBody.rooms["!room1:server"].sessions["session" + i] = {} as IKeyBackupSession;
}
return {
id: "id" + idGenerator++,
body: JSON.stringify(requestBody),
} as unknown as Mocked<RustSdkCryptoJs.KeysBackupRequest>;
}

beforeEach(async () => {
jest.useFakeTimers();
idGenerator = 0;

mockOlmMachine = {
getBackupKeys: jest.fn().mockResolvedValue({
backupVersion: TestData.SIGNED_BACKUP_DATA.version!,
decryptionKey: RustSdkCryptoJs.BackupDecryptionKey.fromBase64(TestData.BACKUP_DECRYPTION_KEY_BASE64),
} as unknown as RustSdkCryptoJs.BackupKeys),
backupRoomKeys: jest.fn(),
isBackupEnabled: jest.fn().mockResolvedValue(true),
enableBackupV1: jest.fn(),
verifyBackup: jest.fn().mockResolvedValue({
trusted: jest.fn().mockResolvedValue(true),
} as unknown as RustSdkCryptoJs.SignatureVerification),
roomKeyCounts: jest.fn(),
} as unknown as Mocked<RustSdkCryptoJs.OlmMachine>;

outgoingRequestProcessor = {
makeOutgoingRequest: jest.fn(),
} as unknown as Mocked<OutgoingRequestProcessor>;

rustBackupManager = new RustBackupManager(mockOlmMachine, httpAPi, outgoingRequestProcessor);

fetchMock.get("path:/_matrix/client/v3/room_keys/version", testData.SIGNED_BACKUP_DATA);
});

afterEach(() => {
fetchMock.reset();
jest.useRealTimers();
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recommend a call to jest.restoreAllMocks here, to make sure that tests don't depend on mocks set up in other tests.


it("Should call expensive roomKeyCounts only once per loop", async () => {
const lastKeysCalled = defer();
const remainingEmitted: number[] = [];

const zeroRemainingWasEmitted = new Promise<void>((resolve) => {
rustBackupManager.on(CryptoEvent.KeyBackupSessionsRemaining, (count) => {
remainingEmitted.push(count);
if (count == 0) {
resolve();
}
});
});

// We want several batch of keys to check that we don't call expensive room key count several times
mockOlmMachine.backupRoomKeys
.mockResolvedValueOnce(mockBackupRequest(100))
.mockResolvedValueOnce(mockBackupRequest(100))
.mockResolvedValueOnce(mockBackupRequest(100))
.mockResolvedValueOnce(mockBackupRequest(100))
.mockResolvedValueOnce(mockBackupRequest(100))
.mockResolvedValueOnce(mockBackupRequest(100))
.mockResolvedValueOnce(mockBackupRequest(2))
.mockImplementation(async () => {
lastKeysCalled.resolve();
return null;
});

mockOlmMachine.roomKeyCounts.mockResolvedValue({
total: 602,
// first iteration don't call count, it will in second after 200 keys have been saved
BillCarsonFr marked this conversation as resolved.
Show resolved Hide resolved
backedUp: 200,
});

await rustBackupManager.checkKeyBackupAndEnable(false);
await jest.runAllTimersAsync();

await lastKeysCalled.promise;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure we need this await? Don't think it adds anything except complexity.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, was usefull before I started to use Faketimers, removed

await zeroRemainingWasEmitted;

expect(outgoingRequestProcessor.makeOutgoingRequest).toHaveBeenCalledTimes(7);
expect(mockOlmMachine.roomKeyCounts).toHaveBeenCalledTimes(1);

// check event emission
expect(remainingEmitted[0]).toEqual(402);
expect(remainingEmitted[1]).toEqual(302);
expect(remainingEmitted[2]).toEqual(202);
expect(remainingEmitted[3]).toEqual(102);
expect(remainingEmitted[4]).toEqual(2);
expect(remainingEmitted[5]).toEqual(0);
});

it("Should not call expensive roomKeyCounts for small chunks", async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not the size of the chunk, but the fact there is only one chunk, right?

const lastKeysCalled = defer();

const zeroRemainingWasEmitted = new Promise<void>((resolve) => {
rustBackupManager.on(CryptoEvent.KeyBackupSessionsRemaining, (count) => {
if (count == 0) {
resolve();
}
});
});

// We want several batch of keys to check that we don't call expensive room key count several times
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... but there's only one batch here?

mockOlmMachine.backupRoomKeys.mockResolvedValueOnce(mockBackupRequest(2)).mockImplementation(async () => {
lastKeysCalled.resolve();
return null;
});

mockOlmMachine.roomKeyCounts.mockResolvedValue({
total: 2,
backedUp: 0,
});

await rustBackupManager.checkKeyBackupAndEnable(false);
await jest.runAllTimersAsync();

await lastKeysCalled.promise;
await zeroRemainingWasEmitted;

expect(outgoingRequestProcessor.makeOutgoingRequest).toHaveBeenCalledTimes(1);
expect(mockOlmMachine.roomKeyCounts).toHaveBeenCalledTimes(0);
});
});
50 changes: 29 additions & 21 deletions src/rust-crypto/backup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,8 +330,7 @@ export class RustBackupManager extends TypedEventEmitter<RustBackupCryptoEvents,
try {
// number of consecutive network failures for exponential backoff
let numFailures = 0;
// `olmMachine.roomKeyCounts()` is very slow on some configurations (see more comments below),
// we compute it only once per `backupKeysLoop` if necessary.
// The number of keys left to back up. (Populated lazily: see more comments below.)
let remainingToUploadCount: number | null = null;
// To avoid computing the key when only a few keys were added (after a sync for example),
// we compute the count only when at least two iterations are needed.
Expand Down Expand Up @@ -361,29 +360,38 @@ export class RustBackupManager extends TypedEventEmitter<RustBackupCryptoEvents,
return;
}

// Keys count performance (`olmMachine.roomKeyCounts()`) can be pretty bad on some configurations (big database in FF).
// We detected on some M1 mac that when the object store reach a threshold, the count performances stops growing in O(n) and
// suddenly become very slow (40s, 60s or more). Even on other configurations, the count can take several seconds.
// This will block other operations on the database, like sending messages
// This is a workaround to avoid calling `olmMachine.roomKeyCounts()` too often, and only when necessary.
// We don't call it on the first loop because there could be only a few keys to upload, and we don't want to wait for the count.
if (!isFirstIteration && remainingToUploadCount === null) {
try {
const keyCount = await this.olmMachine.roomKeyCounts();
remainingToUploadCount = keyCount.total - keyCount.backedUp;
} catch (err) {
logger.error("Backup: Failed to get key counts from rust crypto-sdk", err);
}
}

try {
await this.outgoingRequestProcessor.makeOutgoingRequest(request);
numFailures = 0;
if (this.stopped) break;

// Key count performance (`olmMachine.roomKeyCounts()`) can be pretty bad on some configurations.
// In particular, we detected on some M1 macs that when the object store reaches a threshold, the count
// performance stops growing in O(n) and suddenly becomes very slow (40s, 60s or more).
// For reference, the performance drop occurs around 300-400k keys on the platforms where this issue is observed.
// Even on other configurations, the count can take several seconds.
// This will block other operations on the database, like sending messages.
//
// This is a workaround to avoid calling `olmMachine.roomKeyCounts()` too often, and only when necessary.
// We don't call it on the first loop because there could be only a few keys to upload, and we don't want to wait for the count.
if (!isFirstIteration && remainingToUploadCount === null) {
try {
const keyCount = await this.olmMachine.roomKeyCounts();
remainingToUploadCount = keyCount.total - keyCount.backedUp;
} catch (err) {
logger.error("Backup: Failed to get key counts from rust crypto-sdk", err);
}
}

if (remainingToUploadCount !== null) {
this.emit(CryptoEvent.KeyBackupSessionsRemaining, remainingToUploadCount);
const keysCountInBatch = this.keysCountInBatch(request);
// The `remainingToUploadCount` is computed only once for the current backupKeysLoop. But new
BillCarsonFr marked this conversation as resolved.
Show resolved Hide resolved
// keys could be added during the current loop (after a sync for example).
// So the count can get out of sync with the real number of remaining keys to upload.
// Depending on the number of new keys imported and the time to complete the loop,
// this could result in multiple events being emitted with a remaining key count of 0.
remainingToUploadCount = Math.max(remainingToUploadCount - keysCountInBatch, 0);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while the backup loop runs, new megolm sessions could arrive (especially if you're backing up 400K sessions or so), so presumably memoizing the count like this could mean remainingToUploadCount gets stuck at 0 for quite a while at the end (while it backs up the additional keys that arrived). Worst case, the user might think that the progress has got stuck at zero and cancel it somehow. I wonder if it's worth spelling this edge case out at least as a comment, that the KeyBackupSessionsRemaining event may now lie and keep emitting 0 for a bit at the end of the backup loop?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, worth explaining. Added comment here 8dc1ff7

this.emit(CryptoEvent.KeyBackupSessionsRemaining, remainingToUploadCount);
}
} catch (err) {
numFailures++;
Expand All @@ -407,7 +415,7 @@ export class RustBackupManager extends TypedEventEmitter<RustBackupCryptoEvents,
// wait for that and then continue?
const waitTime = err.data.retry_after_ms;
if (waitTime > 0) {
sleep(waitTime);
await sleep(waitTime);
continue;
} // else go to the normal backoff
}
Expand Down Expand Up @@ -435,8 +443,8 @@ export class RustBackupManager extends TypedEventEmitter<RustBackupCryptoEvents,
private keysCountInBatch(batch: RustSdkCryptoJs.KeysBackupRequest): number {
const parsedBody: IKeyBackup = JSON.parse(batch.body);
let count = 0;
for (const entry of Object.entries(parsedBody.rooms)) {
count += Object.keys(entry[1].sessions).length;
for (const { sessions } of Object.values(parsedBody.rooms)) {
count += Object.keys(sessions).length;
}
return count;
}
Expand Down
Loading