Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/calm-benchmarks-order.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"sideshow": patch
---

Make recent-post ordering deterministic when multiple writes share the same millisecond timestamp, preventing different SQLite versions from selecting different posts at the result limit.
5 changes: 4 additions & 1 deletion server/sqlStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,11 @@ export class SqlStore implements Store {
}

async listRecentPosts(limit: number) {
// ISO timestamps only have millisecond precision, so bulk writes frequently
// tie. Make LIMIT membership deterministic across SQLite versions and match
// JsonFileStore: among equal timestamps, the later insertion wins.
const rows = this.sql
.exec("SELECT * FROM posts ORDER BY updatedAt DESC LIMIT ?", limit)
.exec("SELECT * FROM posts ORDER BY updatedAt DESC, rowid DESC LIMIT ?", limit)
.toArray();
return rows.map((r) => this.rowToPost(r));
}
Expand Down
7 changes: 5 additions & 2 deletions server/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,10 +363,13 @@ export class JsonFileStore implements Store {

async listRecentPosts(limit: number) {
await this.load();
// Decorate with Map insertion order so millisecond timestamp ties have the
// same explicit newest-insertion-first order as SqlStore's rowid fallback.
return [...this.surfaces.values()]
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
.map((post, insertion) => ({ post, insertion }))
.sort((a, b) => b.post.updatedAt.localeCompare(a.post.updatedAt) || b.insertion - a.insertion)
.slice(0, limit)
.map(clone);
.map(({ post }) => clone(post));
}

async getPost(id: string) {
Expand Down
5 changes: 4 additions & 1 deletion server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,10 @@ export interface Store {
* omit it; the app falls back to listPosts() for source compatibility.
*/
countPostsBySession?(): Promise<Map<string, number>>;
/** The N most-recently-updated posts across all sessions (newest first). */
/**
* The N most-recently-updated posts across all sessions (newest first).
* Equal millisecond timestamps are ordered by newest insertion first.
*/
listRecentPosts(limit: number): Promise<Post[]>;
getPost(id: string): Promise<Post | null>;
createPost(input: CreatePostInput): Promise<Post | null>;
Expand Down
2 changes: 1 addition & 1 deletion test/sqlStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ test("SqlStore hot queries use their covering or ordering indexes", () => {
"sideshow_posts_session_created_at_idx",
);
assertUsesIndex(
"SELECT * FROM posts ORDER BY updatedAt DESC LIMIT ?",
"SELECT * FROM posts ORDER BY updatedAt DESC, rowid DESC LIMIT ?",
"sideshow_posts_updated_at_idx",
20,
);
Expand Down
51 changes: 50 additions & 1 deletion test/storeContract.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { HISTORY_LIMIT, htmlSurface, type Store, type Surface } from "../server/types.ts";
import {
HISTORY_LIMIT,
htmlSurface,
type Post,
type Store,
type Surface,
} from "../server/types.ts";

const bytes = (...values: number[]) => new Uint8Array(values);
const NUL = String.fromCharCode(0);
Expand Down Expand Up @@ -376,6 +382,49 @@ export function runStoreContract(name: string, makeStore: () => Store | Promise<
},
);

contract(
"listRecentPosts deterministically limits posts with tied millisecond timestamps",
async (store) => {
const session = await store.createSession({ agent: "pi" });
const OriginalDate = globalThis.Date;
const fixedMillis = OriginalDate.parse("2026-01-01T00:00:00.000Z");
const FixedDate = class extends OriginalDate {
constructor() {
super(fixedMillis);
}

static override now() {
return fixedMillis;
}
};
const posts: Post[] = [];

try {
globalThis.Date = FixedDate as DateConstructor;
for (let i = 0; i < 25; i++) {
const post = await store.createPost({
sessionId: session.id,
title: `tied ${i}`,
surfaces: [htmlSurface(`<p>${"x".repeat(i)}</p>`)],
});
assert.ok(post);
posts.push(post);
}
} finally {
globalThis.Date = OriginalDate;
}

assert.equal(new Set(posts.map((post) => post.updatedAt)).size, 1);
assert.deepEqual(
(await store.listRecentPosts(20)).map((post) => post.id),
posts
.slice(-20)
.reverse()
.map((post) => post.id),
);
},
);

contract("updates bump the version and archive the previous one", async (store) => {
const session = await store.createSession({ agent: "pi" });
const surface = await store.createPost({
Expand Down
Loading