@smthrs/journal 1.0.0-rc.7 → 1.0.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,7 +27,7 @@ import * as Duration from "effect/Duration";
27
27
  import * as Effect from "effect/Effect";
28
28
  import * as Layer from "effect/Layer";
29
29
  import * as SqlClient from "effect/sql/SqlClient";
30
- import { Consensus, ConsensusError, fenceLost, heartbeatStaleAfter, matchesEvidence } from "./Consensus.js";
30
+ import { Consensus, ConsensusError, fenceLost, heartbeatStaleAfter, matchesEvidence, provesDeath } from "./Consensus.js";
31
31
  const staleAfterMs = Duration.toMillis(heartbeatStaleAfter);
32
32
  const rejected = (reason) => ({ _tag: "Rejected", reason });
33
33
  const claimed = (grantedAtMs) => ({ _tag: "Claimed", grantedAtMs });
@@ -175,7 +175,7 @@ export const make = Effect.gen(function* () {
175
175
  AND owner_host_id = ${evidence.expectedOwner.hostId}
176
176
  AND owner_pid = ${evidence.expectedOwner.pid}
177
177
  AND owner_nonce = ${evidence.expectedOwner.nonce}
178
- AND heartbeat_at_ms < ${nowMs - staleAfterMs}
178
+ AND ${provesDeath(evidence, claimant) ? sql `TRUE` : sql `heartbeat_at_ms < ${nowMs - staleAfterMs}`}
179
179
  AND claim_host_id IS NULL
180
180
  RETURNING run_id
181
181
  `;
@@ -1 +1 @@
1
- {"version":3,"file":"SqlConsensus.js","sourceRoot":"","sources":["../../src/SqlConsensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,OAAO,MAAM,0BAA0B,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAA;AAC9D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAA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qB,MAAM,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,KAAa,EAAE,KAAc,EAAE,EAAE,CAC7F,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;QACxB,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,GAAG,CAAyB;;yBAE7B,KAAK;gCACE,KAAK,CAAC,MAAM;4BAChB,KAAK,CAAC,GAAG;8BACP,KAAK,CAAC,KAAK;OAClC,CAAA;QACD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACtB,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;QACpD,CAAC;IACH,CAAC,CAAC,CAAC,CACJ,CAAA;IAED,OAAO,SAAS,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAA;AAChG,CAAC,CAAC,CAAA;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAuE,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA","sourcesContent":["/**\n * The default database-backed consensus strategy.\n *\n * This is the run store's former `flows_runs` ownership compare-and-swap\n * relocated: the owner tuple, the two-phase claim columns, claim recovery, and\n * the grant timestamp are the private schema of one strategy — the\n * `flows_consensus_leases` table — instead of a public contract on the run\n * row. The run row still mirrors the outcome, but the lease is what\n * arbitrates.\n *\n * Commit-time admission (R3) is exact: `guard` is a plain SELECT that joins\n * the caller's open write transaction — `DurableWriter` serializes write\n * transactions, so no reclaim can commit between the guard read and the\n * statements beside it — and every mutating operation runs through\n * `DurableWriter.write`, joining an enclosing transaction as a savepoint.\n * Prior art: Temporal's shard `rangeID` check\n * (`reference/temporal/service/history/shard/context_impl.go`,\n * `renewRangeLocked`).\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n *\n * @since 1.0.0\n */\n\nimport * as Dialect from \"@smthrs/database/Dialect\"\nimport { DurableWriter } from \"@smthrs/database/DurableWriter\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport {\n type ActivateOutcome,\n type Claimed,\n type ClaimOutcome,\n Consensus,\n ConsensusError,\n fenceLost,\n type HeartbeatOutcome,\n heartbeatStaleAfter,\n type LivenessEvidence,\n matchesEvidence,\n type RecoverOutcome,\n type Rejected,\n type RejectionReason,\n type Service\n} from \"./Consensus.ts\"\nimport type { OwnerId } from \"./OwnerId.ts\"\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost = { _tag: \"Lost\" } as const\nconst activated = { _tag: \"Activated\" } as const\nconst recovered = { _tag: \"Recovered\" } as const\n\ninterface LeaseRow {\n readonly owner_host_id: string | null\n readonly owner_pid: number | null\n readonly owner_nonce: string | null\n readonly claim_host_id: string | null\n readonly claim_pid: number | null\n readonly claim_nonce: string | null\n}\n\n/**\n * Constructs the database-backed strategy over the context's SQL client and\n * durable writer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlClient> = Effect.gen(function*() {\n const sql = yield* Effect.service(SqlClient.SqlClient)\n const writer = yield* DurableWriter\n\n const strategyError = (cause: unknown): ConsensusError =>\n new ConsensusError({\n code: \"persistence_failed\",\n message: \"consensus lease operation failed\",\n cause\n })\n\n // The original cause is preserved through the wrapper so an enclosing\n // `DurableWriter.write`'s retry classification still sees a transient\n // conflict raised by a savepoint-nested lease statement.\n const write = <A>(\n body: Effect.Effect<A, unknown>\n ): Effect.Effect<A, ConsensusError> =>\n writer.write(body).pipe(Effect.mapError((cause) => cause instanceof ConsensusError ? cause : strategyError(cause)))\n\n const leaseOf = (runId: string) =>\n sql<LeaseRow>`\n SELECT owner_host_id, owner_pid, owner_nonce, claim_host_id, claim_pid, claim_nonce\n FROM flows_consensus_leases\n WHERE run_id = ${runId}\n `\n\n const prune = (runId: string) =>\n sql`\n DELETE FROM flows_consensus_leases\n WHERE run_id = ${runId} AND owner_host_id IS NULL AND claim_host_id IS NULL\n `\n\n const claim: Service[\"claim\"] = Effect.fn(\"Consensus.claim\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n INSERT INTO flows_consensus_leases (run_id, claim_host_id, claim_pid, claim_nonce, claimed_at_ms)\n VALUES (${runId}, ${claimant.hostId}, ${claimant.pid}, ${claimant.nonce}, ${nowMs})\n ON CONFLICT (run_id) DO UPDATE SET\n claim_host_id = excluded.claim_host_id,\n claim_pid = excluded.claim_pid,\n claim_nonce = excluded.claim_nonce,\n claimed_at_ms = excluded.claimed_at_ms\n WHERE flows_consensus_leases.claim_host_id IS NULL\n AND flows_consensus_leases.owner_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n // The upsert only misses on a conflicting row, so the lease exists and\n // holds a claim, an owner, or both.\n const lease = (yield* leaseOf(runId))[0]!\n return lease.claim_host_id !== null ? rejected(\"already_claimed\") : rejected(\"owner_held\")\n }))\n )\n\n const activate: Service[\"activate\"] = Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n owner_host_id = ${owner.hostId},\n owner_pid = ${owner.pid},\n owner_nonce = ${owner.nonce},\n granted_at_ms = ${grantedAtMs},\n heartbeat_at_ms = ${nowMs},\n claim_host_id = NULL,\n claim_pid = NULL,\n claim_nonce = NULL,\n claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n RETURNING run_id\n `\n return (rows.length > 0 ? activated : lost) satisfies ActivateOutcome\n }))\n )\n\n const heartbeat: Service[\"heartbeat\"] = Effect.fn(\"Consensus.heartbeat\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // Monotonic: a pulse delayed past a newer one from the same owner never\n // moves the lease backwards and never makes a live run look stale.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const reconfirm: Service[\"reconfirm\"] = Effect.fn(\"Consensus.reconfirm\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // A pending steal has already reserved the lease, even before activation.\n // Compare both owner and claim in the same update as the renewal.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n AND claim_host_id IS NULL\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const release: Service[\"release\"] = Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n yield* sql`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n `\n yield* sql`\n UPDATE flows_consensus_leases\n SET owner_host_id = NULL, owner_pid = NULL, owner_nonce = NULL,\n granted_at_ms = NULL, heartbeat_at_ms = NULL\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n yield* prune(runId)\n }))\n )\n\n const steal: Service[\"steal\"] = Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<ClaimOutcome, ConsensusError> => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n claim_host_id = ${claimant.hostId},\n claim_pid = ${claimant.pid},\n claim_nonce = ${claimant.nonce},\n claimed_at_ms = ${nowMs}\n WHERE run_id = ${runId}\n AND owner_host_id = ${evidence.expectedOwner.hostId}\n AND owner_pid = ${evidence.expectedOwner.pid}\n AND owner_nonce = ${evidence.expectedOwner.nonce}\n AND heartbeat_at_ms < ${nowMs - staleAfterMs}\n AND claim_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n const lease = (yield* leaseOf(runId))[0]\n if (lease !== undefined && lease.claim_host_id !== null) return rejected(\"already_claimed\")\n if (\n lease === undefined ||\n lease.owner_host_id !== evidence.expectedOwner.hostId ||\n Number(lease.owner_pid) !== evidence.expectedOwner.pid ||\n lease.owner_nonce !== evidence.expectedOwner.nonce\n ) {\n // A run nobody owns, or one owned by somebody else, has no owner\n // this evidence could disprove.\n return rejected(\"evidence_invalid\")\n }\n return rejected(\"owner_live\")\n }))\n })\n )\n\n const recover: Service[\"recover\"] = Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<RecoverOutcome, ConsensusError> => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n AND claimed_at_ms < ${nowMs - staleAfterMs}\n RETURNING run_id\n `\n if (rows.length > 0) {\n yield* prune(runId)\n return recovered\n }\n const matches = yield* sql<{ readonly run_id: string }>`\n SELECT run_id FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n `\n // The exact claim survived the compare-and-swap only because it is\n // not yet stale; anything else means the claim moved on.\n return matches.length > 0 ? rejected(\"claim_fresh\") : rejected(\"claim_changed\")\n }))\n })\n )\n\n const guard: Service[\"guard\"] = Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n const held = yield* sql<{ readonly ok: number }>`\n SELECT 1 AS ok FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n if (held.length === 0) {\n return yield* Effect.fail(fenceLost(runId, owner))\n }\n }))\n )\n\n return Consensus.of({ claim, activate, heartbeat, reconfirm, release, steal, recover, guard })\n})\n\n/**\n * Provides the database-backed strategy.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Consensus, never, DurableWriter | SqlClient.SqlClient> = Layer.effect(Consensus, make)\n"]}
1
+ {"version":3,"file":"SqlConsensus.js","sourceRoot":"","sources":["../../src/SqlConsensus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,OAAO,MAAM,0BAA0B,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAA;AAC9D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA;AACjD,OAAO,EAIL,SAAS,EACT,cAAc,EACd,SAAS,EAET,mBAAmB,EAEnB,eAAe,EACf,WAAW,EAKZ,MAAM,gBAAgB,CAAA;AAGvB,MAAM,YAAY,GAAG,QAAQ,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAA;AAE3D,MAAM,QAAQ,GAAG,CAAC,MAAuB,EAAY,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAA;AACtF,MAAM,OAAO,GAAG,CAAC,WAAmB,EAAW,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC,CAAA;AACpF,MAAM,IAAI,GAAG,EAAE,IAAI,EAAE,MAAM,EAAW,CAAA;AACtC,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,WAAW,EAAW,CA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SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;QACpD,CAAC;IACH,CAAC,CAAC,CAAC,CACJ,CAAA;IAED,OAAO,SAAS,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAA;AAChG,CAAC,CAAC,CAAA;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAuE,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA","sourcesContent":["/**\n * The default database-backed consensus strategy.\n *\n * This is the run store's former `flows_runs` ownership compare-and-swap\n * relocated: the owner tuple, the two-phase claim columns, claim recovery, and\n * the grant timestamp are the private schema of one strategy — the\n * `flows_consensus_leases` table — instead of a public contract on the run\n * row. The run row still mirrors the outcome, but the lease is what\n * arbitrates.\n *\n * Commit-time admission (R3) is exact: `guard` is a plain SELECT that joins\n * the caller's open write transaction — `DurableWriter` serializes write\n * transactions, so no reclaim can commit between the guard read and the\n * statements beside it — and every mutating operation runs through\n * `DurableWriter.write`, joining an enclosing transaction as a savepoint.\n * Prior art: Temporal's shard `rangeID` check\n * (`reference/temporal/service/history/shard/context_impl.go`,\n * `renewRangeLocked`).\n *\n * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.\n *\n * @since 1.0.0\n */\n\nimport * as Dialect from \"@smthrs/database/Dialect\"\nimport { DurableWriter } from \"@smthrs/database/DurableWriter\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as SqlClient from \"effect/sql/SqlClient\"\nimport {\n type ActivateOutcome,\n type Claimed,\n type ClaimOutcome,\n Consensus,\n ConsensusError,\n fenceLost,\n type HeartbeatOutcome,\n heartbeatStaleAfter,\n type LivenessEvidence,\n matchesEvidence,\n provesDeath,\n type RecoverOutcome,\n type Rejected,\n type RejectionReason,\n type Service\n} from \"./Consensus.ts\"\nimport type { OwnerId } from \"./OwnerId.ts\"\n\nconst staleAfterMs = Duration.toMillis(heartbeatStaleAfter)\n\nconst rejected = (reason: RejectionReason): Rejected => ({ _tag: \"Rejected\", reason })\nconst claimed = (grantedAtMs: number): Claimed => ({ _tag: \"Claimed\", grantedAtMs })\nconst lost = { _tag: \"Lost\" } as const\nconst activated = { _tag: \"Activated\" } as const\nconst recovered = { _tag: \"Recovered\" } as const\n\ninterface LeaseRow {\n readonly owner_host_id: string | null\n readonly owner_pid: number | null\n readonly owner_nonce: string | null\n readonly claim_host_id: string | null\n readonly claim_pid: number | null\n readonly claim_nonce: string | null\n}\n\n/**\n * Constructs the database-backed strategy over the context's SQL client and\n * durable writer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlClient> = Effect.gen(function*() {\n const sql = yield* Effect.service(SqlClient.SqlClient)\n const writer = yield* DurableWriter\n\n const strategyError = (cause: unknown): ConsensusError =>\n new ConsensusError({\n code: \"persistence_failed\",\n message: \"consensus lease operation failed\",\n cause\n })\n\n // The original cause is preserved through the wrapper so an enclosing\n // `DurableWriter.write`'s retry classification still sees a transient\n // conflict raised by a savepoint-nested lease statement.\n const write = <A>(\n body: Effect.Effect<A, unknown>\n ): Effect.Effect<A, ConsensusError> =>\n writer.write(body).pipe(Effect.mapError((cause) => cause instanceof ConsensusError ? cause : strategyError(cause)))\n\n const leaseOf = (runId: string) =>\n sql<LeaseRow>`\n SELECT owner_host_id, owner_pid, owner_nonce, claim_host_id, claim_pid, claim_nonce\n FROM flows_consensus_leases\n WHERE run_id = ${runId}\n `\n\n const prune = (runId: string) =>\n sql`\n DELETE FROM flows_consensus_leases\n WHERE run_id = ${runId} AND owner_host_id IS NULL AND claim_host_id IS NULL\n `\n\n const claim: Service[\"claim\"] = Effect.fn(\"Consensus.claim\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n INSERT INTO flows_consensus_leases (run_id, claim_host_id, claim_pid, claim_nonce, claimed_at_ms)\n VALUES (${runId}, ${claimant.hostId}, ${claimant.pid}, ${claimant.nonce}, ${nowMs})\n ON CONFLICT (run_id) DO UPDATE SET\n claim_host_id = excluded.claim_host_id,\n claim_pid = excluded.claim_pid,\n claim_nonce = excluded.claim_nonce,\n claimed_at_ms = excluded.claimed_at_ms\n WHERE flows_consensus_leases.claim_host_id IS NULL\n AND flows_consensus_leases.owner_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n // The upsert only misses on a conflicting row, so the lease exists and\n // holds a claim, an owner, or both.\n const lease = (yield* leaseOf(runId))[0]!\n return lease.claim_host_id !== null ? rejected(\"already_claimed\") : rejected(\"owner_held\")\n }))\n )\n\n const activate: Service[\"activate\"] = Effect.fn(\"Consensus.activate\")((\n runId: string,\n owner: OwnerId,\n grantedAtMs: number,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n owner_host_id = ${owner.hostId},\n owner_pid = ${owner.pid},\n owner_nonce = ${owner.nonce},\n granted_at_ms = ${grantedAtMs},\n heartbeat_at_ms = ${nowMs},\n claim_host_id = NULL,\n claim_pid = NULL,\n claim_nonce = NULL,\n claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n RETURNING run_id\n `\n return (rows.length > 0 ? activated : lost) satisfies ActivateOutcome\n }))\n )\n\n const heartbeat: Service[\"heartbeat\"] = Effect.fn(\"Consensus.heartbeat\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // Monotonic: a pulse delayed past a newer one from the same owner never\n // moves the lease backwards and never makes a live run look stale.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const reconfirm: Service[\"reconfirm\"] = Effect.fn(\"Consensus.reconfirm\")((\n runId: string,\n owner: OwnerId,\n nowMs: number\n ) =>\n write(Effect.gen(function*() {\n // A pending steal has already reserved the lease, even before activation.\n // Compare both owner and claim in the same update as the renewal.\n const rows = yield* sql<{ readonly heartbeat_at_ms: number }>`\n UPDATE flows_consensus_leases\n SET heartbeat_at_ms = ${Dialect.greatest(sql)}(heartbeat_at_ms, ${nowMs})\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n AND claim_host_id IS NULL\n RETURNING heartbeat_at_ms\n `\n const row = rows[0]\n return (row === undefined\n ? lost\n : { _tag: \"Renewed\", heartbeatAtMs: Number(row.heartbeat_at_ms) }) satisfies HeartbeatOutcome\n }))\n )\n\n const release: Service[\"release\"] = Effect.fn(\"Consensus.release\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n yield* sql`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${owner.hostId}\n AND claim_pid = ${owner.pid}\n AND claim_nonce = ${owner.nonce}\n `\n yield* sql`\n UPDATE flows_consensus_leases\n SET owner_host_id = NULL, owner_pid = NULL, owner_nonce = NULL,\n granted_at_ms = NULL, heartbeat_at_ms = NULL\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n yield* prune(runId)\n }))\n )\n\n const steal: Service[\"steal\"] = Effect.fn(\"Consensus.steal\")((\n runId: string,\n claimant: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<ClaimOutcome, ConsensusError> => {\n if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET\n claim_host_id = ${claimant.hostId},\n claim_pid = ${claimant.pid},\n claim_nonce = ${claimant.nonce},\n claimed_at_ms = ${nowMs}\n WHERE run_id = ${runId}\n AND owner_host_id = ${evidence.expectedOwner.hostId}\n AND owner_pid = ${evidence.expectedOwner.pid}\n AND owner_nonce = ${evidence.expectedOwner.nonce}\n AND ${provesDeath(evidence, claimant) ? sql`TRUE` : sql`heartbeat_at_ms < ${nowMs - staleAfterMs}`}\n AND claim_host_id IS NULL\n RETURNING run_id\n `\n if (rows.length > 0) return claimed(nowMs)\n const lease = (yield* leaseOf(runId))[0]\n if (lease !== undefined && lease.claim_host_id !== null) return rejected(\"already_claimed\")\n if (\n lease === undefined ||\n lease.owner_host_id !== evidence.expectedOwner.hostId ||\n Number(lease.owner_pid) !== evidence.expectedOwner.pid ||\n lease.owner_nonce !== evidence.expectedOwner.nonce\n ) {\n // A run nobody owns, or one owned by somebody else, has no owner\n // this evidence could disprove.\n return rejected(\"evidence_invalid\")\n }\n return rejected(\"owner_live\")\n }))\n })\n )\n\n const recover: Service[\"recover\"] = Effect.fn(\"Consensus.recover\")((\n runId: string,\n staleClaimant: OwnerId,\n grantedAtMs: number,\n observer: OwnerId,\n nowMs: number,\n evidence: LivenessEvidence\n ) =>\n Effect.suspend((): Effect.Effect<RecoverOutcome, ConsensusError> => {\n if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) {\n return Effect.succeed(rejected(\"evidence_invalid\"))\n }\n return write(Effect.gen(function*() {\n const rows = yield* sql<{ readonly run_id: string }>`\n UPDATE flows_consensus_leases\n SET claim_host_id = NULL, claim_pid = NULL, claim_nonce = NULL, claimed_at_ms = NULL\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n AND claimed_at_ms < ${nowMs - staleAfterMs}\n RETURNING run_id\n `\n if (rows.length > 0) {\n yield* prune(runId)\n return recovered\n }\n const matches = yield* sql<{ readonly run_id: string }>`\n SELECT run_id FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND claim_host_id = ${staleClaimant.hostId}\n AND claim_pid = ${staleClaimant.pid}\n AND claim_nonce = ${staleClaimant.nonce}\n AND claimed_at_ms = ${grantedAtMs}\n `\n // The exact claim survived the compare-and-swap only because it is\n // not yet stale; anything else means the claim moved on.\n return matches.length > 0 ? rejected(\"claim_fresh\") : rejected(\"claim_changed\")\n }))\n })\n )\n\n const guard: Service[\"guard\"] = Effect.fn(\"Consensus.guard\")((runId: string, owner: OwnerId) =>\n write(Effect.gen(function*() {\n const held = yield* sql<{ readonly ok: number }>`\n SELECT 1 AS ok FROM flows_consensus_leases\n WHERE run_id = ${runId}\n AND owner_host_id = ${owner.hostId}\n AND owner_pid = ${owner.pid}\n AND owner_nonce = ${owner.nonce}\n `\n if (held.length === 0) {\n return yield* Effect.fail(fenceLost(runId, owner))\n }\n }))\n )\n\n return Consensus.of({ claim, activate, heartbeat, reconfirm, release, steal, recover, guard })\n})\n\n/**\n * Provides the database-backed strategy.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Consensus, never, DurableWriter | SqlClient.SqlClient> = Layer.effect(Consensus, make)\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"Notifying.js","sourceRo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EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAC3C;oBACD,CAAC,CAAC,MAAM,CAAA;YACZ,CAAC,CAAA;QACH,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACtB,CAAC;IACH,CAAC;IACD,OAAO,OAAY,CAAA;AACrB,CAAC,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CACnB,GAAuB,EACvB,IAAU,EACkB,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAA","sourcesContent":["/**\n * Effect-native analogue of Bazel Skyframe's `NotifyingHelper` and\n * `NotifyingInMemoryGraph`: wrap a record-of-Effect-methods service so a listener hook fires around\n * every operation. The hook runs in the calling fiber, so a hook that dies,\n * interrupts, or awaits a `Latch` injects crashes, fence loss, and exact\n * sequencing at any durable transition point, the mechanism that makes\n * interstitial interleaving bugs testable at all.\n *\n * Deliberately NOT ported from Skyframe: `DeterministicHelper`'s\n * deterministic-scheduler machinery, `ChainedFunction`, and `TrackingAwaiter`.\n * Effect already gives us deterministic fibers, `TestClock`, `Latch`, and\n * failure propagation across fiber joins, so those helpers have no residue\n * here.\n *\n * @since 0.1.0\n */\n\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * Whether the hook is firing before or after the delegated operation.\n * Skyframe's `NotifyingHelper.Order`, minus its `BEFORE_AND_AFTER` (pass the\n * same hook body for both firings instead).\n *\n * @category models\n * @since 0.1.0\n */\nexport type Order = \"before\" | \"after\"\n\n/**\n * Listener invoked around every delegated operation. `op` is the service\n * method name (Skyframe's `EventType`, but open-world), `args` the call\n * arguments. Express crash injection as `Effect.die` or `Effect.interrupt`\n * inside the hook, the hook's type stays `Effect<void>` so the wrapped\n * service is structurally identical to the real one.\n *\n * The `after` firing only happens when the operation succeeds; a failed\n * operation already is the interesting event.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Hook = (\n op: string,\n order: Order,\n args: ReadonlyArray<unknown>\n) => Effect.Effect<void>\n\n/**\n * Wraps a service so `hook(op, \"before\" | \"after\", args)` fires around every\n * Effect-valued operation, delegating to the real implementation in between.\n *\n * Generic over any record-of-Effect-methods service (`Journal`, `CacheStore`,\n * `AttemptStore`, `RunStore`, ...): Effect-returning methods and plain Effect\n * properties are hooked; non-Effect members (e.g. `Stream`-returning methods)\n * delegate untouched.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const wrap = <S extends object>(service: S, hook: Hook): S => {\n const wrapped: Record<string, unknown> = {}\n for (const key of Object.keys(service)) {\n const value = (service as Record<string, unknown>)[key]\n if (Effect.isEffect(value)) {\n wrapped[key] = hook(key, \"before\", []).pipe(\n Effect.andThen(value as Effect.Effect<unknown, unknown, unknown>),\n Effect.tap(() => hook(key, \"after\", []))\n )\n } else if (typeof value === \"function\") {\n const method = value as (...args: Array<unknown>) => unknown\n wrapped[key] = (...args: Array<unknown>) => {\n const result = method.apply(service, args)\n return Effect.isEffect(result)\n ? hook(key, \"before\", args).pipe(\n Effect.andThen(result as Effect.Effect<unknown, unknown, unknown>),\n Effect.tap(() => hook(key, \"after\", args))\n )\n : result\n }\n } else {\n wrapped[key] = value\n }\n }\n return wrapped as S\n}\n\n/**\n * Layer form of {@link wrap}: reads the real service from the environment and\n * re-provides the notifying wrapper under the same key, so an existing stack\n * gains a listener without touching its construction.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer = <Id, S extends object>(\n tag: Context.Key<Id, S>,\n hook: Hook\n): Layer.Layer<Id, never, Id> => Layer.effect(tag)(Effect.map(tag, (service) => wrap(service, hook)))\n"]}
1
+ {"version":3,"file":"Notifying.js","sourceRoot":"","sources":["../../../src/test/Notifying.ts"],"names":[],"mappings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;oBACD,CAAC,CAAC,MAAM,CAAA;YACZ,CAAC,CAAA;QACH,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;QACtB,CAAC;IACH,CAAC;IACD,OAAO,OAAY,CAAA;AACrB,CAAC,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CACnB,GAAuB,EACvB,IAAU,EACkB,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAA","sourcesContent":["/**\n * Effect-native analogue of Bazel Skyframe's `NotifyingHelper` and\n * `NotifyingInMemoryGraph`: wrap a record-of-Effect-methods service so a listener hook fires around\n * every operation. The hook runs in the calling fiber, so a hook that dies,\n * interrupts, or awaits a `Latch` injects crashes, fence loss, and exact\n * sequencing at any durable transition point, the mechanism that makes\n * interstitial interleaving bugs testable at all.\n *\n * Deliberately NOT ported from Skyframe: `DeterministicHelper`'s\n * deterministic-scheduler machinery, `ChainedFunction`, and `TrackingAwaiter`.\n * Effect already gives us deterministic fibers, `TestClock`, `Latch`, and\n * failure propagation across fiber joins, so those helpers have no residue\n * here.\n *\n * @since 0.1.0\n */\n\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * Whether the hook is firing before or after the delegated operation.\n * Skyframe's `NotifyingHelper.Order`, minus its `BEFORE_AND_AFTER` (pass the\n * same hook body for both firings instead).\n *\n * @category models\n * @since 0.1.0\n */\nexport type Order = \"before\" | \"after\"\n\n/**\n * Listener invoked around every delegated operation. `op` is the service\n * method name (Skyframe's `EventType`, but open-world), `args` the call\n * arguments. Express crash injection as `Effect.die` or `Effect.interrupt`\n * inside the hook, the hook's type stays `Effect<void>` so the wrapped\n * service is structurally identical to the real one.\n *\n * The `after` firing only happens when the operation succeeds; a failed\n * operation already is the interesting event.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Hook = (\n op: string,\n order: Order,\n args: ReadonlyArray<unknown>\n) => Effect.Effect<void>\n\n/**\n * Wraps a service so `hook(op, \"before\" | \"after\", args)` fires around every\n * Effect-valued operation, delegating to the real implementation in between.\n *\n * Generic over any record-of-Effect-methods service (`Journal`, `CacheStore`,\n * `AttemptStore`, `RunStore`, ...): Effect-returning methods and plain Effect\n * properties are hooked; non-Effect members (e.g. `Stream`-returning methods)\n * delegate untouched.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const wrap = <S extends object>(service: S, hook: Hook): S => {\n const wrapped: Record<string, unknown> = {}\n for (const key of Object.keys(service)) {\n const value = (service as Record<string, unknown>)[key]\n if (Effect.isEffect(value)) {\n wrapped[key] = hook(key, \"before\", []).pipe(\n Effect.andThen(value),\n Effect.tap(() => hook(key, \"after\", []))\n )\n } else if (typeof value === \"function\") {\n const method = value as (...args: Array<unknown>) => unknown\n wrapped[key] = (...args: Array<unknown>) => {\n const result = method.apply(service, args)\n return Effect.isEffect(result)\n ? hook(key, \"before\", args).pipe(\n Effect.andThen(result),\n Effect.tap(() => hook(key, \"after\", args))\n )\n : result\n }\n } else {\n wrapped[key] = value\n }\n }\n return wrapped as S\n}\n\n/**\n * Layer form of {@link wrap}: reads the real service from the environment and\n * re-provides the notifying wrapper under the same key, so an existing stack\n * gains a listener without touching its construction.\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer = <Id, S extends object>(\n tag: Context.Key<Id, S>,\n hook: Hook\n): Layer.Layer<Id, never, Id> => Layer.effect(tag)(Effect.map(tag, (service) => wrap(service, hook)))\n"]}
package/docs/README.md CHANGED
@@ -13,7 +13,9 @@ typed receipt or a typed failure, and the database arrives as a layer you
13
13
  compose. It belongs to the Smithers durable flow engine, but it runs on its
14
14
  own: no other Smithers package is required.
15
15
 
16
- Not on npm yet; see [Installation](https://github.com/smithersai/smithers/blob/main/packages/smithers/flows/flow/docs/installation.md#use-the-libraries).
16
+ ```bash
17
+ npm install @smthrs/journal@next effect
18
+ ```
17
19
 
18
20
  `effect` is a peer dependency in the range `^4.0.4`. Two copies of `effect`
19
21
  in one program are two sets of service tags, so a journal layer built against
package/docs/api.md CHANGED
@@ -236,30 +236,32 @@ That package's `Ownership` re-exports it alongside `LivenessEvidence`,
236
236
  The injectable strategy that arbitrates who holds a run. The journal owns the
237
237
  rules (one writer per run, fenced and unfenced appends, commit-time
238
238
  admission, the generation fence, steal only on staleness plus liveness
239
- evidence, and ownership transitions as events), and a strategy chooses where
239
+ evidence or on a same-host probe that proves the owner's pid gone, and
240
+ ownership transitions as events), and a strategy chooses where
240
241
  the lease lives and how the fence is checked at commit time.
241
242
 
242
- | Export | Signature |
243
- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
244
- | `Consensus` | `Context.Service<Consensus, Service>` |
245
- | `Service.claim` | `(runId, claimant: OwnerId, nowMs) => Effect<ClaimOutcome, ConsensusError>` |
246
- | `Service.activate` | `(runId, owner: OwnerId, grantedAtMs, nowMs) => Effect<ActivateOutcome, ConsensusError>` |
247
- | `Service.heartbeat` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>` |
248
- | `Service.reconfirm` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>`; renews only while the owner matches and no claim is pending |
249
- | `Service.release` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>` |
250
- | `Service.steal` | `(runId, claimant: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<ClaimOutcome, ConsensusError>` |
251
- | `Service.recover` | `(runId, staleClaimant: OwnerId, grantedAtMs, observer: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<RecoverOutcome, ConsensusError>` |
252
- | `Service.guard` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>`; fails `fence_lost` unless `owner` holds the run |
253
- | `ClaimOutcome` | `Claimed { grantedAtMs }` or `Rejected { reason }` |
254
- | `ActivateOutcome` | `Activated` or `Lost` |
255
- | `HeartbeatOutcome` | `Renewed { heartbeatAtMs }` or `Lost` |
256
- | `RecoverOutcome` | `Recovered` or `Rejected { reason }` |
257
- | `RejectionReason` | `already_claimed`, `owner_held`, `owner_live`, `evidence_invalid`, `claim_fresh`, `claim_changed`, `unavailable` |
258
- | `ConsensusError` | `{ code: "fence_lost" \| "persistence_failed", message, cause? }` |
259
- | `LivenessEvidence` | `{ expectedOwner: OwnerId, checkedAtMs, kind }` with `kind` one of `same-host-pid-dead`, `cross-host-unreachable-stale`, `lease-expired` |
260
- | `matchesEvidence`, `sameOwner` | The evidence and identity predicates every strategy applies |
261
- | `heartbeatInterval`, `heartbeatStaleAfter`, `heartbeatSkewAllowance`, `heartbeatWriteTolerance` | The lease durations every strategy judges staleness against |
262
- | `make`, `makeNoop`, `makeLocal`, `layerNoop`, `layerLocal` | Constructors and layers; `layerLocal` is the in-memory single-process strategy |
243
+ | Export | Signature |
244
+ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
245
+ | `Consensus` | `Context.Service<Consensus, Service>` |
246
+ | `Service.claim` | `(runId, claimant: OwnerId, nowMs) => Effect<ClaimOutcome, ConsensusError>` |
247
+ | `Service.activate` | `(runId, owner: OwnerId, grantedAtMs, nowMs) => Effect<ActivateOutcome, ConsensusError>` |
248
+ | `Service.heartbeat` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>` |
249
+ | `Service.reconfirm` | `(runId, owner: OwnerId, nowMs) => Effect<HeartbeatOutcome, ConsensusError>`; renews only while the owner matches and no claim is pending |
250
+ | `Service.release` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>` |
251
+ | `Service.steal` | `(runId, claimant: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<ClaimOutcome, ConsensusError>` |
252
+ | `Service.recover` | `(runId, staleClaimant: OwnerId, grantedAtMs, observer: OwnerId, nowMs, evidence: LivenessEvidence) => Effect<RecoverOutcome, ConsensusError>` |
253
+ | `Service.guard` | `(runId, owner: OwnerId) => Effect<void, ConsensusError>`; fails `fence_lost` unless `owner` holds the run |
254
+ | `ClaimOutcome` | `Claimed { grantedAtMs }` or `Rejected { reason }` |
255
+ | `ActivateOutcome` | `Activated` or `Lost` |
256
+ | `HeartbeatOutcome` | `Renewed { heartbeatAtMs }` or `Lost` |
257
+ | `RecoverOutcome` | `Recovered` or `Rejected { reason }` |
258
+ | `RejectionReason` | `already_claimed`, `owner_held`, `owner_live`, `evidence_invalid`, `claim_fresh`, `claim_changed`, `unavailable` |
259
+ | `ConsensusError` | `{ code: "fence_lost" \| "persistence_failed", message, cause? }` |
260
+ | `LivenessEvidence` | `{ expectedOwner: OwnerId, checkedAtMs, kind }` with `kind` one of `same-host-pid-dead`, `cross-host-unreachable-stale`, `lease-expired` |
261
+ | `matchesEvidence`, `sameOwner` | The evidence and identity predicates every strategy applies |
262
+ | `provesDeath` | `(evidence, claimant: OwnerId) => boolean`; `true` for `same-host-pid-dead` about a pid other than the claimant's, which `steal` admits at once |
263
+ | `heartbeatInterval`, `heartbeatStaleAfter`, `heartbeatSkewAllowance`, `heartbeatWriteTolerance` | The lease durations every strategy judges staleness against |
264
+ | `make`, `makeNoop`, `makeLocal`, `layerNoop`, `layerLocal` | Constructors and layers; `layerLocal` is the in-memory single-process strategy |
263
265
 
264
266
  The claim lifecycle is two-phase: `claim` (or `steal`, its evidence-gated
265
267
  form) reserves the run and returns the grant timestamp, `activate` presents
@@ -62,7 +62,11 @@ is why `RunStore.layerWith` takes the strategy too.
62
62
 
63
63
  The journal owns the rules: one writer per run, fenced and unfenced appends,
64
64
  commit-time admission, the generation fence, steal only on staleness plus
65
- liveness evidence, and ownership transitions as events. A strategy chooses
65
+ liveness evidence, and ownership transitions as events. One kind of evidence
66
+ needs no staleness: `same-host-pid-dead` about a pid other than the
67
+ claimant's (`Consensus.provesDeath`). The claimant found no process behind the
68
+ owner's pid on its own host, and a process that does not exist renews no lease
69
+ and writes nothing, so waiting out the lease adds no safety. A strategy chooses
66
70
  where the lease lives and how the fence is checked. The claim lifecycle is
67
71
  two-phase — `claim` or `steal` reserves the run and returns a grant
68
72
  timestamp, `activate` presents that grant to take ownership, `release` gives
@@ -31,13 +31,14 @@ not a substring test, so `tokenizer`, `secretary`, `monkey`, and
31
31
  `idempotencyKey` stay intact. Redacting them would destroy data in a permanent
32
32
  row without protecting anything, and `idempotencyKey` in particular is the
33
33
  durable identity an effect boundary replays on. Token counters are kept too: a
34
- non-negative safe integer under `inputTokens`, `outputTokens`,
35
- `cachedInputTokens`, `reasoningTokens`, or `totalTokens` is accounting, not
36
- bearer material.
34
+ non-negative safe integer under any name ending in a plural `tokens`
35
+ (`inputTokens`, `cacheWriteTokens`, `max_tokens`) or under `inputToken`,
36
+ `outputToken`, `cachedInputToken`, `reasoningToken`, or `totalToken` is
37
+ accounting, not bearer material. A bare `token` is redacted even when numeric.
37
38
 
38
39
  **Textual.** `Redaction.defaultRules` scans inside any string for credential
39
- shapes seen in real bug reports: provider keys, bearer tokens, GitHub, AWS,
40
- Slack, and Google credentials, URL passwords, Basic authorization, bare JWTs,
40
+ shapes seen in real bug reports: provider keys, bearer tokens, GitHub, GitLab, npm,
41
+ AWS, Slack (tokens and webhook URLs), and Google credentials, URL passwords, Basic authorization, bare JWTs,
41
42
  PEM private-key blocks, INI/YAML credential assignments such as
42
43
  `SECRET = value` and `password: value`, credential flags such as
43
44
  `--password value`, cookie and session assignments, and embedded JSON
@@ -63,6 +64,9 @@ and a count under a plural `tokens` name (`max_tokens: 4096`) is kept.
63
64
  A credential name that is a URL's user
64
65
  (`https://x-access-token:…@github.com/acme/app.git`) takes only the password
65
66
  before `@`, so the host and path a failed clone is diagnosed by are kept.
67
+ A URL password runs to the last `@` before the host, as a URL parser reads it,
68
+ so `redis://:pa:ss@cache` and `mysql://root:p@ss@db` lose the whole password,
69
+ and a URL with no password (`ssh://git@host`) is unchanged.
66
70
 
67
71
  In a journal row a bare value is one token, and a string or container the text
68
72
  never closes stops at the end of its line: a stray backtick in an agent's
@@ -7,7 +7,11 @@ sidebar:
7
7
 
8
8
  ## Install the package
9
9
 
10
- Not on npm yet; see [Installation](https://github.com/smithersai/smithers/blob/main/packages/smithers/flows/flow/docs/installation.md#use-the-libraries).
10
+ ```bash
11
+ npm install @smthrs/journal@next effect
12
+ ```
13
+
14
+ The `next` tag carries the 1.0 release candidates.
11
15
 
12
16
  The package requires Node.js 26.4.0 or later and ships as both ESM and
13
17
  CommonJS with TypeScript declarations. Its only runtime dependencies are
@@ -17,10 +17,13 @@ redacted.
17
17
 
18
18
  - Node.js 26.4.0 or later, where the built-in SQLite module lives.
19
19
  - An ESM package (`"type": "module"`, because the program ends in a top-level
20
- `await`) with the journal, the database it writes through, and `effect`
21
- installed. See [Installation](./installation.md) for the `effect` range.
20
+ `await`) with the journal, the database it writes through, its Node SQLite
21
+ driver, and `effect` installed. See [Installation](./installation.md) for the
22
+ `effect` range.
22
23
 
23
- Not on npm yet; see [Installation](https://github.com/smithersai/smithers/blob/main/packages/smithers/flows/flow/docs/installation.md#use-the-libraries).
24
+ ```bash
25
+ npm install @smthrs/journal@next @smthrs/database@next @effect/sql-sqlite-node effect
26
+ ```
24
27
 
25
28
  ## Compose the layer
26
29
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@smthrs/journal",
3
3
  "type": "module",
4
- "version": "1.0.0-rc.7",
4
+ "version": "1.0.0-rc.9",
5
5
  "license": "MIT",
6
6
  "smthrs": {
7
7
  "group": "engine"
@@ -226,14 +226,14 @@
226
226
  "tag": "next"
227
227
  },
228
228
  "dependencies": {
229
- "@smthrs/database": "1.0.0-rc.7"
229
+ "@smthrs/database": "1.0.0-rc.9"
230
230
  },
231
231
  "devDependencies": {
232
232
  "@effect/language-service": "0.87.2",
233
233
  "@effect/sql-sqlite-node": "4.0.4",
234
234
  "@effect/vitest": "4.0.4",
235
235
  "@eslint/js": "9.39.5",
236
- "@smthrs/flow": "1.0.0-rc.7",
236
+ "@smthrs/flow": "1.0.0-rc.9",
237
237
  "@types/node": "26.4.1",
238
238
  "@vitest/coverage-v8": "5.0.0",
239
239
  "dprint": "0.57.1",
@@ -254,7 +254,7 @@
254
254
  "effect": "^4.0.4"
255
255
  },
256
256
  "scripts": {
257
- "lint": "eslint src --max-warnings=0 && dprint check",
257
+ "lint": "eslint src examples --max-warnings=0 && dprint check",
258
258
  "format": "dprint fmt",
259
259
  "build": "node scripts/build.mjs",
260
260
  "check": "tsc -b tsconfig.json && tsc -p tsconfig.test.json --noEmit",
package/src/Consensus.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * The journal owns the consensus rules — single writer per run, fenced and
5
5
  * unfenced appends, commit-time admission, the generation fence, and steal
6
- * only on staleness plus liveness evidence — and this service is how a deployment chooses *how* those rules are
6
+ * only on staleness plus liveness evidence, or on a same-host probe that
7
+ * proves the owner's process gone — and this service is how a deployment chooses *how* those rules are
7
8
  * arbitrated: where the lease lives, how liveness is probed, and how the
8
9
  * fence is checked at commit time. `Consensus` lives here beside `OwnerId`
9
10
  * for the same reason `OwnerId` does: the journal is what it fences.
@@ -117,7 +118,8 @@ const staleAfterMs = Duration.toMillis(heartbeatStaleAfter)
117
118
  * strategy can check for itself, and `steal` checks it: the takeover refuses
118
119
  * any lease whose heartbeat is still inside the window. It is therefore
119
120
  * accepted from a claimant on any host, while the other two stay bound to the
120
- * host relation that makes them meaningful. The observation must carry the
121
+ * host relation that makes them meaningful. `same-host-pid-dead` alone also
122
+ * admits a steal inside the window; see {@link provesDeath}. The observation must carry the
121
123
  * exact instant supplied to the consuming operation: `checkedAtMs` must equal
122
124
  * that operation's `nowMs`. A caller that probes at T and calls at T+1 is
123
125
  * refused and must build fresh evidence.
@@ -182,6 +184,34 @@ export const matchesEvidence = (
182
184
  }
183
185
  }
184
186
 
187
+ /**
188
+ * Whether evidence proves the owner gone, so a steal need not wait for its
189
+ * lease to go stale.
190
+ *
191
+ * The lease stands in for a question a peer cannot ask directly: is the owner
192
+ * still running? A `same-host-pid-dead` probe asks it. The claimant read its
193
+ * own host's process table and found no process behind the owner's pid, and a
194
+ * process that does not exist renews no lease and writes nothing, so waiting
195
+ * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with
196
+ * `SIGKILL` is therefore reclaimed by the next process on the same host at
197
+ * once.
198
+ *
199
+ * The evidence must still pass {@link matchesEvidence}, which binds the kind
200
+ * to the same host. One more case is excluded here: an owner recorded with the
201
+ * claimant's own pid names the claimant's process, which is running, so a
202
+ * probe of that pid cannot report it gone. Such evidence keeps the staleness
203
+ * cutoff.
204
+ *
205
+ * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a
206
+ * judgement about a host this process cannot inspect, and `lease-expired` is
207
+ * the cutoff itself.
208
+ *
209
+ * @since 1.0.0
210
+ * @category predicates
211
+ */
212
+ export const provesDeath = (evidence: LivenessEvidence, claimant: OwnerId): boolean =>
213
+ evidence.kind === "same-host-pid-dead" && evidence.expectedOwner.pid !== claimant.pid
214
+
185
215
  /**
186
216
  * Why a strategy refused a claim, steal, or recovery.
187
217
  *
@@ -621,7 +651,9 @@ export const makeLocal: Effect.Effect<Service> = Effect.sync(() => {
621
651
  if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {
622
652
  return rejected("evidence_invalid")
623
653
  }
624
- if (lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) return rejected("owner_live")
654
+ if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {
655
+ return rejected("owner_live")
656
+ }
625
657
  lease.claim = { id: claimant, claimedAtMs: nowMs }
626
658
  return claimed(nowMs)
627
659
  })
package/src/Redaction.ts CHANGED
@@ -779,7 +779,14 @@ export const defaultRules: ReadonlyArray<Rule> = [
779
779
  // of `aaaaaaaa-` cost 11 seconds, on the path every journal write and every
780
780
  // log line takes. A scheme longer than 30 characters is not one this net is
781
781
  // for, and the cap makes each start position cost a constant.
782
- pattern: /\b([a-z][a-z0-9+.-]{0,30}:\/\/[^\s:@/]+):(?!\[REDACTED\]@)[^\s:@/]+@/gi,
782
+ //
783
+ // The username may be empty (`redis://:password@host`), and the password
784
+ // runs to the LAST `@` before the authority ends, as a URL parser reads
785
+ // it: RFC 3986 allows `:` in a password and a raw `@` is common in
786
+ // connection strings. Stopping at the first `:` or `@` left the tail of
787
+ // such a password in the row. Quotes and backslashes end the scan so a
788
+ // URL inside JSON text never swallows the next string.
789
+ pattern: /\b([a-z][a-z0-9+.-]{0,30}:\/\/[^\s:@/]*):(?!\[REDACTED\]@)[^\s/?#"'`\\]*@/gi,
783
790
  replace: "$1:[REDACTED]@"
784
791
  },
785
792
  {
@@ -836,6 +843,23 @@ export const defaultRules: ReadonlyArray<Rule> = [
836
843
  pattern: /\bAIza[0-9A-Za-z_-]{35,}(?![0-9A-Za-z_-])/g,
837
844
  replace: "[REDACTED]"
838
845
  },
846
+ {
847
+ id: "gitlab-token",
848
+ pattern: /\bglpat-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
849
+ replace: "[REDACTED]"
850
+ },
851
+ {
852
+ id: "npm-token",
853
+ pattern: /\bnpm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g,
854
+ replace: "[REDACTED]"
855
+ },
856
+ {
857
+ // The webhook path is the whole credential: anyone holding it can post
858
+ // to the channel. The host stays so a failed delivery is still readable.
859
+ id: "slack-webhook",
860
+ pattern: /(\bhooks\.slack\.com\/services\/)T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,
861
+ replace: "$1[REDACTED]"
862
+ },
839
863
  {
840
864
  id: "assignment",
841
865
  // A credential name, `:`, `=` or `=>`, and its whole value: quoted at any
@@ -1056,13 +1080,16 @@ const tokenCounterKeys: ReadonlySet<string> = new Set([
1056
1080
  ])
1057
1081
 
1058
1082
  /**
1059
- * A bare plural `tokens` is a count too: `Envelope.budget.tokens` is the run's
1060
- * token ceiling, and redacting it erased every journaled budget. A singular
1061
- * `token` stays bearer material even when it is numeric.
1083
+ * Any name ending in a plural `tokens` holds a count too, the rule the textual
1084
+ * pass applies in {@link namesCredential}: `Envelope.budget.tokens` is the
1085
+ * run's token ceiling, and `usage.cacheWriteTokens`, `maxTokens`, and
1086
+ * `contextWindowTokens` are accounting; redacting them erased every journaled
1087
+ * budget and cache-write count (#3846). A bare singular `token` stays bearer
1088
+ * material even when it is numeric.
1062
1089
  */
1063
1090
  const isTokenCount = (key: string, value: unknown): boolean =>
1064
1091
  typeof value === "number" && Number.isSafeInteger(value) && value >= 0 &&
1065
- (tokenCounterKeys.has(canonicalKey(key)) || key.toLowerCase() === "tokens")
1092
+ (tokenCounterKeys.has(canonicalKey(key)) || /tokens$/i.test(key))
1066
1093
 
1067
1094
  /**
1068
1095
  * Whether a field name names a credential.
@@ -39,6 +39,7 @@ import {
39
39
  heartbeatStaleAfter,
40
40
  type LivenessEvidence,
41
41
  matchesEvidence,
42
+ provesDeath,
42
43
  type RecoverOutcome,
43
44
  type Rejected,
44
45
  type RejectionReason,
@@ -252,7 +253,7 @@ export const make: Effect.Effect<Service, never, DurableWriter | SqlClient.SqlCl
252
253
  AND owner_host_id = ${evidence.expectedOwner.hostId}
253
254
  AND owner_pid = ${evidence.expectedOwner.pid}
254
255
  AND owner_nonce = ${evidence.expectedOwner.nonce}
255
- AND heartbeat_at_ms < ${nowMs - staleAfterMs}
256
+ AND ${provesDeath(evidence, claimant) ? sql`TRUE` : sql`heartbeat_at_ms < ${nowMs - staleAfterMs}`}
256
257
  AND claim_host_id IS NULL
257
258
  RETURNING run_id
258
259
  `
@@ -66,7 +66,7 @@ export const wrap = <S extends object>(service: S, hook: Hook): S => {
66
66
  const value = (service as Record<string, unknown>)[key]
67
67
  if (Effect.isEffect(value)) {
68
68
  wrapped[key] = hook(key, "before", []).pipe(
69
- Effect.andThen(value as Effect.Effect<unknown, unknown, unknown>),
69
+ Effect.andThen(value),
70
70
  Effect.tap(() => hook(key, "after", []))
71
71
  )
72
72
  } else if (typeof value === "function") {
@@ -75,7 +75,7 @@ export const wrap = <S extends object>(service: S, hook: Hook): S => {
75
75
  const result = method.apply(service, args)
76
76
  return Effect.isEffect(result)
77
77
  ? hook(key, "before", args).pipe(
78
- Effect.andThen(result as Effect.Effect<unknown, unknown, unknown>),
78
+ Effect.andThen(result),
79
79
  Effect.tap(() => hook(key, "after", args))
80
80
  )
81
81
  : result