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

perf(postgres): Add indexer on blocks."time" and optimize roundtable query #2742

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions indexer/packages/postgres/__tests__/helpers/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,11 +459,11 @@ export const defaultConditionalOrderId: string = OrderTable.uuid(

export const defaultBlock: BlockCreateObject = {
blockHeight: '1',
time: DateTime.utc(2022, 6, 1).toISO(),
time: DateTime.utc(2025, 3, 5).toISO(),
};
export const defaultBlock2: BlockCreateObject = {
blockHeight: '2',
time: DateTime.utc(2022, 6, 2).toISO(),
time: DateTime.utc(2025, 3, 6).toISO(),
};

// ============== TendermintEvents ==============
Expand Down
42 changes: 42 additions & 0 deletions indexer/packages/postgres/__tests__/stores/block-table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
teardown,
} from '../../src/helpers/db-helpers';
import { defaultBlock, defaultBlock2 } from '../helpers/constants';
import { DateTime } from 'luxon';

describe('Block store', () => {
beforeAll(async () => {
Expand Down Expand Up @@ -91,4 +92,45 @@ describe('Block store', () => {
it('Unable to find latest Block', async () => {
await expect(BlockTable.getLatest()).rejects.toEqual(new Error('Unable to find latest block'));
});

it('Successfully finds first block created on or after timestamp', async () => {
await Promise.all([
BlockTable.create(defaultBlock),
BlockTable.create(defaultBlock2),
]);

const block: BlockFromDatabase | undefined = await BlockTable.findBlockByCreatedOnOrAfter(
DateTime.utc(2025, 3, 5).toISO(),
);

expect(block).toBeDefined();
expect(block).toEqual(expect.objectContaining(defaultBlock));
});

it('Successfully finds first block when querying with later timestamp', async () => {
await Promise.all([
BlockTable.create(defaultBlock),
BlockTable.create(defaultBlock2),
]);

const block: BlockFromDatabase | undefined = await BlockTable.findBlockByCreatedOnOrAfter(
DateTime.utc(2025, 3, 6).toISO(),
);

expect(block).toBeDefined();
expect(block).toEqual(expect.objectContaining(defaultBlock2));
});

it('Returns undefined when no blocks found after timestamp', async () => {
await Promise.all([
BlockTable.create(defaultBlock),
BlockTable.create(defaultBlock2),
]);

const block: BlockFromDatabase | undefined = await BlockTable.findBlockByCreatedOnOrAfter(
DateTime.utc(2025, 3, 7).toISO(),
);

expect(block).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as Knex from 'knex';

export async function up(knex: Knex): Promise<void> {
await knex.raw(`
CREATE INDEX CONCURRENTLY IF NOT EXISTS "blocks_time_since_march2025_idx"
ON "blocks" ("time")
WHERE "time" >= '2025-03-01 00:00:00+00';
`);
}

export async function down(knex: Knex): Promise<void> {
await knex.raw(`
DROP INDEX CONCURRENTLY IF EXISTS
"blocks_time_since_march2025_idx";
`);
}

export const config = {
transaction: false,
};
49 changes: 43 additions & 6 deletions indexer/packages/postgres/src/stores/block-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,52 @@ import {
QueryConfig,
} from '../types';

/**
* Find blocks by their block heights.
*/
export async function findByBlockHeights(
blockHeights: string[],
options: Options = DEFAULT_POSTGRES_OPTIONS,
): Promise<BlockFromDatabase[]> {
const baseQuery: QueryBuilder<BlockModel> = setupBaseQuery<BlockModel>(
BlockModel,
options,
);

return baseQuery
.whereIn(BlockColumns.blockHeight, blockHeights)
.orderBy(BlockColumns.blockHeight, Ordering.ASC)
.returning('*');
}

/**
* Find the first block created on or after the given timestamp.
* Uses the blocks_time_since_march2025_idx index for efficient querying.
*/
export async function findBlockByCreatedOnOrAfter(
createdOnOrAfter: string,
options: Options = DEFAULT_POSTGRES_OPTIONS,
): Promise<BlockFromDatabase | undefined> {
const baseQuery: QueryBuilder<BlockModel> = setupBaseQuery<BlockModel>(
BlockModel,
options,
);

const blocks = await baseQuery
.where(BlockColumns.time, '>=', createdOnOrAfter)
.orderBy(BlockColumns.time, Ordering.ASC)
.limit(1)
.returning('*');
return blocks.length > 0 ? blocks[0] : undefined;
}

// Mark as deprecated to encourage migration to more specific methods
/**
* @deprecated Use findByBlockHeights or findByCreatedOnOrAfter instead
*/
export async function findAll(
{
blockHeight,
createdOnOrAfter,
limit,
}: BlockQueryConfig,
requiredFields: QueryableField[],
Expand All @@ -28,7 +70,6 @@ export async function findAll(
verifyAllRequiredFields(
{
blockHeight,
createdOnOrAfter,
limit,
} as QueryConfig,
requiredFields,
Expand All @@ -43,10 +84,6 @@ export async function findAll(
baseQuery = baseQuery.whereIn(BlockColumns.blockHeight, blockHeight);
}

if (createdOnOrAfter !== undefined) {
baseQuery = baseQuery.where(BlockColumns.time, '>=', createdOnOrAfter);
}

if (options.orderBy !== undefined) {
for (const [column, order] of options.orderBy) {
baseQuery = baseQuery.orderBy(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,12 +381,12 @@ export class AggregateTradingReward {
}

private async getNextBlock(time: IsoString): Promise<string> {
const blocks: BlockFromDatabase[] = await BlockTable.findAll({
createdOnOrAfter: time,
limit: 1,
}, [], { readReplica: true });
const block: BlockFromDatabase | undefined = await BlockTable.findBlockByCreatedOnOrAfter(
time,
{ readReplica: true },
);

if (blocks.length === 0) {
if (block === undefined) {
logger.error({
at: 'aggregate-trading-rewards#getStartedAtHeight',
message: 'No blocks found after time, this should never happen',
Expand All @@ -395,7 +395,7 @@ export class AggregateTradingReward {
});
throw new Error(`No blocks found after ${time}`);
}
return blocks[0].blockHeight;
return block.blockHeight;
}

private isEndofPeriod(endTime: DateTime): boolean {
Expand Down
Loading