Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

fix(core): keep descending memory dataset pages from repeating newer items (#4301)

Raphael Fakhri912e7e3c317c
diff --git a/packages/core/src/memory-storage/resource-clients/dataset.ts b/packages/core/src/memory-storage/resource-clients/dataset.ts
index 71fa9452c..992de92c7 100644
--- a/packages/core/src/memory-storage/resource-clients/dataset.ts
+++ b/packages/core/src/memory-storage/resource-clients/dataset.ts
@@ -88,10 +88,11 @@ export class DatasetBackend<Data extends Dictionary = Dictionary>
async #getDataPage(options: storage.DatasetBackendListOptions = {}): Promise<storage.PaginatedList<Data>> {
const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
- const [start, end] = this.#getStartAndEndIndexes(
- desc ? Math.max(this.itemCount - offset - limit, 0) : offset,
- limit,
- );
+ // In descending order, the window ends `offset` items before the newest one, so it can be shorter than `limit`.
+ const windowStart = desc ? Math.max(this.itemCount - offset - limit, 0) : offset;
+ const windowEnd = desc ? Math.max(this.itemCount - offset, 0) : offset + limit;
+
+ const [start, end] = this.#getStartAndEndIndexes(windowStart, windowEnd - windowStart);
const items: Data[] = [];
diff --git a/test/core/memory-storage/reverse-datataset-list.test.ts b/test/core/memory-storage/reverse-datataset-list.test.ts
index 2ea7006fa..08531219d 100644
--- a/test/core/memory-storage/reverse-datataset-list.test.ts
+++ b/test/core/memory-storage/reverse-datataset-list.test.ts
@@ -41,4 +41,17 @@ describe('Dataset#getData respects the desc option', () => {
expect(result.items).toHaveLength(5);
expect(result.items).toStrictEqual(elements.slice().reverse().slice(2, 7));
});
+
+ test('with desc: true and a window past the oldest item', async () => {
+ const result = await dataset.getData({ desc: true, limit: 5, offset: 8 });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items).toStrictEqual(elements.slice().reverse().slice(8, 13));
+ });
+
+ test('with desc: true and an offset past the end', async () => {
+ const result = await dataset.getData({ desc: true, limit: 5, offset: 10 });
+
+ expect(result.items).toHaveLength(0);
+ });
});