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
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,20 @@ handling, no CSRF defense. Your host owns its login flow and its HTTP
surface; this store remembers the result.

> [!IMPORTANT]
> `@pegma/sessions` is published as `0.1.0`. It remains early `0.x`: the
> public API is not stable, and it is not ready for production use.
> `@pegma/sessions` remains early `0.x`: the public API is not stable, and
> it is not ready for production use. Published versions are listed on
> [npm](https://www.npmjs.com/package/@pegma/sessions).

The `0.2.1` change observes the default clock after awaited reads and sweeps.
With a consistent advancing clock, a concurrent touch observed in that snapshot
is no longer mistaken for a future timestamp merely because the operation
started earlier. Explicit caller-supplied timestamps keep their semantics.

Clock rollback and skew between hosts remain fail-closed: an idle anchor ahead
of the observing clock is dead under the single liveness predicate and may be
conditionally deleted. This change adds no clock-skew tolerance or coordination.
Source versions describe behavior; publication is recorded in
[GitHub releases](https://github.com/pegma-dev/sessions/releases).

Current status: the record-store package is published on npm, the first
consumer migration is merged in
Expand Down
19 changes: 19 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
# @pegma/sessions v0.2.1

Fix default clock observation around awaited session reads and expiry sweeps.
Default read time is observed after hashing and the initial storage read;
default sweep time is observed after the versioned list snapshot. With a
consistent advancing clock, a concurrent touch in that snapshot is no longer
misclassified as a future idle anchor merely because the operation began
before the touch. Sessions that expire during these awaits are rejected or
purged using the later observation.

Explicit caller-supplied instants retain their existing semantics. Clock
rollback or skew between hosts can still produce a future idle anchor, which
fails closed and may be conditionally deleted. There is no skew tolerance or
clock-coordination API. The single liveness predicate, malformed timestamp
refusal, conditional hygiene deletion, unconditional revocation and best-effort
non-resurrecting touch remain in place. No storage call, schema, runtime
dependency or public method is added. Memory and Azurite regressions cover the
concurrent touches, awaited expiry, clock observation and explicit-time behavior.

# @pegma/sessions v0.2.0

A dependency-alignment release: `@pegma/storage-core` advances from `0.3.0` to
Expand Down
11 changes: 7 additions & 4 deletions docs/PROJECT_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

## Status

**Stage:** Phases 1–4 are complete. `@pegma/sessions@0.1.1` is published;
RetireGolden is the first integrated consumer and pegma.dev is the second,
live consumer. `0.2.0` is prepared, aligning `@pegma/storage-core` at `0.4.0`
across the stack. The public API remains unstable.
**Stage:** Phases 1–4 are complete. The published `0.2.0` release aligned
`@pegma/storage-core` at `0.4.0`. RetireGolden is the first integrated consumer
and pegma.dev is the second, live consumer. The `0.2.1` patch moves default
clock observations after awaited reads and sweep snapshots. Publication is
recorded in [GitHub releases](https://github.com/pegma-dev/sessions/releases)
and [npm](https://www.npmjs.com/package/@pegma/sessions); source metadata alone
does not publish a version. The public API remains unstable.

Phase 1 is merged on `main`
([PR #1](https://github.com/pegma-dev/sessions/pull/1), `f5ea435`,
Expand Down
23 changes: 14 additions & 9 deletions docs/RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ There is no npm-token or manual-dispatch fallback.

## Historical `v0.1.0` exception

`@pegma/sessions@0.1.0` is published and is the current `latest` version. It
`@pegma/sessions@0.1.0` was the first published version. It
is immutable, but it predates the hardened release path:

- the GitHub release used a lightweight tag at
Expand Down Expand Up @@ -110,7 +110,10 @@ After the first OIDC release succeeds, set npm Publishing access to

Prepare every version from `0.1.1` onward through an ordinary pull request
that updates the root, workspace, and lockfile versions together and adds
reviewed release notes. Run the complete gate and a local release pack on
reviewed release notes. Keep README and project-plan status factual, using
release checkpoints and registry links for publication status. Release notes
describe version behavior without a candidate/publication label that would
become stale after release. Run the complete gate and a local release pack on
Node 22 and 24. Node 25 and later do not bundle Corepack, so install it
first if `corepack` is missing:

Expand All @@ -127,20 +130,22 @@ pnpm run release:pack -- -- --output .release
```

After merge, create and verify the tag before creating the GitHub release.
For example, for the next patch release:
For example, for the next patch release. The final command sends only the
current version's section to GitHub; older sections stay in the changelog:

```sh
git fetch origin
git switch --detach origin/main
git config gpg.format ssh
git config user.signingkey ~/.ssh/pegma-release-signing-key
git config gpg.ssh.allowedSignersFile ~/.config/pegma/release-allowed-signers
git tag --sign v0.2.0 --message "Sessions v0.2.0" HEAD
git verify-tag v0.2.0
git push origin refs/tags/v0.2.0
git fetch origin tag v0.2.0 --force
git verify-tag v0.2.0
gh release create v0.2.0 --verify-tag --title "@pegma/sessions v0.2.0" --notes-file RELEASE_NOTES.md
git tag --sign v0.2.1 --message "Sessions v0.2.1" HEAD
git verify-tag v0.2.1
git push origin refs/tags/v0.2.1
git fetch origin tag v0.2.1 --force
git verify-tag v0.2.1
node --input-type=module -e 'import { readFileSync } from "node:fs"; process.stdout.write(readFileSync("RELEASE_NOTES.md", "utf8").split("\n# @pegma/sessions ")[0]);' |
gh release create v0.2.1 --verify-tag --title "@pegma/sessions v0.2.1" --notes-file -
```

Do not let `gh release create` create a tag. Never move or recreate a release
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sessions",
"version": "0.2.0",
"version": "0.2.1",
"private": true,
"description": "Server-side session records for Pegma components.",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion packages/sessions/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@pegma/sessions",
"version": "0.2.0",
"version": "0.2.1",
"description": "Hashed server-side session records with absolute and idle expiry.",
"license": "MIT",
"type": "module",
Expand Down
219 changes: 219 additions & 0 deletions packages/sessions/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,50 @@ function wrapSessionCollection(
};
}

function pauseSessionRead(base: Store) {
let next: "getVersioned" | "listVersioned" | undefined;
let reached!: () => void;
let release!: () => void;
const entered = new Promise<void>((resolve) => {
reached = resolve;
});
const resume = new Promise<void>((resolve) => {
release = resolve;
});
async function before(method: "getVersioned" | "listVersioned") {
if (next !== method) return;
next = undefined;
reached();
await resume;
}
const store = wrapSessionCollection(base, (collection) => {
const getVersioned: typeof collection.getVersioned = async (...args) => {
await before("getVersioned");
return collection.getVersioned(...args);
};
const listVersioned: typeof collection.listVersioned = async (...args) => {
await before("listVersioned");
return collection.listVersioned(...args);
};
return new Proxy(collection, {
get(target, property) {
if (property === "getVersioned") return getVersioned;
if (property === "listVersioned") return listVersioned;
const value = Reflect.get(target, property, target);
return typeof value === "function" ? value.bind(target) : value;
},
});
});
return {
store,
entered,
release,
arm(method: typeof next) {
next = method;
},
};
}

function recordingLogger() {
const entries: {
readonly level: string;
Expand Down Expand Up @@ -230,6 +274,167 @@ for (const backend of backends) {
).toThrow(/positive finite/);
});

it("observes the default clock after an overlapping read has touched the live session", async () => {
const inspected = inspectStorage(backend.freshStore());
const paused = pauseSessionRead(inspected.store);
let milliseconds = Date.parse(NOW);
const clock = { now: () => new Date(milliseconds).toISOString() };
const sessions = createSessionStore(paused.store, { clock });
await sessions.create("overlapping-default-read", NEW_SESSION);

paused.arm("getVersioned");
const earlier = sessions.get("overlapping-default-read");
await paused.entered;
milliseconds += 1;
try {
// This actual SDK read, not a forged storage row, advances lastSeenAt.
expect(await sessions.get("overlapping-default-read")).not.toBeNull();
} finally {
paused.release();
}

expect((await earlier)?.lastSeenAt).toBe(clock.now());
expect(await sessions.get("overlapping-default-read")).not.toBeNull();
expect(
storedSessions(await inspected.records().list("session")),
).toHaveLength(1);
});

it("observes the default sweep clock after an overlapping read has touched the live session", async () => {
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
const inspected = inspectStorage(backend.freshStore());
const paused = pauseSessionRead(inspected.store);
let milliseconds = Date.parse(NOW);
const clock = { now: () => new Date(milliseconds).toISOString() };
const sessions = createSessionStore(paused.store, { clock });
await sessions.create("overlapping-default-sweep", NEW_SESSION);

paused.arm("listVersioned");
const sweeping = sessions.purgeExpired();
await paused.entered;
milliseconds += 1;
try {
expect(await sessions.get("overlapping-default-sweep")).not.toBeNull();
} finally {
paused.release();
}

expect(await sweeping).toBe(0);
expect(await sessions.get("overlapping-default-sweep")).not.toBeNull();
expect(
storedSessions(await inspected.records().list("session")),
).toHaveLength(1);
});

it("observes expiry at the default clock after the awaited session read", async () => {
const inspected = inspectStorage(backend.freshStore());
const paused = pauseSessionRead(inspected.store);
let milliseconds = Date.parse(NOW);
const clock = { now: () => new Date(milliseconds).toISOString() };
const sessions = createSessionStore(paused.store, {
clock,
absoluteLifetimeMs: 1_000,
});
await sessions.create("delayed-default-expiry", NEW_SESSION);

paused.arm("getVersioned");
const reading = sessions.get("delayed-default-expiry");
await paused.entered;
try {
milliseconds += 1_000;
} finally {
paused.release();
}

expect(await reading).toBeNull();
expect(
storedSessions(await inspected.records().list("session")),
).toHaveLength(0);
});

it("observes expiry at the default clock after the awaited sweep list", async () => {
const inspected = inspectStorage(backend.freshStore());
const paused = pauseSessionRead(inspected.store);
let milliseconds = Date.parse(NOW);
const clock = { now: () => new Date(milliseconds).toISOString() };
const sessions = createSessionStore(paused.store, {
clock,
absoluteLifetimeMs: 1_000,
});
await sessions.create("delayed-sweep-expiry", NEW_SESSION);

paused.arm("listVersioned");
const sweeping = sessions.purgeExpired();
await paused.entered;
try {
milliseconds += 1_000;
} finally {
paused.release();
}

expect(await sweeping).toBe(1);
expect(
storedSessions(await inspected.records().list("session")),
).toHaveLength(0);
});

it("observes one default clock after a missing read and an empty sweep", async () => {
const paused = pauseSessionRead(backend.freshStore());
let observations = 0;
const sessions = createSessionStore(paused.store, {
clock: {
now() {
++observations;
return NOW;
},
},
});
paused.arm("getVersioned");
const missing = sessions.get("unknown-session");
await paused.entered;
try {
expect(observations).toBe(0);
} finally {
paused.release();
}

expect(await missing).toBeNull();
expect(observations).toBe(1);
expect(await sessions.purgeExpired()).toBe(0);
expect(observations).toBe(2);
expect(await sessions.get("unknown-session", NOW)).toBeNull();
expect(await sessions.purgeExpired(NOW)).toBe(0);
expect(observations).toBe(2);
});

it("preserves explicit read and sweep instants after awaited storage", async () => {
const inspected = inspectStorage(backend.freshStore());
const paused = pauseSessionRead(inspected.store);
let milliseconds = Date.parse(NOW);
const clock = { now: () => new Date(milliseconds).toISOString() };
const sessions = createSessionStore(paused.store, {
clock,
absoluteLifetimeMs: 1_000,
});
await sessions.create("explicit-read-instant", NEW_SESSION);
const explicitNow = "2026-07-27T12:00:00.500Z";

paused.arm("getVersioned");
const reading = sessions.get("explicit-read-instant", explicitNow);
await paused.entered;
try {
milliseconds += 1_000;
} finally {
paused.release();
}

expect(await reading).not.toBeNull();
expect(await sessions.purgeExpired(explicitNow)).toBe(0);
expect(
storedSessions(await inspected.records().list("session")),
).toHaveLength(1);
expect(await sessions.get("explicit-read-instant")).toBeNull();
});

it("returns the initially validated record without claiming its touch", async () => {
const sessions = createSessionStore(backend.freshStore(), {
clock: fixedClock(NOW),
Expand Down Expand Up @@ -336,6 +541,20 @@ for (const backend of backends) {

await sessions.create("invalid-purge-now", NEW_SESSION);
expect(await sessions.purgeExpired("still-not-a-time")).toBe(1);

// JavaScript callers can supply malformed values despite the TS type.
// Only undefined selects the default clock; null must still fail closed.
await sessions.create("invalid-null-read", NEW_SESSION);
expect(
await Reflect.apply(sessions.get, sessions, [
"invalid-null-read",
null,
]),
).toBeNull();
await sessions.create("invalid-null-purge", NEW_SESSION);
expect(await Reflect.apply(sessions.purgeExpired, sessions, [null])).toBe(
1,
);
});

it("fails closed on a future idle anchor", async () => {
Expand Down
Loading
Loading