@alma-harness/postgres-execution 0.6.1 → 0.8.0

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.
package/README.md CHANGED
@@ -19,6 +19,13 @@ root. SQL locks serialize ordinals; a trigger validates root admission and updat
19
19
  membership count atomically. Lost acknowledgements are resolved by scoped reads
20
20
  or equal reservation replay, never a new root execution authority.
21
21
 
22
+ A root claim INSERT uniqueness failure permits one read after rollback and connection
23
+ release. Only an exactly equal normalized binding returns `existing`, without a
24
+ fence; a closed or expired winner gains no renewed authority. Readback failures,
25
+ other SQL errors and COMMIT uncertainty remain errors. Mapped errors retain the
26
+ original PostgreSQL `cause` non-enumerably for trusted diagnostics; do not serialize
27
+ that cause into client output or routine logs (spec: operation-tree-claim-readback).
28
+
22
29
  Expired roots cannot reserve even before `reconcileExpired(scope)` marks them for
23
30
  reconciliation. The bounded sweep skips locked roots. `close` stops admission;
24
31
  it does not mean accounting or delivery completed. `listCalls` pages by ordinal,
@@ -89,6 +96,16 @@ available under reconciliation; acceptance is not batch completion, accounting o
89
96
  permission to submit again. Scoped reads never expose the original fence token.
90
97
  SQL access remains a trusted host capability, as with existing fenced stores.
91
98
 
99
+ A claim INSERT uniqueness failure is read back once after transaction cleanup,
100
+ in a fresh scoped transaction. Only an identical complete normalized manifest
101
+ returns `existing`; no fence is recovered and the INSERT is never retried.
102
+ Missing or changed bindings still conflict; unrelated errors and lost COMMIT
103
+ acknowledgements cannot enable this path (spec: batch-claim-readback).
104
+ Mapped batch conflict/state errors retain the original SQL error in non-enumerable
105
+ `cause`, including any constraint/detail supplied by PostgreSQL. These diagnostics
106
+ are for trusted inspection only: they may contain scoped identifiers. Do not
107
+ serialize causes into client responses or automatically log the entire error.
108
+
92
109
  Install the additive migration before constructing the adapter; populated replay
93
110
  is supported and old execution migrations leave the new tables intact. Input
94
111
  normalization caps manifests at 2 MiB; SQL additionally bounds JSONB text to 4 MiB
package/dist/index.d.ts CHANGED
@@ -82,7 +82,6 @@ declare class PostgresBatchSubmissionStore implements BatchSubmissionStore {
82
82
  } | {
83
83
  status: "existing";
84
84
  record: BatchSubmissionRecord;
85
- fence?: never;
86
85
  }>;
87
86
  beginDispatch(fence: BatchSubmissionFence): Promise<{
88
87
  dispatch: boolean;
@@ -170,7 +169,6 @@ declare class PostgresOperationTreeStore implements OperationTreeStore {
170
169
  } | {
171
170
  status: "existing";
172
171
  record: OperationRootRecord;
173
- fence?: never;
174
172
  }>;
175
173
  reserve(value: OperationFence, request: OperationCallInput): Promise<OperationCallRecord>;
176
174
  close(value: OperationFence): Promise<OperationRootRecord>;
package/dist/index.js CHANGED
@@ -551,9 +551,9 @@ var PostgresBatchSubmissionStore = class {
551
551
  try {
552
552
  return await inScope3(this.pool, this.#role, s, fn, this.#timeout);
553
553
  } catch (e) {
554
- const code = e.code;
555
- if (code === "23505") throw new ExecutionConflictError3();
556
- if (code === "23514" || code === "23503") throw new ExecutionStateError3();
554
+ const code = e?.code;
555
+ const mapped = code === "23505" ? new ExecutionConflictError3() : code === "23514" || code === "23503" ? new ExecutionStateError3() : void 0;
556
+ if (mapped) throw Object.defineProperty(mapped, "cause", { value: e, writable: true, configurable: true });
557
557
  throw e;
558
558
  }
559
559
  }
@@ -562,18 +562,35 @@ var PostgresBatchSubmissionStore = class {
562
562
  }
563
563
  async claim(value) {
564
564
  const input = normalizeBatchSubmission(value);
565
- return this.#scope(input.scope, async (c) => {
566
- let row = await this.#read(c, input.scope, input.key, true);
567
- if (!row) {
568
- const at2 = (await c.query("select clock_timestamp() at")).rows[0].at.toISOString();
569
- checkBatchDeadline(input, at2);
570
- row = (await c.query(`insert into alma_batch_submissions(org,uid,key,id,input,state,token,created_at,updated_at) values($1,$2,$3,$4,$5::jsonb,'prepared',$6,clock_timestamp(),clock_timestamp()) on conflict(org,uid,key) do nothing returning *`, [input.scope.org, input.scope.uid, input.key, input.id, JSON.stringify(input), crypto.randomUUID()])).rows[0];
571
- if (row) return { status: "claimed", record: record3(row), fence: { scope: { ...input.scope }, key: input.key, id: input.id, token: row.token } };
572
- row = await this.#read(c, input.scope, input.key, true);
573
- }
574
- if (!row || !equalExecution2(record3(row).input, input)) throw new ExecutionConflictError3();
575
- return { status: "existing", record: record3(row) };
576
- });
565
+ let insertConflict;
566
+ try {
567
+ return await this.#scope(input.scope, async (c) => {
568
+ let row = await this.#read(c, input.scope, input.key, true);
569
+ if (!row) {
570
+ const at2 = (await c.query("select clock_timestamp() at")).rows[0].at.toISOString();
571
+ checkBatchDeadline(input, at2);
572
+ try {
573
+ row = (await c.query(`insert into alma_batch_submissions(org,uid,key,id,input,state,token,created_at,updated_at) values($1,$2,$3,$4,$5::jsonb,'prepared',$6,clock_timestamp(),clock_timestamp()) on conflict(org,uid,key) do nothing returning *`, [input.scope.org, input.scope.uid, input.key, input.id, JSON.stringify(input), crypto.randomUUID()])).rows[0];
574
+ } catch (e) {
575
+ if (e?.code === "23505") insertConflict = e;
576
+ throw e;
577
+ }
578
+ if (row) return { status: "claimed", record: record3(row), fence: { scope: { ...input.scope }, key: input.key, id: input.id, token: row.token } };
579
+ row = await this.#read(c, input.scope, input.key, true);
580
+ }
581
+ if (!row || !equalExecution2(record3(row).input, input)) throw new ExecutionConflictError3();
582
+ return { status: "existing", record: record3(row) };
583
+ });
584
+ } catch (e) {
585
+ if (!insertConflict || !(e instanceof ExecutionConflictError3) || e.cause !== insertConflict) throw e;
586
+ return this.#scope(input.scope, async (c) => {
587
+ const row = await this.#read(c, input.scope, input.key);
588
+ if (!row) throw e;
589
+ const existing = record3(row);
590
+ if (!equalExecution2(existing.input, input)) throw e;
591
+ return { status: "existing", record: existing };
592
+ });
593
+ }
577
594
  }
578
595
  async #owner(value, fn) {
579
596
  const f = normalizeBatchFence(value);
@@ -1072,9 +1089,9 @@ var PostgresOperationTreeStore = class {
1072
1089
  try {
1073
1090
  return await inScope6(this.pool, this.#role, scope, fn, this.#timeout);
1074
1091
  } catch (e) {
1075
- const code = e.code;
1076
- if (code === "23505") throw new ExecutionConflictError6();
1077
- if (code === "23503" || code === "23514") throw new ExecutionStateError6();
1092
+ const code = e?.code;
1093
+ const mapped = code === "23505" ? new ExecutionConflictError6() : code === "23503" || code === "23514" ? new ExecutionStateError6() : void 0;
1094
+ if (mapped) throw Object.defineProperty(mapped, "cause", { value: e, writable: true, configurable: true });
1078
1095
  throw e;
1079
1096
  }
1080
1097
  }
@@ -1083,22 +1100,39 @@ var PostgresOperationTreeStore = class {
1083
1100
  }
1084
1101
  async claim(value) {
1085
1102
  const i = normalizeOperationRoot3(value);
1086
- return this.#scope(i.scope, async (c) => {
1087
- let row = await this.#read(c, i.scope, i.key, true);
1088
- if (!row) {
1089
- checkOperationDeadline2(i, await at(c));
1090
- row = (await c.query(`insert into alma_operation_roots(org,uid,key,id,session_id,policy_version,caps,max_sensitivity,deadline_at,max_calls,status,token,created_at,updated_at,request)
1103
+ let insertConflict;
1104
+ try {
1105
+ return await this.#scope(i.scope, async (c) => {
1106
+ let row = await this.#read(c, i.scope, i.key, true);
1107
+ if (!row) {
1108
+ checkOperationDeadline2(i, await at(c));
1109
+ try {
1110
+ row = (await c.query(`insert into alma_operation_roots(org,uid,key,id,session_id,policy_version,caps,max_sensitivity,deadline_at,max_calls,status,token,created_at,updated_at,request)
1091
1111
  values($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::timestamptz,$10,'active',$11,clock_timestamp(),clock_timestamp(),$12::jsonb)
1092
1112
  on conflict(org,uid,key) do nothing returning ${ROOT},token`, [i.scope.org, i.scope.uid, i.key, i.id, i.sessionId, i.policyVersion, JSON.stringify(i.caps), i.maxSensitivity, i.deadlineAt, i.maxCalls, crypto.randomUUID(), i.request ? JSON.stringify(i.request) : null])).rows[0];
1093
- if (row) {
1094
- checkOperationDeadline2(i, await at(c));
1095
- return { status: "claimed", record: record(row), fence: { scope: { ...i.scope }, key: i.key, id: i.id, token: row.token } };
1113
+ } catch (e) {
1114
+ if (e?.code === "23505") insertConflict = e;
1115
+ throw e;
1116
+ }
1117
+ if (row) {
1118
+ checkOperationDeadline2(i, await at(c));
1119
+ return { status: "claimed", record: record(row), fence: { scope: { ...i.scope }, key: i.key, id: i.id, token: row.token } };
1120
+ }
1121
+ row = await this.#read(c, i.scope, i.key, true);
1096
1122
  }
1097
- row = await this.#read(c, i.scope, i.key, true);
1098
- }
1099
- if (!row || !equalExecution4(record(row).input, i)) throw new ExecutionConflictError6();
1100
- return { status: "existing", record: record(row) };
1101
- });
1123
+ if (!row || !equalExecution4(record(row).input, i)) throw new ExecutionConflictError6();
1124
+ return { status: "existing", record: record(row) };
1125
+ });
1126
+ } catch (e) {
1127
+ if (!insertConflict || !(e instanceof ExecutionConflictError6) || e.cause !== insertConflict) throw e;
1128
+ return this.#scope(i.scope, async (c) => {
1129
+ const row = await this.#read(c, i.scope, i.key);
1130
+ if (!row) throw e;
1131
+ const existing = record(row);
1132
+ if (!equalExecution4(existing.input, i)) throw e;
1133
+ return { status: "existing", record: existing };
1134
+ });
1135
+ }
1102
1136
  }
1103
1137
  async #authorize(c, f, closing = false) {
1104
1138
  const r = await this.#read(c, f.scope, f.key, true);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/request-schema.ts","../src/rows.ts","../src/accounting.ts","../src/accounting-schema.ts","../src/session.ts","../src/session-schema.ts","../src/batch.ts","../src/batch-schema.ts","../src/batch-usage.ts","../src/batch-usage-schema.ts","../src/batch-pricing-schema.ts","../src/batch-accounting.ts","../src/batch-accounting-schema.ts"],"sourcesContent":["import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementLimit, settlementScope, type Scope } from \"@alma-harness/core\";\nimport { checkOperationCall, checkOperationDeadline, normalizeOperationCall, normalizeOperationFence, normalizeOperationRoot, operationCallQuery, type OperationCallInput, type OperationCallRecord, type OperationFence, type OperationRootInput, type OperationRootRecord, type OperationTreeStore } from \"@alma-harness/execution\";\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from \"@alma-harness/postgres\";\nimport type { Pool, PoolClient } from \"pg\";\nexport { operationTreeMigrationSql, migrateOperationTreeStore } from \"./schema\";\nimport { ROOT, record, call, type RootRow, type CallRow } from \"./rows\";\nconst at = async (c: PoolClient) => (await c.query<{ at: Date }>(\"select clock_timestamp() at\")).rows[0]!.at.toISOString();\nexport class PostgresOperationTreeStore implements OperationTreeStore {\n readonly #role: string | null; readonly #timeout: number | null;\n constructor(readonly pool: Pool, opts: ScopedStoreOptions = {}) { this.#role = resolveRlsRole(opts); this.#timeout = resolveStatementTimeout(opts); }\n async #scope<T>(scope: Scope, fn: (c: PoolClient) => Promise<T>): Promise<T> {\n try { return await inScope(this.pool, this.#role, scope, fn, this.#timeout); }\n catch (e) { const code = (e as { code?: string }).code; if (code === \"23505\") throw new ExecutionConflictError(); if (code === \"23503\" || code === \"23514\") throw new ExecutionStateError(); throw e; }\n }\n async #read(c: PoolClient, scope: Scope, key: string, lock = false): Promise<RootRow | undefined> {\n return (await c.query<RootRow>(`select ${ROOT}${lock ? \",token\" : \"\"} from alma_operation_roots where org=$1 and uid=$2 and key=$3${lock ? \" for update\" : \"\"}`, [scope.org, scope.uid, key])).rows[0];\n }\n async claim(value: OperationRootInput) {\n const i = normalizeOperationRoot(value);\n return this.#scope(i.scope, async c => {\n let row = await this.#read(c, i.scope, i.key, true);\n if (!row) {\n checkOperationDeadline(i, await at(c));\n row = (await c.query<RootRow>(`insert into alma_operation_roots(org,uid,key,id,session_id,policy_version,caps,max_sensitivity,deadline_at,max_calls,status,token,created_at,updated_at,request)\n values($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::timestamptz,$10,'active',$11,clock_timestamp(),clock_timestamp(),$12::jsonb)\n on conflict(org,uid,key) do nothing returning ${ROOT},token`, [i.scope.org, i.scope.uid, i.key, i.id, i.sessionId, i.policyVersion, JSON.stringify(i.caps), i.maxSensitivity, i.deadlineAt, i.maxCalls, crypto.randomUUID(), i.request ? JSON.stringify(i.request) : null])).rows[0];\n if (row) { checkOperationDeadline(i, await at(c)); return { status: \"claimed\" as const, record: record(row), fence: { scope: { ...i.scope }, key: i.key, id: i.id, token: row.token! } }; }\n row = await this.#read(c, i.scope, i.key, true);\n }\n if (!row || !equalExecution(record(row).input, i)) throw new ExecutionConflictError();\n return { status: \"existing\" as const, record: record(row) };\n });\n }\n async #authorize(c: PoolClient, f: OperationFence, closing = false): Promise<RootRow> {\n const r = await this.#read(c, f.scope, f.key, true);\n if (!r || r.id !== f.id || r.token !== f.token) throw new ExecutionStateError();\n if (closing && r.status === \"closed\") return r;\n if (r.status !== \"active\" || r.deadline_at.toISOString() <= await at(c)) throw new ExecutionStateError(); return r;\n }\n async reserve(value: OperationFence, request: OperationCallInput): Promise<OperationCallRecord> {\n const f = normalizeOperationFence(value), input = normalizeOperationCall(request);\n return this.#scope(f.scope, async c => {\n const r = await this.#authorize(c, f); checkOperationCall(record(r).input, input);\n const old = (await c.query<CallRow>(\"select * from alma_operation_calls where org=$1 and uid=$2 and root_id=$3 and slot=$4\", [f.scope.org, f.scope.uid, f.id, input.slot])).rows[0];\n if (old) { if (!equalExecution(call(old).input, input)) throw new ExecutionConflictError(); return call(old); }\n if (r.call_count >= r.max_calls) throw new ExecutionStateError();\n const e = input.execution;\n const row = (await c.query<CallRow>(`insert into alma_operation_calls(org,uid,root_id,slot,ordinal,kind,parent_call_id,call_id,settlement_id,operation_key,input,reserved_at)\n values($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,clock_timestamp()) returning *`, [f.scope.org, f.scope.uid, f.id, input.slot, r.call_count + 1, input.kind, input.parentCallId ?? null, e.callId, e.settlementId, e.operationKey, JSON.stringify(e)])).rows[0]!;\n return call(row);\n });\n }\n async close(value: OperationFence): Promise<OperationRootRecord> {\n const f = normalizeOperationFence(value);\n return this.#scope(f.scope, async c => {\n const row = await this.#authorize(c, f, true); if (row.status === \"closed\") return record(row);\n return record((await c.query<RootRow>(`update alma_operation_roots set status='closed',updated_at=clock_timestamp() where org=$1 and uid=$2 and key=$3 returning ${ROOT}`, [f.scope.org, f.scope.uid, f.key])).rows[0]!);\n });\n }\n async get(scope: Scope, identity: string): Promise<OperationRootRecord | null> {\n const s = settlementScope(scope), k = id(identity);\n return this.#scope(s, async c => { const row = await this.#read(c, s, k); return row ? record(row) : null; });\n }\n async listCalls(scope: Scope, identity: string, query?: { afterOrdinal?: number; limit?: number }): Promise<OperationCallRecord[]> {\n const s = settlementScope(scope), k = id(identity), q = operationCallQuery(query);\n return this.#scope(s, async c => (await c.query<CallRow>(`select c.* from alma_operation_calls c join alma_operation_roots r on (r.org,r.uid,r.id)=(c.org,c.uid,c.root_id)\n where r.org=$1 and r.uid=$2 and r.key=$3 and c.ordinal>$4 order by c.ordinal limit $5`, [s.org, s.uid, k, q.afterOrdinal, q.limit])).rows.map(call));\n }\n async reconcileExpired(scope: Scope, opts: { limit?: number } = {}): Promise<OperationRootRecord[]> {\n const s = settlementScope(scope), limit = settlementLimit(opts.limit);\n return this.#scope(s, async c => {\n const rows = (await c.query<RootRow>(`select ${ROOT} from alma_operation_roots where org=$1 and uid=$2 and status='active' and deadline_at<=clock_timestamp() order by deadline_at,key limit $3 for update skip locked`, [s.org, s.uid, limit])).rows;\n const results: OperationRootRecord[] = [];\n for (const r of rows) results.push(record((await c.query<RootRow>(`update alma_operation_roots set status='reconciliation_required',updated_at=clock_timestamp() where org=$1 and uid=$2 and key=$3 returning ${ROOT}`, [s.org, s.uid, r.key])).rows[0]!));\n return results;\n });\n }\n}\n\nexport { PostgresOperationAccountingStore } from \"./accounting\";\nexport { operationAccountingMigrationSql, migrateOperationAccountingStore } from \"./accounting-schema\";\nexport { PostgresOperationSessionStore } from \"./session\";\nexport { operationSessionMigrationSql, migrateOperationSessionStore } from \"./session-schema\";\nexport { PostgresBatchSubmissionStore } from './batch';\nexport { batchSubmissionMigrationSql, migrateBatchSubmissionStore } from './batch-schema';\nexport { PostgresBatchUsageStore } from './batch-usage';\nexport { batchUsageMigrationSql, migrateBatchUsageStore } from './batch-usage-schema';\nexport { PostgresBatchAccountingStore } from './batch-accounting';\nexport { batchAccountingMigrationSql, migrateBatchAccountingStore } from './batch-accounting-schema';\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from \"pg\";\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, executionStoreMigrationSql, rlsPolicySql } from \"@alma-harness/postgres\";\nimport { operationRequestRootSql, operationRequestShapeSql } from \"./request-schema\";\nexport function operationTreeMigrationSql(role = DEFAULT_RLS_ROLE): string {\n assertRoleIdentifier(role);\n return `${executionStoreMigrationSql(role)}${operationRequestShapeSql}\ncreate or replace function alma_operation_caps(v jsonb) returns boolean language plpgsql immutable as $caps$\ndeclare item record;\nbegin\n if jsonb_typeof(v) <> 'object' then return false; end if;\n for item in select * from jsonb_each(v) loop\n if (item.key in ('perTurnUsd','perSessionUsd','perTenantDayUsd') and jsonb_typeof(item.value)='object'\n and item.value ?& array['usd','onExceeded'] and (item.value-'usd'-'onExceeded')='{}'::jsonb\n and jsonb_typeof(item.value->'usd')='number' and item.value->'usd'>='0'::jsonb\n and item.value->>'onExceeded' in ('warn','block')) is not true then return false; end if;\n end loop; return true;\nend $caps$;\ncreate table if not exists alma_operation_roots (\n org text not null, uid text not null, key text collate \"C\" not null, id text not null,\n session_id text not null, policy_version text not null, caps jsonb not null,\n max_sensitivity text not null check(max_sensitivity in ('public','internal','personal','health')),\n deadline_at timestamptz not null, max_calls int not null check(max_calls between 1 and 512),\n status text not null check(status in ('active','closed','reconciliation_required')),\n token text not null, call_count int not null default 0 check(call_count between 0 and max_calls),\n created_at timestamptz not null, updated_at timestamptz not null,\n primary key(org,uid,key), unique(org,uid,id),\n check((${[\"org\", \"uid\", \"key\", \"id\", \"session_id\", \"policy_version\", \"token\"].map(k => `${k} ~ '^[!-~]{1,200}$'`).join(\" and \")}) is true),\n check(alma_operation_caps(caps) is true)\n);\ncreate index if not exists alma_operation_expired on alma_operation_roots(org,uid,deadline_at,key) where status='active';\ncreate table if not exists alma_operation_calls (\n org text not null, uid text not null, root_id text not null, slot text collate \"C\" not null,\n ordinal int not null check(ordinal between 1 and 512), kind text not null check(kind in ('main','direct','delegate','summary')),\n parent_call_id text, call_id text not null, settlement_id text not null, operation_key text not null,\n input jsonb not null, reserved_at timestamptz not null,\n primary key(org,uid,root_id,slot), unique(org,uid,root_id,ordinal), unique(org,uid,root_id,call_id),\n unique(org,uid,call_id), unique(org,uid,settlement_id), unique(org,uid,operation_key),\n foreign key(org,uid,root_id) references alma_operation_roots(org,uid,id),\n foreign key(org,uid,root_id,parent_call_id) references alma_operation_calls(org,uid,root_id,call_id),\n check((kind='main')=(parent_call_id is null)), check(parent_call_id is null or parent_call_id<>call_id),\n check(slot ~ '^[!-~]{1,200}$'),\n constraint alma_operation_call_shape check((alma_execution_shape_v2(jsonb_set(input,'{controls}',(input->'controls')-'temperature'),'input')\n and input ?& array['scope','operationKey','operationId','attemptId','callId','settlementId','sessionId','inputRevision','policyVersion','outputContractVersion','intent','model','requestedTier','priceVersion','prices','controls','occurredAt','deadlineAt','governance']\n and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid and input->>'callId'=call_id\n and input->>'settlementId'=settlement_id and input->>'operationKey'=operation_key) is true),\n constraint alma_operation_temperature_check check((not (input->'controls' ? 'temperature') or\n (jsonb_typeof(input->'controls'->'temperature')='number' and input->'controls'->'temperature'>='0'::jsonb and input->'controls'->'temperature'<='2'::jsonb)) is true)\n);\n-- Replace only the legacy parent-kind CHECK; old migration replay uses CREATE IF NOT EXISTS.\nalter table alma_operation_calls drop constraint if exists alma_operation_calls_check;\ndo $parent_kind$ begin\n if not exists(select from pg_constraint where conrelid='alma_operation_calls'::regclass and conname='alma_operation_parent_kind') then\n alter table alma_operation_calls add constraint alma_operation_parent_kind\n check((kind='main' and parent_call_id is null) or kind='summary' or (kind in ('direct','delegate') and parent_call_id is not null));\n end if;\nend $parent_kind$;\ncreate or replace function alma_operation_reserve() returns trigger language plpgsql as $reserve$\ndeclare r alma_operation_roots%rowtype;\nbegin\n select * into r from alma_operation_roots where org=new.org and uid=new.uid and id=new.root_id for update;\n if (r.status='active' and r.deadline_at>clock_timestamp() and new.ordinal=r.call_count+1 and new.ordinal<=r.max_calls\n and new.input->>'sessionId'=r.session_id and new.input->>'policyVersion'=r.policy_version\n and new.input->'governance'->'caps'=r.caps and (new.input->>'deadlineAt')::timestamptz<=r.deadline_at\n and array_position(array['public','internal','personal','health'],new.input->'intent'->>'sensitivity')<=array_position(array['public','internal','personal','health'],r.max_sensitivity)) is not true then\n raise exception 'Invalid operation reservation' using errcode='23514';\n end if;\n if new.parent_call_id is not null and not exists(select from alma_operation_calls where org=new.org and uid=new.uid and root_id=new.root_id and call_id=new.parent_call_id and ordinal<new.ordinal) then\n raise exception 'Invalid operation parent' using errcode='23514';\n end if;\n update alma_operation_roots set call_count=new.ordinal,updated_at=clock_timestamp() where org=new.org and uid=new.uid and id=new.root_id;\n return new;\nend $reserve$;\ndo $trigger$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_calls'::regclass and tgname='alma_operation_reserve') then\n create trigger alma_operation_reserve before insert on alma_operation_calls for each row execute function alma_operation_reserve();\n end if;\nend $trigger$;\n${rlsPolicySql(\"alma_operation_roots\")}${rlsPolicySql(\"alma_operation_calls\")}\ngrant select,insert,update on alma_operation_roots to ${role};\ngrant select,insert on alma_operation_calls to ${role};\n${operationRequestRootSql}\n${functionPathSql(\"alma_operation_reserve()\")}\n`;\n}\nexport async function migrateOperationTreeStore(pool: Pool, opts: { role?: string } = {}): Promise<void> { await pool.query(operationTreeMigrationSql(opts.role)); }\n","import { functionPathSql } from \"@alma-harness/postgres\";\n/** Versioned checks survive frozen legacy migration replay (spec: conversation-root-binding). */\nexport const operationRequestShapeSql = `\ncreate or replace function alma_operation_request_v1(v jsonb) returns boolean language plpgsql immutable as $request$\ndeclare field text;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['inputRevision','configRevision','resultContractVersion','resultRetentionMs']\n and (v-array['inputRevision','configRevision','resultContractVersion','resultRetentionMs'])='{}'::jsonb\n and jsonb_typeof(v->'resultRetentionMs')='number' and (v->>'resultRetentionMs')::numeric between 1 and 31536000000\n and trunc((v->>'resultRetentionMs')::numeric)=(v->>'resultRetentionMs')::numeric) is not true then return false; end if;\n foreach field in array array['inputRevision','configRevision','resultContractVersion'] loop\n if (jsonb_typeof(v->field)='string' and v->>field ~ '^[!-~]{1,200}$') is not true then return false; end if;\n end loop; return true;\nexception when others then return false;\nend $request$;\n`;\nexport const operationRequestRootSql = `\nalter table alma_operation_roots add column if not exists request jsonb;\ndo $request_check$ begin\n if not exists(select from pg_constraint where conrelid='alma_operation_roots'::regclass and conname='alma_operation_request_check') then\n alter table alma_operation_roots add constraint alma_operation_request_check check(request is null or alma_operation_request_v1(request) is true);\n end if;\nend $request_check$;\ncreate or replace function alma_operation_binding_immutable() returns trigger language plpgsql as $binding$\nbegin\n if (new.org,new.uid,new.key,new.id,new.session_id,new.policy_version,new.caps,new.max_sensitivity,new.deadline_at,new.max_calls,new.token,new.created_at,new.request)\n is distinct from (old.org,old.uid,old.key,old.id,old.session_id,old.policy_version,old.caps,old.max_sensitivity,old.deadline_at,old.max_calls,old.token,old.created_at,old.request) then\n raise exception 'Immutable operation binding' using errcode='23514';\n end if; return new;\nend $binding$;\ndo $binding_trigger$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_roots'::regclass and tgname='alma_operation_binding_immutable') then\n create trigger alma_operation_binding_immutable before update on alma_operation_roots for each row execute function alma_operation_binding_immutable();\n end if;\nend $binding_trigger$;\n`;\nexport const operationRequestAdmissionSql = `\ncreate or replace function alma_admission_input_v2(v jsonb) returns boolean language sql immutable as $shape$\n select (alma_admission_input(v-'request') and (not(v ? 'request') or alma_operation_request_v1(v->'request'))) is true;\n$shape$;\ndo $admission_check$ declare legacy record;\nbegin\n -- Replace only the original input-shape check, not state, fence or scope controls.\n for legacy in select conname from pg_constraint where conrelid='alma_operation_admissions'::regclass\n and contype='c' and pg_get_constraintdef(oid) like '%alma_admission_input(input)%' loop\n execute format('alter table alma_operation_admissions drop constraint %I',legacy.conname);\n end loop;\n if not exists(select from pg_constraint where conrelid='alma_operation_admissions'::regclass and conname='alma_admission_input_v2_check') then\n alter table alma_operation_admissions add constraint alma_admission_input_v2_check check((alma_admission_input_v2(input)\n and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid and input->>'key'=root_key\n and input->>'id'=root_id and input->>'sessionId'=session_id and (input->>'deadlineAt')::timestamptz=deadline_at) is true);\n end if;\nend $admission_check$;\n${functionPathSql(\"alma_admission_input_v2(jsonb)\")}\n`;\n","import { normalizeOperationRoot, normalizeOperationCall, type OperationRootRecord, type OperationCallInput, type OperationCallRecord } from \"@alma-harness/execution\";\nexport const ROOT = \"org,uid,key,id,session_id,policy_version,caps,max_sensitivity,deadline_at,max_calls,status,call_count,created_at,updated_at,request\";\nexport interface RootRow { request: unknown | null; org: string; uid: string; key: string; id: string; session_id: string; policy_version: string; caps: unknown; max_sensitivity: string; deadline_at: Date; max_calls: number; status: OperationRootRecord[\"status\"]; call_count: number; created_at: Date; updated_at: Date; token?: string }\nexport function record(r: RootRow): OperationRootRecord {\n return { input: normalizeOperationRoot({ ...(r.request === null ? {} : { request: r.request }), scope: { org: r.org, uid: r.uid }, key: r.key, id: r.id, sessionId: r.session_id, policyVersion: r.policy_version, caps: r.caps, maxSensitivity: r.max_sensitivity, deadlineAt: r.deadline_at.toISOString(), maxCalls: r.max_calls }), status: r.status, callCount: r.call_count, createdAt: r.created_at.toISOString(), updatedAt: r.updated_at.toISOString() };\n}\nexport interface CallRow { root_id: string; ordinal: number; slot: string; kind: OperationCallInput[\"kind\"]; parent_call_id: string | null; input: OperationCallInput[\"execution\"]; reserved_at: Date }\nexport function call(r: CallRow): OperationCallRecord {\n return { rootId: r.root_id, ordinal: r.ordinal, input: normalizeOperationCall({ slot: r.slot, kind: r.kind, ...(r.parent_call_id !== null ? { parentCallId: r.parent_call_id } : {}), execution: r.input }), reservedAt: r.reserved_at.toISOString() };\n}\n","import { ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementScope, type Scope } from \"@alma-harness/core\";\nimport { normalizeGovernedCostReceipt, normalizeRootCallReceipt, operationCallQuery, rootCallReceipt, rootWarnings, type GovernedCostReceipt, type OperationAccountingStore, type RootCallReceipt, type RootFinancialSummary } from \"@alma-harness/execution\";\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from \"@alma-harness/postgres\";\nimport type { Pool, PoolClient } from \"pg\";\nimport { ROOT, record, call, type RootRow, type CallRow } from \"./rows\";\ninterface FinancialRow { root_id: string; call_id: string; settlement_id: string; accounting_ordinal: number; reservation_ordinal: number; cost_usd: number; previous_usd: number; current_usd: number; decisions: unknown; new_warnings: string[]; recorded_at: Date }\nfunction receipt(r: FinancialRow): RootCallReceipt { return normalizeRootCallReceipt({ rootId: r.root_id, callId: r.call_id, settlementId: r.settlement_id, accountingOrdinal: r.accounting_ordinal, reservationOrdinal: r.reservation_ordinal, costUsd: r.cost_usd, previousUsd: r.previous_usd, currentUsd: r.current_usd, decisions: r.decisions, newWarnings: r.new_warnings, recordedAt: r.recorded_at.toISOString() }); }\nexport class PostgresOperationAccountingStore implements OperationAccountingStore {\n readonly #role: string | null; readonly #timeout: number | null;\n constructor(readonly pool: Pool, opts: ScopedStoreOptions = {}) { this.#role = resolveRlsRole(opts); this.#timeout = resolveStatementTimeout(opts); }\n async #scope<T>(scope: Scope, fn: (c: PoolClient) => Promise<T>): Promise<T> {\n try { return await inScope(this.pool, this.#role, scope, fn, this.#timeout); }\n catch (e) { if ([\"23505\", \"23503\", \"23514\"].includes((e as { code?: string }).code ?? \"\")) throw new ExecutionConflictError(); throw e; }\n }\n async #root(c: PoolClient, s: Scope, k: string, write: boolean): Promise<RootRow | undefined> {\n return (await c.query<RootRow>(`select ${ROOT} from alma_operation_roots where org=$1 and uid=$2 and key=$3 for ${write ? \"update\" : \"share\"}`, [s.org, s.uid, k])).rows[0];\n }\n async record(scope: Scope, rootKey: string, callId: string) {\n const s = settlementScope(scope), k = id(rootKey), identity = id(callId);\n return this.#scope(s, async c => {\n const root = await this.#root(c, s, k, true); if (!root) throw new ExecutionStateError();\n const args = [s.org, s.uid, root.id];\n const old = (await c.query<FinancialRow>(\"select * from alma_operation_financial_calls where org=$1 and uid=$2 and root_id=$3 and call_id=$4\", [...args, identity])).rows[0];\n if (old) return { status: \"replayed\" as const, receipt: receipt(old) };\n const row = (await c.query<CallRow>(\"select * from alma_operation_calls where org=$1 and uid=$2 and root_id=$3 and call_id=$4\", [...args, identity])).rows[0];\n if (!row) throw new ExecutionStateError(); const member = call(row);\n const cost = (await c.query<{ id: string; request: unknown; decisions: unknown; settlement_payload: unknown; settlement_session_usd: number; settlement_day_usd: number }>(`select c.id,c.settlement_payload,c.settlement_session_usd,c.settlement_day_usd,g.request,g.decisions\n from alma_audit_cost c left join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where c.org=$1 and c.uid=$2 and c.settlement_id=$3 and c.settlement_governed`, [s.org, s.uid, member.input.execution.settlementId])).rows[0];\n if (!cost) return { status: \"pending\" as const };\n const source: GovernedCostReceipt = normalizeGovernedCostReceipt({ request: cost.request, decisions: cost.decisions, receipt: { settlement: cost.settlement_payload, totals: { sessionUsd: cost.settlement_session_usd, tenantDayUsd: cost.settlement_day_usd } } });\n const last = (await c.query<FinancialRow>(\"select * from alma_operation_financial_calls where org=$1 and uid=$2 and root_id=$3 order by accounting_ordinal desc limit 1\", args)).rows[0];\n const warned = (await c.query<{ cap: RootCallReceipt[\"newWarnings\"][number] }>(\"select cap from alma_operation_warnings where org=$1 and uid=$2 and root_id=$3\", args)).rows.map(r => r.cap);\n const now = (await c.query<{ at: Date }>(\"select clock_timestamp() at\")).rows[0]!.at.toISOString();\n const value = rootCallReceipt(record(root).input, member, source, last ? receipt(last) : undefined, warned, now);\n const saved = (await c.query<FinancialRow>(`insert into alma_operation_financial_calls(org,uid,root_id,call_id,settlement_id,cost_id,accounting_ordinal,reservation_ordinal,cost_usd,previous_usd,current_usd,decisions,new_warnings,recorded_at)\n values($1,$2,$3,$4,$5,$6::uuid,$7,$8,$9,$10,$11,$12::jsonb,$13::text[],$14::timestamptz) returning *`, [...args, value.callId, value.settlementId, cost.id, value.accountingOrdinal, value.reservationOrdinal, value.costUsd, value.previousUsd, value.currentUsd, JSON.stringify(value.decisions), value.newWarnings, value.recordedAt])).rows[0]!;\n return { status: \"applied\" as const, receipt: receipt(saved) };\n });\n }\n async get(scope: Scope, rootKey: string): Promise<RootFinancialSummary | null> {\n const s = settlementScope(scope), k = id(rootKey);\n return this.#scope(s, async c => {\n const root = await this.#root(c, s, k, false); if (!root) return null;\n const args = [s.org, s.uid, root.id], last = (await c.query<FinancialRow>(\"select * from alma_operation_financial_calls where org=$1 and uid=$2 and root_id=$3 order by accounting_ordinal desc limit 1\", args)).rows[0];\n const rows = (await c.query<FinancialRow & { cap: string }>(`select f.*,w.cap from alma_operation_warnings w join alma_operation_financial_calls f on (f.org,f.uid,f.root_id,f.call_id)=(w.org,w.uid,w.root_id,w.call_id)\n where w.org=$1 and w.uid=$2 and w.root_id=$3 order by f.accounting_ordinal,w.cap`, args)).rows;\n const warnings = rows.map(r => { const found = rootWarnings(s, receipt(r)).find(w => w.cap === r.cap); if (!found) throw new ExecutionConflictError(); return found; });\n return { rootId: root.id, costUsd: last ? receipt(last).currentUsd : 0, reservedCalls: root.call_count, settledCalls: last?.accounting_ordinal ?? 0, rootStatus: root.status, warnings };\n });\n }\n async list(scope: Scope, rootKey: string, query?: { afterOrdinal?: number; limit?: number }): Promise<RootCallReceipt[]> {\n const s = settlementScope(scope), k = id(rootKey), q = operationCallQuery(query);\n return this.#scope(s, async c => (await c.query<FinancialRow>(`select f.* from alma_operation_financial_calls f join alma_operation_roots r on (r.org,r.uid,r.id)=(f.org,f.uid,f.root_id)\n where r.org=$1 and r.uid=$2 and r.key=$3 and f.accounting_ordinal>$4 order by f.accounting_ordinal limit $5`, [s.org, s.uid, k, q.afterOrdinal, q.limit])).rows.map(receipt));\n }\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from \"pg\";\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, governedCostSettlementStoreMigrationSql, rlsPolicySql } from \"@alma-harness/postgres\";\nimport { operationTreeMigrationSql } from \"./schema\";\nexport function operationAccountingMigrationSql(role = DEFAULT_RLS_ROLE): string {\n assertRoleIdentifier(role);\n return `${operationTreeMigrationSql(role)}${governedCostSettlementStoreMigrationSql(role)}\ncreate table if not exists alma_operation_financial_calls (\n org text not null, uid text not null, root_id text not null, call_id text not null, settlement_id text not null, cost_id uuid not null,\n accounting_ordinal int not null check(accounting_ordinal between 1 and 512), reservation_ordinal int not null check(reservation_ordinal between 1 and 512),\n cost_usd double precision not null, previous_usd double precision not null, current_usd double precision not null,\n decisions jsonb not null, new_warnings text[] not null, recorded_at timestamptz not null,\n primary key(org,uid,root_id,call_id), unique(org,uid,root_id,accounting_ordinal), unique(org,uid,root_id,settlement_id),\n foreign key(org,uid,root_id,call_id) references alma_operation_calls(org,uid,root_id,call_id),\n foreign key(org,uid,cost_id) references alma_audit_cost(org,uid,id),\n check(cost_usd>=0 and cost_usd<'Infinity'::float8 and previous_usd>=0 and previous_usd<'Infinity'::float8 and current_usd=previous_usd+cost_usd and current_usd<'Infinity'::float8),\n check(jsonb_typeof(decisions)='array' and jsonb_array_length(decisions)<=3),\n check(cardinality(new_warnings)<=3 and new_warnings<@array['perTurnUsd','perSessionUsd','perTenantDayUsd']::text[])\n);\ncreate table if not exists alma_operation_warnings (\n org text not null, uid text not null, root_id text not null, cap text not null check(cap in ('perTurnUsd','perSessionUsd','perTenantDayUsd')), call_id text not null,\n primary key(org,uid,root_id,cap), foreign key(org,uid,root_id,call_id) references alma_operation_financial_calls(org,uid,root_id,call_id)\n);\ncreate or replace function alma_operation_financial_validate() returns trigger language plpgsql as $financial$\ndeclare root alma_operation_roots%rowtype; member alma_operation_calls%rowtype; previous alma_operation_financial_calls%rowtype;\n source record; expected jsonb; warnings text[]; field text;\nbegin\n select * into root from alma_operation_roots where org=new.org and uid=new.uid and id=new.root_id for update;\n select * into member from alma_operation_calls where org=new.org and uid=new.uid and root_id=new.root_id and call_id=new.call_id;\n select * into previous from alma_operation_financial_calls where org=new.org and uid=new.uid and root_id=new.root_id order by accounting_ordinal desc limit 1;\n select c.settlement_payload payload,g.request,g.decisions into source from alma_audit_cost c join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where c.org=new.org and c.uid=new.uid and c.id=new.cost_id and c.settlement_governed;\n if (root.id is not null and member.call_id is not null and source.payload is not null\n and new.reservation_ordinal=member.ordinal and new.accounting_ordinal=coalesce(previous.accounting_ordinal,0)+1\n and new.previous_usd=coalesce(previous.current_usd,0) and new.cost_usd=(source.payload->>'costUsd')::float8\n and source.payload->>'callId'=new.call_id and source.payload->>'id'=new.settlement_id\n and source.payload->>'id'=member.input->>'settlementId' and source.payload->'scope'=member.input->'scope'\n and source.payload->'model'=member.input->'model' and source.payload->>'at'=member.input->>'occurredAt'\n and source.payload->'consumers'=member.input->'governance'->'consumers' and source.request->>'policyVersion'=root.policy_version and source.request->'caps'=root.caps\n and (not(source.payload ? 'parentCallId') or source.payload->>'parentCallId'=member.parent_call_id)) is not true then\n raise exception 'Invalid root financial association' using errcode='23514';\n end if;\n foreach field in array array['sessionId','operationId','attemptId','priceVersion'] loop\n if (source.payload->>field=member.input->>field) is not true then raise exception 'Invalid root financial binding' using errcode='23514'; end if;\n end loop;\n select coalesce(jsonb_agg(case when d->>'cap'='perTurnUsd' then d || jsonb_build_object('previousUsd',new.previous_usd,'currentUsd',new.current_usd,'exceeded',new.current_usd>(d->>'thresholdUsd')::float8) else d end order by n),'[]'::jsonb)\n into expected from jsonb_array_elements(source.decisions) with ordinality as x(d,n);\n if new.decisions<>expected then raise exception 'Invalid root financial decisions' using errcode='23514'; end if;\n select coalesce(array_agg(d->>'cap' order by n),array[]::text[]) into warnings from jsonb_array_elements(expected) with ordinality as x(d,n)\n where d->>'onExceeded'='warn' and (d->>'exceeded')::boolean and not exists(select from alma_operation_warnings w where w.org=new.org and w.uid=new.uid and w.root_id=new.root_id and w.cap=d->>'cap');\n if new.new_warnings<>warnings then raise exception 'Invalid root financial warnings' using errcode='23514'; end if;\n return new;\nend $financial$;\ncreate or replace function alma_operation_financial_warn() returns trigger language plpgsql as $warnings$\ndeclare cap text;\nbegin\n foreach cap in array new.new_warnings loop insert into alma_operation_warnings(org,uid,root_id,cap,call_id) values(new.org,new.uid,new.root_id,cap,new.call_id); end loop;\n return new;\nend $warnings$;\ncreate or replace function alma_operation_warning_validate() returns trigger language plpgsql as $validate$\nbegin\n if not exists(select from alma_operation_financial_calls f where f.org=new.org and f.uid=new.uid and f.root_id=new.root_id and f.call_id=new.call_id and new.cap=any(f.new_warnings)) then\n raise exception 'Invalid root warning association' using errcode='23514';\n end if; return new;\nend $validate$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_financial_calls'::regclass and tgname='alma_operation_financial_validate') then\n create trigger alma_operation_financial_validate before insert on alma_operation_financial_calls for each row execute function alma_operation_financial_validate();\n create trigger alma_operation_financial_warn after insert on alma_operation_financial_calls for each row execute function alma_operation_financial_warn();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_operation_warnings'::regclass and tgname='alma_operation_warning_validate') then\n create trigger alma_operation_warning_validate before insert on alma_operation_warnings for each row execute function alma_operation_warning_validate();\n end if;\nend $triggers$;\n${rlsPolicySql(\"alma_operation_financial_calls\")}${rlsPolicySql(\"alma_operation_warnings\")}\ngrant select,insert on alma_operation_financial_calls,alma_operation_warnings to ${role};\n${functionPathSql(\"alma_operation_financial_validate()\",\"alma_operation_financial_warn()\",\"alma_operation_warning_validate()\")}\n`;\n}\nexport async function migrateOperationAccountingStore(pool: Pool, opts: { role?: string } = {}): Promise<void> { await pool.query(operationAccountingMigrationSql(opts.role)); }\n","import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementLimit, settlementScope, type Scope } from \"@alma-harness/core\";\nimport { checkOperationDeadline, normalizeOperationRoot, normalizeOperationSessionFence, operationCallQuery, type OperationRootInput, type OperationSessionClaim, type OperationSessionFence, type OperationSessionRecord, type OperationSessionStore } from \"@alma-harness/execution\";\nimport { assertRoleIdentifier, DEFAULT_RETENTION_ROLE, inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from \"@alma-harness/postgres\";\nimport type { Pool, PoolClient } from \"pg\";\ninterface Row { input: OperationRootInput; token: string; ordinal: string; status: OperationSessionRecord[\"status\"]; created_at: Date; updated_at: Date; resolution_id: string | null }\nconst record = (r: Row): OperationSessionRecord => ({ input: normalizeOperationRoot(r.input), ordinal: Number(r.ordinal), status: r.status, createdAt: r.created_at.toISOString(), updatedAt: r.updated_at.toISOString(), ...(r.resolution_id === null ? {} : { resolutionId: r.resolution_id }) });\nexport class PostgresOperationSessionStore implements OperationSessionStore {\n readonly #role: string | null; readonly #operator: string; readonly #timeout: number | null;\n constructor(readonly pool: Pool, opts: ScopedStoreOptions & { operatorRole?: string } = {}) {\n this.#role = resolveRlsRole(opts); this.#timeout = resolveStatementTimeout(opts);\n this.#operator = opts.operatorRole ?? DEFAULT_RETENTION_ROLE; assertRoleIdentifier(this.#operator);\n if (this.#role === this.#operator) throw new TypeError(\"Admission operator must have a separate role\");\n }\n async #scope<T>(s: Scope, fn: (c: PoolClient) => Promise<T>, operator = false): Promise<T> {\n try { return await inScope(this.pool, operator ? this.#operator : this.#role, s, fn, this.#timeout); }\n catch (e) { const code = (e as { code?: string }).code; if (code === \"23505\") throw new ExecutionConflictError(); if (code === \"23514\" || code === \"23503\") throw new ExecutionStateError(); throw e; }\n }\n async #read(c: PoolClient, s: Scope, k: string, lock = false): Promise<Row | undefined> {\n return (await c.query<Row>(`select * from alma_operation_admissions where org=$1 and uid=$2 and root_key=$3${lock ? \" for update\" : \"\"}`, [s.org, s.uid, k])).rows[0];\n }\n async #lock(c: PoolClient, s: Scope, sessionId: string) {\n await c.query(\"select session_id from alma_operation_sessions where org=$1 and uid=$2 and session_id=$3 for update\", [s.org, s.uid, sessionId]);\n }\n async claim(value: OperationRootInput): Promise<OperationSessionClaim> {\n const i = normalizeOperationRoot(value);\n return this.#scope(i.scope, async c => {\n await c.query(\"insert into alma_operation_sessions(org,uid,session_id) values($1,$2,$3) on conflict do nothing\", [i.scope.org, i.scope.uid, i.sessionId]);\n await this.#lock(c, i.scope, i.sessionId);\n const old = await this.#read(c, i.scope, i.key);\n if (old) { if (!equalExecution(old.input, i)) throw new ExecutionConflictError(); return { status: \"existing\", record: record(old) }; }\n if ((await c.query(\"select 1 from alma_operation_admissions where org=$1 and uid=$2 and root_id=$3\", [i.scope.org, i.scope.uid, i.id])).rowCount) throw new ExecutionConflictError();\n const occupied = (await c.query<Row>(\"select * from alma_operation_admissions where org=$1 and uid=$2 and session_id=$3 and status<>'released'\", [i.scope.org, i.scope.uid, i.sessionId])).rows[0];\n if (occupied) return { status: \"busy\", rootKey: occupied.input.key, rootId: occupied.input.id };\n const at = (await c.query<{ at: Date }>(\"select clock_timestamp() at\")).rows[0]!.at.toISOString(); checkOperationDeadline(i, at);\n const token = crypto.randomUUID();\n const row = (await c.query<Row>(`insert into alma_operation_admissions(org,uid,root_key,root_id,session_id,input,deadline_at,token,ordinal,status,created_at,updated_at)\n values($1,$2,$3,$4,$5,$6::jsonb,$7,$8,(select coalesce(max(ordinal),0)+1 from alma_operation_admissions where org=$1 and uid=$2 and session_id=$5),'active',clock_timestamp(),clock_timestamp()) returning *`,\n [i.scope.org, i.scope.uid, i.key, i.id, i.sessionId, JSON.stringify(i), i.deadlineAt, token])).rows[0]!;\n return { status: \"claimed\", record: record(row), fence: { scope: { ...i.scope }, sessionId: i.sessionId, rootKey: i.key, token } };\n });\n }\n async get(scope: Scope, rootKey: string) {\n const s = settlementScope(scope), k = id(rootKey);\n return this.#scope(s, async c => { const r = await this.#read(c, s, k); return r ? record(r) : null; });\n }\n async list(scope: Scope, sessionId: string, query?: { afterOrdinal?: number; limit?: number }) {\n const s = settlementScope(scope), session = id(sessionId), q = operationCallQuery(query);\n return this.#scope(s, async c => (await c.query<Row>(\"select * from alma_operation_admissions where org=$1 and uid=$2 and session_id=$3 and ordinal>$4 order by ordinal limit $5\", [s.org, s.uid, session, q.afterOrdinal, q.limit])).rows.map(record));\n }\n async #owner(value: OperationSessionFence, finish: boolean): Promise<OperationSessionRecord> {\n const f = normalizeOperationSessionFence(value);\n return this.#scope(f.scope, async c => {\n await this.#lock(c, f.scope, f.sessionId);\n const r = await this.#read(c, f.scope, f.rootKey, true);\n if (!r || r.token !== f.token || r.input.sessionId !== f.sessionId) throw new ExecutionStateError();\n if (finish) {\n if (r.status === \"released\" && r.resolution_id === null) return record(r);\n if (r.status !== \"active\") throw new ExecutionStateError();\n } else if (r.status !== \"active\") return record(r);\n await c.query(\"select set_config('alma.operation_admission_token',$1,true)\", [f.token]);\n return record((await c.query<Row>(\"update alma_operation_admissions set status=$4 where org=$1 and uid=$2 and root_key=$3 returning *\", [f.scope.org, f.scope.uid, f.rootKey, finish ? \"released\" : \"reconciliation_required\"])).rows[0]!);\n });\n }\n finish(fence: OperationSessionFence) { return this.#owner(fence, true); }\n markUncertain(fence: OperationSessionFence) { return this.#owner(fence, false); }\n async reconcileExpired(scope: Scope, opts: { limit?: number } = {}) {\n const s = settlementScope(scope), limit = settlementLimit(opts.limit);\n return this.#scope(s, async c => {\n const sessions = (await c.query<{ session_id: string }>(`select session_id from alma_operation_sessions s where org=$1 and uid=$2\n and exists(select from alma_operation_admissions a where (a.org,a.uid,a.session_id)=(s.org,s.uid,s.session_id) and status='active' and deadline_at<=clock_timestamp())\n order by session_id limit $3 for update of s skip locked`, [s.org, s.uid, limit])).rows;\n const records: OperationSessionRecord[] = [];\n for (const row of sessions) records.push(...(await c.query<Row>(\"update alma_operation_admissions set status='reconciliation_required' where org=$1 and uid=$2 and session_id=$3 and status='active' and deadline_at<=clock_timestamp() returning *\", [s.org, s.uid, row.session_id])).rows.map(record));\n return records;\n });\n }\n async resolve(scope: Scope, rootKey: string, opts: { resolutionId: string }) {\n const s = settlementScope(scope), k = id(rootKey), resolutionId = id(opts.resolutionId);\n return this.#scope(s, async c => {\n const meta = await this.#read(c, s, k); if (!meta) throw new ExecutionStateError();\n await this.#lock(c, s, meta.input.sessionId); const r = (await this.#read(c, s, k, true))!;\n if (r.status === \"released\") { if (r.resolution_id !== resolutionId) throw new ExecutionConflictError(); return record(r); }\n if (r.status !== \"reconciliation_required\") throw new ExecutionStateError();\n return record((await c.query<Row>(\"update alma_operation_admissions set status='released',resolution_id=$4 where org=$1 and uid=$2 and root_key=$3 returning *\", [s.org, s.uid, k, resolutionId])).rows[0]!);\n }, true);\n }\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from \"pg\";\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, DEFAULT_RETENTION_ROLE, rlsPolicySql, roleBootstrapSql } from \"@alma-harness/postgres\";\nimport { operationTreeMigrationSql } from \"./schema\";\nimport { operationRequestAdmissionSql } from \"./request-schema\";\nexport function operationSessionMigrationSql(role = DEFAULT_RLS_ROLE, operatorRole = DEFAULT_RETENTION_ROLE): string {\n assertRoleIdentifier(role); assertRoleIdentifier(operatorRole);\n if (role === operatorRole) throw new TypeError(\"Admission operator must have a separate role\");\n return `${operationTreeMigrationSql(role)}${roleBootstrapSql(operatorRole)}\ncreate table if not exists alma_operation_sessions (\n org text not null, uid text not null, session_id text not null,\n primary key(org,uid,session_id),\n check(org ~ '^[!-~]{1,200}$' and uid ~ '^[!-~]{1,200}$' and session_id ~ '^[!-~]{1,200}$')\n);\ncreate or replace function alma_admission_input(v jsonb) returns boolean language plpgsql immutable as $shape$\ndeclare item record;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['scope','key','id','sessionId','policyVersion','caps','maxSensitivity','deadlineAt','maxCalls']\n and (v-array['scope','key','id','sessionId','policyVersion','caps','maxSensitivity','deadlineAt','maxCalls'])='{}'::jsonb\n and jsonb_typeof(v->'scope')='object' and ((v->'scope')-'org'-'uid')='{}'::jsonb\n and jsonb_typeof(v->'maxCalls')='number' and (v->>'maxCalls')::numeric between 1 and 512\n and trunc((v->>'maxCalls')::numeric)=(v->>'maxCalls')::numeric\n and v->>'maxSensitivity' in ('public','internal','personal','health')\n and jsonb_typeof(v->'deadlineAt')='string' and v->>'deadlineAt' ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{3}Z$'\n and isfinite((v->>'deadlineAt')::timestamptz) and alma_operation_caps(v->'caps')) is not true then return false; end if;\n for item in select value from jsonb_each(v->'scope') union all select value from jsonb_each(v) where key in ('key','id','sessionId','policyVersion') loop\n if (jsonb_typeof(item.value)='string' and (item.value#>>'{}') ~ '^[!-~]{1,200}$') is not true then return false; end if;\n end loop;\n if not (v->'scope' ?& array['org','uid']) then return false; end if;\n for item in select value from jsonb_each(v->'caps') loop\n if (item.value->>'usd')::numeric > 1.7976931348623157e308 then return false; end if;\n end loop;\n return true;\nexception when others then return false;\nend $shape$;\ncreate table if not exists alma_operation_admissions (\n org text not null, uid text not null, root_key text not null, root_id text not null,\n session_id text not null, input jsonb not null, deadline_at timestamptz not null,\n token text not null check(token ~ '^[!-~]{1,200}$'),\n ordinal bigint not null check(ordinal between 1 and 9007199254740991),\n status text not null check(status in ('active','reconciliation_required','released')),\n created_at timestamptz not null, updated_at timestamptz not null,\n resolution_id text check(resolution_id ~ '^[!-~]{1,200}$'),\n primary key(org,uid,root_key), unique(org,uid,root_id), unique(org,uid,session_id,ordinal),\n foreign key(org,uid,session_id) references alma_operation_sessions(org,uid,session_id),\n check((alma_admission_input(input) and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid\n and input->>'key'=root_key and input->>'id'=root_id and input->>'sessionId'=session_id\n and (input->>'deadlineAt')::timestamptz=deadline_at) is true),\n check(resolution_id is null or status='released')\n);\ncreate unique index if not exists alma_admission_occupancy on alma_operation_admissions(org,uid,session_id) where status<>'released';\ncreate or replace function alma_session_lock_immutable() returns trigger language plpgsql as $lock$\nbegin\n if new is distinct from old then raise exception 'Immutable session identity' using errcode='23514'; end if;\n return new;\nend $lock$;\ncreate or replace function alma_admission_transition() returns trigger language plpgsql as $transition$\ndeclare owner boolean; expected bigint;\nbegin\n perform from alma_operation_sessions where org=new.org and uid=new.uid and session_id=new.session_id for update;\n if tg_op='INSERT' then\n select coalesce(max(ordinal),0)+1 into expected from alma_operation_admissions where org=new.org and uid=new.uid and session_id=new.session_id;\n if (new.status='active' and new.resolution_id is null and new.ordinal=expected\n and new.deadline_at>clock_timestamp() and new.deadline_at<=clock_timestamp()+interval '1 hour') is not true then\n raise exception 'Invalid admission' using errcode='23514';\n end if;\n new.created_at=clock_timestamp(); new.updated_at=new.created_at; return new;\n end if;\n if (new.org,new.uid,new.root_key,new.root_id,new.session_id,new.input,new.deadline_at,new.token,new.ordinal,new.created_at)\n is distinct from (old.org,old.uid,old.root_key,old.root_id,old.session_id,old.input,old.deadline_at,old.token,old.ordinal,old.created_at) then\n raise exception 'Immutable admission binding' using errcode='23514';\n end if;\n owner=coalesce(current_setting('alma.operation_admission_token',true)=old.token,false);\n if not (\n (old.status='active' and new.status='released' and new.resolution_id is null and owner and old.deadline_at>clock_timestamp())\n or (old.status='active' and new.status='reconciliation_required' and new.resolution_id is null and (owner or old.deadline_at<=clock_timestamp()))\n or (old.status='reconciliation_required' and new.status='released' and new.resolution_id is not null and pg_has_role(current_user,'${operatorRole}','MEMBER'))\n ) then raise exception 'Invalid admission transition' using errcode='23514'; end if;\n new.updated_at=clock_timestamp(); return new;\nend $transition$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_sessions'::regclass and tgname='alma_session_lock_immutable') then\n create trigger alma_session_lock_immutable before update on alma_operation_sessions for each row execute function alma_session_lock_immutable();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_operation_admissions'::regclass and tgname='alma_admission_transition') then\n create trigger alma_admission_transition before insert or update on alma_operation_admissions for each row execute function alma_admission_transition();\n end if;\nend $triggers$;\n${rlsPolicySql(\"alma_operation_sessions\")}${rlsPolicySql(\"alma_operation_admissions\")}\ngrant select,insert,update on alma_operation_sessions to ${role};\ngrant select,update on alma_operation_sessions to ${operatorRole};\ngrant select,insert,update on alma_operation_admissions to ${role};\ngrant select,update on alma_operation_admissions to ${operatorRole};\n${operationRequestAdmissionSql}\n${functionPathSql(\"alma_admission_input(jsonb)\",\"alma_admission_transition()\")}\n`;\n}\nexport async function migrateOperationSessionStore(pool: Pool, opts: { role?: string; operatorRole?: string } = {}): Promise<void> {\n await pool.query(operationSessionMigrationSql(opts.role, opts.operatorRole));\n}\n","import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementScope, type JobHandle, type Scope } from '@alma-harness/core';\nimport { batchQuery, normalizeBatchSummary, bindBatchHandle, checkBatchDeadline, normalizeBatchFence, normalizeBatchHandle, normalizeBatchRecord, normalizeBatchSubmission, type BatchSubmissionFence, type BatchSubmissionInput, type BatchSubmissionRecord, type BatchSubmissionStore } from '@alma-harness/execution';\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from '@alma-harness/postgres';\nimport type { Pool,PoolClient } from 'pg';\ninterface Row {input:BatchSubmissionInput;state:BatchSubmissionRecord['state'];token:string;created_at:Date;updated_at:Date;dispatched_at:Date|null;accepted_at:Date|null;handle:JobHandle|null}\nconst record=(r:Row)=>normalizeBatchRecord({input:r.input,state:r.state,createdAt:r.created_at.toISOString(),updatedAt:r.updated_at.toISOString(),...(r.dispatched_at?{dispatchedAt:r.dispatched_at.toISOString()}:{}),...(r.accepted_at?{acceptedAt:r.accepted_at.toISOString(),handle:r.handle}:{})});\nexport class PostgresBatchSubmissionStore implements BatchSubmissionStore {\n readonly #role:string|null;readonly #timeout:number|null;\n constructor(readonly pool:Pool,opts:ScopedStoreOptions={}){this.#role=resolveRlsRole(opts);this.#timeout=resolveStatementTimeout(opts);}\n async #scope<T>(s:Scope,fn:(c:PoolClient)=>Promise<T>):Promise<T>{try{return await inScope(this.pool,this.#role,s,fn,this.#timeout);}catch(e){const code=(e as {code?:string}).code;if(code==='23505')throw new ExecutionConflictError();if(code==='23514'||code==='23503')throw new ExecutionStateError();throw e;}}\n async #read(c:PoolClient,s:Scope,k:string,lock=false){return (await c.query<Row>(`select * from alma_batch_submissions where org=$1 and uid=$2 and key=$3${lock?' for update':''}`,[s.org,s.uid,k])).rows[0];}\n async claim(value:BatchSubmissionInput){const input=normalizeBatchSubmission(value);return this.#scope(input.scope,async c=>{\n let row=await this.#read(c,input.scope,input.key,true);\n if(!row){const at=(await c.query<{at:Date}>('select clock_timestamp() at')).rows[0]!.at.toISOString();checkBatchDeadline(input,at);\n row=(await c.query<Row>(`insert into alma_batch_submissions(org,uid,key,id,input,state,token,created_at,updated_at) values($1,$2,$3,$4,$5::jsonb,'prepared',$6,clock_timestamp(),clock_timestamp()) on conflict(org,uid,key) do nothing returning *`,[input.scope.org,input.scope.uid,input.key,input.id,JSON.stringify(input),crypto.randomUUID()])).rows[0];\n if(row)return {status:'claimed' as const,record:record(row),fence:{scope:{...input.scope},key:input.key,id:input.id,token:row.token}};\n row=await this.#read(c,input.scope,input.key,true);\n }\n if(!row||!equalExecution(record(row).input,input))throw new ExecutionConflictError();return {status:'existing' as const,record:record(row)};\n });}\n async #owner<T>(value:BatchSubmissionFence,fn:(c:PoolClient,r:Row,f:BatchSubmissionFence)=>Promise<T>){const f=normalizeBatchFence(value);return this.#scope(f.scope,async c=>{const r=await this.#read(c,f.scope,f.key,true);if(!r||r.token!==f.token||r.input.id!==f.id)throw new ExecutionStateError();await c.query(\"select set_config('alma.batch_token',$1,true)\",[f.token]);return fn(c,r,f);});}\n async beginDispatch(fence:BatchSubmissionFence){return this.#owner(fence,async(c,r,f)=>{\n if(r.state!=='prepared')return {dispatch:false,record:record(r)};\n const row=(await c.query<Row>(\"update alma_batch_submissions set state='dispatching' where org=$1 and uid=$2 and key=$3 returning *\",[f.scope.org,f.scope.uid,f.key])).rows[0]!;\n return {dispatch:true,record:record(row)};\n });}\n async accept(value:BatchSubmissionFence,raw:JobHandle){const f=normalizeBatchFence(value),handle=normalizeBatchHandle(raw);return this.#owner(f,async(c,r)=>{\n bindBatchHandle(record(r).input,handle);if(r.handle){if(!equalExecution(r.handle,handle))throw new ExecutionConflictError();return record(r);}if(!r.dispatched_at)throw new ExecutionStateError();\n return record((await c.query<Row>(`update alma_batch_submissions set handle=$4::jsonb,state=case when state='dispatching' and (input->>'submitDeadlineAt')::timestamptz>clock_timestamp() then 'submitted' else 'reconciliation_required' end where org=$1 and uid=$2 and key=$3 returning *`,[f.scope.org,f.scope.uid,f.key,JSON.stringify(handle)])).rows[0]!);\n });}\n async markUncertain(fence:BatchSubmissionFence){return this.#owner(fence,async(c,r,f)=>r.state==='reconciliation_required'?record(r):record((await c.query<Row>(\"update alma_batch_submissions set state='reconciliation_required' where org=$1 and uid=$2 and key=$3 returning *\",[f.scope.org,f.scope.uid,f.key])).rows[0]!));}\n async get(scope:Scope,identity:string){const s=settlementScope(scope),k=id(identity);return this.#scope(s,async c=>{const r=await this.#read(c,s,k);return r?record(r):null;});}\n async list(scope:Scope,query?:{afterKey?:string;limit?:number}){const s=settlementScope(scope),q=batchQuery(query);return this.#scope(s,async c=>(await c.query<Omit<Row,'input'|'token'>&{key:string;id:string;session_id:string;deadline:string;item_count:number}>(`select key,id,input->>'sessionId' session_id,input->>'submitDeadlineAt' deadline,jsonb_array_length(input->'items') item_count,state,created_at,updated_at,dispatched_at,accepted_at,handle from alma_batch_submissions where org=$1 and uid=$2 and ($3::text is null or key>$3 collate \"C\") order by key limit $4`,[s.org,s.uid,q.afterKey??null,q.limit])).rows.map(r=>normalizeBatchSummary({key:r.key,id:r.id,sessionId:r.session_id,submitDeadlineAt:r.deadline,itemCount:r.item_count,state:r.state,createdAt:r.created_at.toISOString(),updatedAt:r.updated_at.toISOString(),...(r.dispatched_at?{dispatchedAt:r.dispatched_at.toISOString()}:{}),...(r.accepted_at?{acceptedAt:r.accepted_at.toISOString(),handle:r.handle}:{})})));}\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from 'pg';\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, executionStoreMigrationSql, rlsPolicySql } from '@alma-harness/postgres';\nexport function batchSubmissionMigrationSql(role=DEFAULT_RLS_ROLE):string {\n assertRoleIdentifier(role);\n return `${executionStoreMigrationSql(role)}\ncreate or replace function alma_batch_input_v1(v jsonb) returns boolean language plpgsql immutable as $shape$\ndeclare item jsonb; e jsonb; first jsonb; field text;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['scope','key','id','sessionId','configRevision','submitDeadlineAt','items']\n and (v-array['scope','key','id','sessionId','configRevision','submitDeadlineAt','items'])='{}'::jsonb\n and jsonb_typeof(v->'scope')='object' and v->'scope' ?& array['org','uid'] and ((v->'scope')-'org'-'uid')='{}'::jsonb\n and jsonb_typeof(v->'items')='array' and jsonb_array_length(v->'items') between 1 and 512\n and octet_length(v::text)<=4194304) is not true then return false; end if;\n foreach field in array array['key','id','sessionId','configRevision'] loop\n if (jsonb_typeof(v->field)='string' and v->>field ~ '^[!-~]{1,200}$') is not true then return false; end if;\n end loop;\n first=v->'items'->0->'execution';\n for item in select value from jsonb_array_elements(v->'items') loop\n e=item->'execution';\n if (jsonb_typeof(item)='object' and item ?& array['id','execution'] and (item-'id'-'execution')='{}'::jsonb\n and jsonb_typeof(item->'id')='string' and item->>'id' ~ '^[!-~]{1,200}$'\n and alma_execution_shape_v2(jsonb_set(e,'{controls}',(e->'controls')-'temperature'),'input')\n and e ?& array['scope','operationKey','operationId','attemptId','callId','settlementId','sessionId','inputRevision','policyVersion','outputContractVersion','intent','model','requestedTier','priceVersion','prices','controls','occurredAt','deadlineAt','governance']\n and (not(e->'controls' ? 'temperature') or (jsonb_typeof(e->'controls'->'temperature')='number' and (e->'controls'->>'temperature')::numeric between 0 and 2))\n and e->'scope'=v->'scope' and e->>'sessionId'=v->>'sessionId' and e->>'requestedTier'='batch'\n and e->>'deadlineAt'=v->>'submitDeadlineAt' and e->'model'=first->'model'\n and e->>'policyVersion'=first->>'policyVersion' and e->'governance'->'caps'=first->'governance'->'caps') is not true then return false; end if;\n end loop; return true;\nexception when others then return false;\nend $shape$;\ncreate table if not exists alma_batch_submissions (\n org text not null,uid text not null,key text collate \"C\" not null,id text not null,input jsonb not null,\n state text not null check(state in ('prepared','dispatching','submitted','reconciliation_required')),\n token text not null check(token ~ '^[!-~]{1,200}$'),created_at timestamptz not null,updated_at timestamptz not null,\n dispatched_at timestamptz,accepted_at timestamptz,handle jsonb,\n primary key(org,uid,key),unique(org,uid,id),\n check((alma_batch_input_v1(input) and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid and input->>'key'=key and input->>'id'=id) is true),\n check((handle is null)=(accepted_at is null)),\n check(handle is null or (jsonb_typeof(handle)='object' and handle ?& array['provider','id','model'] and (handle-'provider'-'id'-'model')='{}'::jsonb\n and jsonb_typeof(handle->'id')='string' and handle->>'id' ~ '^[!-~]{1,200}$'\n and handle->'model'=input->'items'->0->'execution'->'model' and handle->>'provider'=handle->'model'->>'provider') is true),\n check(state<>'prepared' or (dispatched_at is null and handle is null)),\n check(state<>'dispatching' or (dispatched_at is not null and handle is null)),\n check(state<>'submitted' or (handle is not null and accepted_at<(input->>'submitDeadlineAt')::timestamptz)),\n check(accepted_at is null or (dispatched_at is not null and accepted_at>=dispatched_at)),\n check(dispatched_at is null or (dispatched_at>=created_at and dispatched_at<(input->>'submitDeadlineAt')::timestamptz)),\n check(updated_at>=created_at and (accepted_at is null or updated_at>=accepted_at) and (dispatched_at is null or updated_at>=dispatched_at))\n);\ncreate table if not exists alma_batch_items (\n org text not null,uid text not null,batch_key text not null,ordinal int not null check(ordinal between 1 and 512),\n item_id text not null,operation_key text not null,operation_id text not null,call_id text not null,settlement_id text not null,\n primary key(org,uid,batch_key,ordinal),unique(org,uid,batch_key,item_id),\n unique(org,uid,operation_key),unique(org,uid,operation_id),unique(org,uid,call_id),unique(org,uid,settlement_id),\n foreign key(org,uid,batch_key) references alma_batch_submissions(org,uid,key)\n);\ncreate or replace function alma_batch_transition() returns trigger language plpgsql as $transition$\ndeclare at timestamptz; deadline timestamptz;\nbegin\n at=clock_timestamp();deadline=(new.input->>'submitDeadlineAt')::timestamptz;\n if tg_op='INSERT' then\n if (new.state='prepared' and new.dispatched_at is null and new.accepted_at is null and new.handle is null and deadline>at and deadline<=at+interval '1 hour') is not true then raise exception 'Invalid batch claim' using errcode='23514'; end if;\n new.created_at=at;new.updated_at=at;return new;\n end if;\n if (new.org,new.uid,new.key,new.id,new.input,new.token,new.created_at) is distinct from (old.org,old.uid,old.key,old.id,old.input,old.token,old.created_at)\n or coalesce(current_setting('alma.batch_token',true)=old.token,false) is not true then raise exception 'Invalid batch binding or fence' using errcode='23514'; end if;\n if old.state='prepared' and new.state='dispatching' and deadline>at and new.handle is null and new.accepted_at is null then\n new.dispatched_at=at;\n elsif old.handle is null and new.handle is not null and old.dispatched_at is not null\n and new.dispatched_at=old.dispatched_at and new.state in ('submitted','reconciliation_required') then\n new.state=case when old.state='dispatching' and deadline>at then 'submitted' else 'reconciliation_required' end;new.accepted_at=at;\n elsif old.state<>'reconciliation_required' and new.state='reconciliation_required' and (new.dispatched_at,new.accepted_at,new.handle) is not distinct from (old.dispatched_at,old.accepted_at,old.handle) then null;\n else raise exception 'Invalid batch transition' using errcode='23514';\n end if;\n new.updated_at=at;return new;\nend $transition$;\ncreate or replace function alma_batch_member() returns trigger language plpgsql as $member$\ndeclare item jsonb;\nbegin\n select input->'items'->(new.ordinal-1) into item from alma_batch_submissions where org=new.org and uid=new.uid and key=new.batch_key;\n if (item->>'id'=new.item_id and item->'execution'->>'operationKey'=new.operation_key and item->'execution'->>'operationId'=new.operation_id\n and item->'execution'->>'callId'=new.call_id and item->'execution'->>'settlementId'=new.settlement_id) is not true then raise exception 'Invalid batch member' using errcode='23514'; end if;return new;\nend $member$;\ncreate or replace function alma_batch_members() returns trigger language plpgsql as $members$\nbegin\n insert into alma_batch_items(org,uid,batch_key,ordinal,item_id,operation_key,operation_id,call_id,settlement_id)\n select new.org,new.uid,new.key,n,value->>'id',value->'execution'->>'operationKey',value->'execution'->>'operationId',value->'execution'->>'callId',value->'execution'->>'settlementId'\n from jsonb_array_elements(new.input->'items') with ordinality as x(value,n);return new;\nend $members$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_batch_submissions'::regclass and tgname='alma_batch_transition') then\n create trigger alma_batch_transition before insert or update on alma_batch_submissions for each row execute function alma_batch_transition();\n create trigger alma_batch_members after insert on alma_batch_submissions for each row execute function alma_batch_members();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_batch_items'::regclass and tgname='alma_batch_member') then\n create trigger alma_batch_member before insert on alma_batch_items for each row execute function alma_batch_member();\n end if;\nend $triggers$;\n${rlsPolicySql('alma_batch_submissions')}${rlsPolicySql('alma_batch_items')}\ngrant select,insert,update on alma_batch_submissions to ${role};\ngrant select,insert on alma_batch_items to ${role};\n${functionPathSql(\"alma_batch_input_v1(jsonb)\",\"alma_batch_member()\",\"alma_batch_members()\")}\n`;\n}\nexport async function migrateBatchSubmissionStore(pool:Pool,opts:{role?:string}={}):Promise<void>{await pool.query(batchSubmissionMigrationSql(opts.role));}\n","import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementScope, type Scope } from '@alma-harness/core';\nimport { batchUsageMember, batchUsageQuery, batchUsageSettlement, bindBatchUsageReceipt, normalizeBatchUsage, normalizeBatchUsageRecord, normalizeGovernedCostReceipt, type BatchUsageInput, type BatchUsageRecord, type BatchUsageQuery, type BatchUsageStore } from '@alma-harness/execution';\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from '@alma-harness/postgres';\nimport type { Pool,PoolClient } from 'pg';\nimport { PostgresBatchSubmissionStore } from './batch';\ninterface Row {org:string;uid:string;batch_key:string;input:BatchUsageInput;execution:BatchUsageRecord['execution'];received_at:Date;cost_id:string|null;request:unknown;decisions:unknown;settlement_payload:unknown;settlement_session_usd:number;settlement_day_usd:number}\nconst select=`select u.*,b.input->'items'->(i.ordinal-1)->'execution' execution,c.settlement_payload,c.settlement_session_usd,c.settlement_day_usd,g.request,g.decisions\n from alma_batch_usage u join alma_batch_items i on (i.org,i.uid,i.batch_key,i.item_id)=(u.org,u.uid,u.batch_key,u.item_id)\n join alma_batch_submissions b on (b.org,b.uid,b.key)=(u.org,u.uid,u.batch_key)\n left join alma_audit_cost c on (c.org,c.uid,c.id)=(u.org,u.uid,u.cost_id)\n left join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)`;\nconst receipt=(r:Pick<Row,'request'|'decisions'|'settlement_payload'|'settlement_session_usd'|'settlement_day_usd'>)=>normalizeGovernedCostReceipt({request:r.request,decisions:r.decisions,receipt:{settlement:r.settlement_payload,totals:{sessionUsd:r.settlement_session_usd,tenantDayUsd:r.settlement_day_usd}}});\nconst record=(r:Row)=>normalizeBatchUsageRecord({scope:{org:r.org,uid:r.uid},batchKey:r.batch_key,input:r.input,execution:r.execution,receivedAt:r.received_at.toISOString(),...(r.cost_id?{receipt:receipt(r)}:{})});\nexport class PostgresBatchUsageStore implements BatchUsageStore {\n readonly #role:string|null;readonly #timeout:number|null;readonly #batches:PostgresBatchSubmissionStore;\n constructor(readonly pool:Pool,opts:ScopedStoreOptions={}){this.#role=resolveRlsRole(opts);this.#timeout=resolveStatementTimeout(opts);this.#batches=new PostgresBatchSubmissionStore(pool,opts);}\n async #scope<T>(s:Scope,fn:(c:PoolClient)=>Promise<T>):Promise<T>{try{return await inScope(this.pool,this.#role,s,fn,this.#timeout);}catch(e){if(['23505','23514','23503'].includes((e as {code?:string}).code??''))throw new ExecutionConflictError();throw e;}}\n async #read(c:PoolClient,s:Scope,k:string,i:string,lock=false){\n const args=[s.org,s.uid,k,i];\n // Read joined receipts in a fresh statement after waiting for a concurrent adoption.\n if(lock)await c.query('select id from alma_batch_usage where org=$1 and uid=$2 and batch_key=$3 and id=$4 for update',args);\n return (await c.query<Row>(`${select} where u.org=$1 and u.uid=$2 and u.batch_key=$3 and u.id=$4`,args)).rows[0];\n }\n async append(scope:Scope,batchKey:string,value:BatchUsageInput){\n const s=settlementScope(scope),k=id(batchKey),input=normalizeBatchUsage(value);batchUsageMember(await this.#batches.get(s,k),input);\n return this.#scope(s,async c=>{\n await c.query('insert into alma_batch_usage(org,uid,batch_key,id,item_id,input,received_at) values($1,$2,$3,$4,$5,$6::jsonb,clock_timestamp()) on conflict(org,uid,batch_key,id) do nothing',[s.org,s.uid,k,input.id,input.itemId,JSON.stringify(input)]);\n const r=record((await this.#read(c,s,k,input.id))!);if(!equalExecution(r.input,input))throw new ExecutionConflictError();return r;\n });\n }\n async get(scope:Scope,batchKey:string,identity:string){const s=settlementScope(scope),k=id(batchKey),i=id(identity);return this.#scope(s,async c=>{const r=await this.#read(c,s,k,i);return r?record(r):null;});}\n async list(scope:Scope,batchKey:string,query?:BatchUsageQuery){const s=settlementScope(scope),k=id(batchKey),q=batchUsageQuery(query);return this.#scope(s,async c=>(await c.query<Row>(`${select} where u.org=$1 and u.uid=$2 and u.batch_key=$3 and ($4::text is null or u.id>$4 collate \"C\") and (not $5::boolean or u.cost_id is null) order by u.id limit $6`,[s.org,s.uid,k,q.afterId??null,q.pendingOnly,q.limit])).rows.map(record));}\n async recordSettlement(scope:Scope,batchKey:string,identity:string){\n const s=settlementScope(scope),k=id(batchKey),i=id(identity);return this.#scope(s,async c=>{\n const row=await this.#read(c,s,k,i,true);if(!row)throw new ExecutionStateError();const r=record(row);\n if(r.receipt)return {status:'replayed' as const,record:r};if(!batchUsageSettlement(r))return {status:'pending' as const};\n const source=(await c.query<Row&{id:string}>(`select c.id,c.settlement_payload,c.settlement_session_usd,c.settlement_day_usd,g.request,g.decisions from alma_audit_cost c join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id) where c.org=$1 and c.uid=$2 and c.settlement_id=$3 and c.settlement_governed`,[s.org,s.uid,r.execution.settlementId])).rows[0];\n if(!source)return {status:'pending' as const};bindBatchUsageReceipt(r,receipt(source));\n await c.query('update alma_batch_usage set cost_id=$5::uuid where org=$1 and uid=$2 and batch_key=$3 and id=$4',[s.org,s.uid,k,i,source.id]);\n return {status:'applied' as const,record:record((await this.#read(c,s,k,i))!)};\n });\n }\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from 'pg';\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, governedCostSettlementStoreMigrationSql, rlsPolicySql } from '@alma-harness/postgres';\nimport { batchSubmissionMigrationSql } from './batch-schema';\nimport { batchPricingSql } from './batch-pricing-schema';\nexport function batchUsageMigrationSql(role=DEFAULT_RLS_ROLE):string {\n assertRoleIdentifier(role);return `${batchSubmissionMigrationSql(role)}${governedCostSettlementStoreMigrationSql(role)}${batchPricingSql}\ncreate or replace function alma_batch_usage_shape(v jsonb) returns boolean language plpgsql immutable as $shape$\ndeclare e jsonb; u jsonb; field text; child jsonb;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['id','itemId','handle','evidence','outcome']\n and (v-array['id','itemId','handle','evidence','outcome','providerRequestId'])='{}'::jsonb\n and v->>'outcome' in ('succeeded','errored','cancelled','expired','unusable')) is not true then return false;end if;\n foreach field in array array['id','itemId','providerRequestId'] loop\n if (v ? field) and (jsonb_typeof(v->field)='string' and v->>field ~ '^[!-~]{1,200}$') is not true then return false;end if;\n end loop;\n e=v->'evidence';u=e->'usage';\n if alma_execution_shape_v2(e,'evidence') is not true then return false;end if;\n if e->>'status'='unknown' then return (e ? 'reason' and (e-'status'-'reason')='{}'::jsonb and e->>'reason' in ('missing','invalid','interrupted')) is true;end if;\n if (e->>'status' in ('known','unpriced') and u ?& array['inputTokens','outputTokens']) is not true then return false;end if;\n if e->>'status'='known' and ((e-'status'-'usage')<>'{}'::jsonb or u->>'serviceTier' is distinct from 'batch') then return false;end if;\n if e->>'status'='unpriced' then\n if (e ? 'issues' and jsonb_array_length(e->'issues') between 1 and 2 and not(e ? 'reason')) is not true then return false;end if;\n for child in select value from jsonb_array_elements(e->'issues') loop if child not in ('\"service_tier\"'::jsonb,'\"cache_ttl\"'::jsonb) then return false;end if;end loop;\n if e ? 'reportedServiceTier' and (e->>'reportedServiceTier' ~ '^[!-~]{1,200}$') is not true then return false;end if;\n end if;\n if u ? 'serviceTier' and u->>'serviceTier' not in ('batch','standard','priority','flex') then return false;end if;\n if u ? 'cacheWriteTtl' and u->>'cacheWriteTtl' not in ('5m','1h') then return false;end if;\n foreach field in array array['inputTokens','outputTokens','cacheReadInputTokens','cacheWriteInputTokens','reasoningTokens','webSearchRequests'] loop\n if u ? field and ((u->>field)::numeric between 0 and 9007199254740991 and trunc((u->>field)::numeric)=(u->>field)::numeric) is not true then return false;end if;\n end loop;\n if e ? 'cacheWriteTokensByTtl' then\n if (e->'cacheWriteTokensByTtl' ?& array['5m','1h']) is not true then return false;end if;\n for child in select value from jsonb_each(e->'cacheWriteTokensByTtl') loop if ((child#>>'{}')::numeric between 0 and 9007199254740991 and trunc((child#>>'{}')::numeric)=(child#>>'{}')::numeric) is not true then return false;end if;end loop;\n end if;return true;\nexception when others then return false;\nend $shape$;\ncreate table if not exists alma_batch_usage (\n org text not null,uid text not null,batch_key text not null,id text collate \"C\" not null,item_id text not null,\n input jsonb not null,received_at timestamptz not null,cost_id uuid,\n primary key(org,uid,batch_key,id),\n foreign key(org,uid,batch_key,item_id) references alma_batch_items(org,uid,batch_key,item_id),\n foreign key(org,uid,cost_id) references alma_audit_cost(org,uid,id),\n check((alma_batch_usage_shape(input) and input->>'id'=id and input->>'itemId'=item_id) is true)\n);\ncreate or replace function alma_batch_usage_validate() returns trigger language plpgsql as $validate$\ndeclare batch alma_batch_submissions%rowtype; e jsonb; source record; field text;\nbegin\n select * into batch from alma_batch_submissions where org=new.org and uid=new.uid and key=new.batch_key;\n select batch.input->'items'->(ordinal-1)->'execution' into e from alma_batch_items where org=new.org and uid=new.uid and batch_key=new.batch_key and item_id=new.item_id;\n if (batch.state in ('submitted','reconciliation_required') and batch.handle is not null and batch.handle=new.input->'handle' and e is not null) is not true then raise exception 'Invalid batch observation binding' using errcode='23514';end if;\n if tg_op='INSERT' then\n if new.cost_id is not null then raise exception 'Observe before adopting receipt' using errcode='23514';end if;\n new.received_at=clock_timestamp();return new;\n end if;\n if (new.org,new.uid,new.batch_key,new.id,new.item_id,new.input,new.received_at) is distinct from (old.org,old.uid,old.batch_key,old.id,old.item_id,old.input,old.received_at)\n or old.cost_id is not null or new.cost_id is null then raise exception 'Immutable batch observation' using errcode='23514';end if;\n select c.settlement_payload payload,g.request into source from alma_audit_cost c join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where c.org=new.org and c.uid=new.uid and c.id=new.cost_id and c.settlement_governed;\n if (source.payload is not null and new.input->'evidence'->>'status'='known' and source.payload->>'id'=e->>'settlementId'\n and source.payload->'scope'=e->'scope' and source.payload->'model'=e->'model' and source.payload->>'at'=e->>'occurredAt'\n and (source.payload->>'costUsd')::float8=alma_batch_price(e,new.input->'evidence'->'usage')\n and source.payload->>'serviceTier'='batch' and source.payload->'usage'=new.input->'evidence'->'usage'\n and source.payload->'consumers'=e->'governance'->'consumers'\n and source.request->>'policyVersion'=e->>'policyVersion' and source.request->'caps'=e->'governance'->'caps'\n and not(source.payload ? 'parentCallId')) is not true then raise exception 'Invalid batch financial association' using errcode='23514';end if;\n if source.payload->'providerRequestId' is distinct from new.input->'providerRequestId' then raise exception 'Invalid provider reference' using errcode='23514';end if;\n foreach field in array array['sessionId','operationId','attemptId','callId','priceVersion'] loop\n if (source.payload->>field=e->>field) is not true then raise exception 'Invalid financial identity' using errcode='23514';end if;\n end loop;return new;\nend $validate$;\ndo $trigger$ begin\n if not exists(select from pg_trigger where tgrelid='alma_batch_usage'::regclass and tgname='alma_batch_usage_validate') then\n create trigger alma_batch_usage_validate before insert or update on alma_batch_usage for each row execute function alma_batch_usage_validate();\n end if;\nend $trigger$;\n${rlsPolicySql('alma_batch_usage')}\ngrant select,insert,update on alma_batch_usage to ${role};\n${functionPathSql(\"alma_batch_usage_shape(jsonb)\",\"alma_batch_usage_validate()\")}\n`; }\nexport async function migrateBatchUsageStore(pool:Pool,opts:{role?:string}={}):Promise<void>{await pool.query(batchUsageMigrationSql(opts.role));}\n","/** SQL defense for receipt association; arithmetic order mirrors core priceUsage. */\nexport const batchPricingSql=`\ncreate or replace function alma_batch_price(e jsonb,u jsonb) returns double precision language plpgsql immutable as $price$\ndeclare price jsonb; rates jsonb; band jsonb; prompt double precision; best double precision;\n searches double precision; hour_rate double precision; write_rate double precision; amount double precision;\nbegin\n select value into price from jsonb_array_elements(e->'prices') where value->'model'=e->'model' and value->>'serviceTier'='batch' limit 1;\n if price is null then return null;end if;\n prompt=(u->>'inputTokens')::float8+coalesce((u->>'cacheReadInputTokens')::float8,0)+coalesce((u->>'cacheWriteInputTokens')::float8,0);\n rates=price;\n for band in select value from jsonb_array_elements(coalesce(price->'bands','[]'::jsonb)) loop\n if prompt>(band->>'aboveInputTokens')::float8 and (best is null or (band->>'aboveInputTokens')::float8>best) then rates=band;best=(band->>'aboveInputTokens')::float8;end if;\n end loop;\n searches=coalesce((u->>'webSearchRequests')::float8,0);\n if searches>0 and not(price ? 'webSearchUsdPerRequest') then return null;end if;\n hour_rate=coalesce((rates->>'cacheWrite1hUsdPerMTok')::float8,(price->>'cacheWrite1hUsdPerMTok')::float8);\n if u->>'cacheWriteTtl'='1h' and coalesce((u->>'cacheWriteInputTokens')::float8,0)>0 then\n if hour_rate is null then return null;end if;write_rate=hour_rate;\n else write_rate=coalesce((rates->>'cacheWriteUsdPerMTok')::float8,(rates->>'inputUsdPerMTok')::float8);end if;\n amount=((u->>'inputTokens')::float8/1000000::float8)*(rates->>'inputUsdPerMTok')::float8\n +((u->>'outputTokens')::float8/1000000::float8)*(rates->>'outputUsdPerMTok')::float8\n +(coalesce((u->>'cacheReadInputTokens')::float8,0)/1000000::float8)*coalesce((rates->>'cacheReadUsdPerMTok')::float8,(rates->>'inputUsdPerMTok')::float8)\n +(coalesce((u->>'cacheWriteInputTokens')::float8,0)/1000000::float8)*write_rate\n +searches*coalesce((price->>'webSearchUsdPerRequest')::float8,0);\n if amount>=0 and amount<'Infinity'::float8 then return amount;end if;return null;\nexception when others then return null;\nend $price$;\n`;\n","import { ExecutionConflictError,ExecutionStateError,settlementIdentifier as id,settlementScope,type Scope } from '@alma-harness/core';\nimport { bindBatchAccounting,batchFinancialReceipt,batchFinancialWarnings,normalizeBatchFinancialReceipt,operationCallQuery,type BatchAccountingStore,type BatchFinancialReceipt,type BatchFinancialSummary } from '@alma-harness/execution';\nimport { inScope,resolveRlsRole,resolveStatementTimeout,type ScopedStoreOptions } from '@alma-harness/postgres';\nimport type { Pool,PoolClient } from 'pg';\nimport { PostgresBatchSubmissionStore } from './batch';\nimport { PostgresBatchUsageStore } from './batch-usage';\nexport class PostgresBatchAccountingStore implements BatchAccountingStore {\n readonly #role:string|null;readonly #timeout:number|null;readonly #batches:PostgresBatchSubmissionStore;readonly #usage:PostgresBatchUsageStore;\n constructor(readonly pool:Pool,opts:ScopedStoreOptions={}){this.#role=resolveRlsRole(opts);this.#timeout=resolveStatementTimeout(opts);this.#batches=new PostgresBatchSubmissionStore(pool,opts);this.#usage=new PostgresBatchUsageStore(pool,opts);}\n async #scope<T>(s:Scope,fn:(c:PoolClient)=>Promise<T>):Promise<T>{try{return await inScope(this.pool,this.#role,s,fn,this.#timeout);}catch(e){if(['23505','23514','23503'].includes((e as {code?:string}).code??''))throw new ExecutionConflictError();throw e;}}\n async record(scope:Scope,batchKey:string,observationId:string){\n const s=settlementScope(scope),k=id(batchKey),i=id(observationId),batch=await this.#batches.get(s,k);if(!batch)throw new ExecutionStateError();\n const value=await this.#usage.get(s,k,i);if(!value)return {status:'pending' as const};const source=bindBatchAccounting(batch,value);if(!source.receipt)return {status:'pending' as const};\n return this.#scope(s,async c=>{\n const args=[s.org,s.uid,k];await c.query('select key from alma_batch_submissions where org=$1 and uid=$2 and key=$3 for update',args);\n const old=(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 and item_id=$4',[...args,source.input.itemId])).rows[0];if(old)return {status:'replayed' as const,receipt:normalizeBatchFinancialReceipt(old.receipt)};\n const previous=(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 order by ordinal desc limit 1',args)).rows[0];\n const warned=(await c.query<{cap:BatchFinancialReceipt['newWarnings'][number]}>('select cap from alma_batch_warnings where org=$1 and uid=$2 and batch_key=$3',args)).rows.map(r=>r.cap);\n const now=(await c.query<{at:Date}>('select clock_timestamp() at')).rows[0]!.at.toISOString();\n const receipt=batchFinancialReceipt(batch,source,previous?normalizeBatchFinancialReceipt(previous.receipt):undefined,warned,now);\n await c.query('insert into alma_batch_financial_items(org,uid,batch_key,item_id,observation_id,ordinal,receipt) values($1,$2,$3,$4,$5,$6,$7::jsonb)',[...args,receipt.itemId,i,receipt.accountingOrdinal,JSON.stringify(receipt)]);\n return {status:'applied' as const,receipt};\n });\n }\n async get(scope:Scope,batchKey:string):Promise<BatchFinancialSummary|null>{\n const s=settlementScope(scope),k=id(batchKey),batch=await this.#batches.get(s,k);if(!batch)return null;\n return this.#scope(s,async c=>{\n const args=[s.org,s.uid,k],state=(await c.query<{state:typeof batch.state}>('select state from alma_batch_submissions where org=$1 and uid=$2 and key=$3 for share',args)).rows[0]!.state;\n const last=(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 order by ordinal desc limit 1',args)).rows[0];\n const rows=(await c.query<{receipt:BatchFinancialReceipt;cap:string}>('select f.receipt,w.cap from alma_batch_warnings w join alma_batch_financial_items f on (f.org,f.uid,f.batch_key,f.item_id)=(w.org,w.uid,w.batch_key,w.item_id) where w.org=$1 and w.uid=$2 and w.batch_key=$3 order by f.ordinal,w.cap',args)).rows;\n const warnings=rows.map(r=>{const w=batchFinancialWarnings(s,r.receipt).find(w=>w.cap===r.cap);if(!w)throw new ExecutionConflictError();return w;});\n const receipt=last?normalizeBatchFinancialReceipt(last.receipt):undefined;return {batchId:batch.input.id,costUsd:receipt?.currentUsd??0,expectedItems:batch.input.items.length,accountedItems:receipt?.accountingOrdinal??0,batchState:state,warnings};\n });\n }\n async list(scope:Scope,batchKey:string,query?:{afterOrdinal?:number;limit?:number}){const s=settlementScope(scope),k=id(batchKey),q=operationCallQuery(query);return this.#scope(s,async c=>(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 and ordinal>$4 order by ordinal limit $5',[s.org,s.uid,k,q.afterOrdinal,q.limit])).rows.map(r=>normalizeBatchFinancialReceipt(r.receipt)));}\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from 'pg';\nimport { assertRoleIdentifier,DEFAULT_RLS_ROLE,rlsPolicySql } from '@alma-harness/postgres';\nimport { batchUsageMigrationSql } from './batch-usage-schema';\nexport function batchAccountingMigrationSql(role=DEFAULT_RLS_ROLE):string {\n assertRoleIdentifier(role);return `${batchUsageMigrationSql(role)}\ncreate table if not exists alma_batch_financial_items (\n org text not null,uid text not null,batch_key text not null,item_id text not null,observation_id text not null,\n ordinal int not null check(ordinal between 1 and 512),receipt jsonb not null,\n primary key(org,uid,batch_key,item_id),unique(org,uid,batch_key,ordinal),\n foreign key(org,uid,batch_key,item_id) references alma_batch_items(org,uid,batch_key,item_id),\n foreign key(org,uid,batch_key,observation_id) references alma_batch_usage(org,uid,batch_key,id)\n);\ncreate table if not exists alma_batch_warnings (\n org text not null,uid text not null,batch_key text not null,cap text not null check(cap in ('perTurnUsd','perSessionUsd','perTenantDayUsd')),item_id text not null,\n primary key(org,uid,batch_key,cap),foreign key(org,uid,batch_key,item_id) references alma_batch_financial_items(org,uid,batch_key,item_id)\n);\ncreate or replace function alma_batch_financial_validate() returns trigger language plpgsql as $financial$\ndeclare batch alma_batch_submissions%rowtype; member alma_batch_items%rowtype; prior alma_batch_financial_items%rowtype;\n source record; r jsonb; before_usd double precision; cost double precision; after_usd double precision; expected jsonb; warnings jsonb; field text;\nbegin\n select * into batch from alma_batch_submissions where org=new.org and uid=new.uid and key=new.batch_key for update;\n select * into member from alma_batch_items where org=new.org and uid=new.uid and batch_key=new.batch_key and item_id=new.item_id;\n select * into prior from alma_batch_financial_items where org=new.org and uid=new.uid and batch_key=new.batch_key order by ordinal desc limit 1;\n select u.item_id,c.settlement_payload payload,g.decisions into source from alma_batch_usage u\n join alma_audit_cost c on (c.org,c.uid,c.id)=(u.org,u.uid,u.cost_id) join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where u.org=new.org and u.uid=new.uid and u.batch_key=new.batch_key and u.id=new.observation_id;\n r=new.receipt;before_usd=coalesce((prior.receipt->>'currentUsd')::float8,0);cost=(source.payload->>'costUsd')::float8;after_usd=before_usd+cost;\n foreach field in array array['batchId','itemId','callId','settlementId','recordedAt'] loop\n if jsonb_typeof(r->field) is distinct from 'string' then raise exception 'Invalid financial string' using errcode='23514';end if;\n end loop;\n foreach field in array array['accountingOrdinal','reservationOrdinal','costUsd','previousUsd','currentUsd'] loop\n if jsonb_typeof(r->field) is distinct from 'number' then raise exception 'Invalid financial amount' using errcode='23514';end if;\n end loop;\n if (source.item_id=new.item_id and source.payload is not null and batch.id is not null\n and jsonb_typeof(r)='object' and r ?& array['batchId','itemId','callId','settlementId','accountingOrdinal','reservationOrdinal','costUsd','previousUsd','currentUsd','decisions','newWarnings','recordedAt']\n and (r-array['batchId','itemId','callId','settlementId','accountingOrdinal','reservationOrdinal','costUsd','previousUsd','currentUsd','decisions','newWarnings','recordedAt'])='{}'::jsonb\n and r->>'batchId'=batch.id and r->>'itemId'=new.item_id and r->>'callId'=member.call_id and r->>'settlementId'=member.settlement_id\n and new.ordinal=coalesce(prior.ordinal,0)+1 and (r->>'accountingOrdinal')::numeric=new.ordinal and (r->>'reservationOrdinal')::numeric=member.ordinal\n and (r->>'previousUsd')::float8=before_usd and (r->>'costUsd')::float8=cost and (r->>'currentUsd')::float8=after_usd and after_usd<'Infinity'::float8\n and to_char((r->>'recordedAt')::timestamptz at time zone 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')=r->>'recordedAt'\n and isfinite((r->>'recordedAt')::timestamptz) and r->>'recordedAt' ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{3}Z$') is not true then raise exception 'Invalid batch financial binding' using errcode='23514';end if;\n select coalesce(jsonb_agg(case when d->>'cap'='perTurnUsd' then d||jsonb_build_object('previousUsd',before_usd,'currentUsd',after_usd,'exceeded',after_usd>(d->>'thresholdUsd')::float8) else d end order by n),'[]'::jsonb) into expected from jsonb_array_elements(source.decisions) with ordinality as x(d,n);\n if r->'decisions' is distinct from expected then raise exception 'Invalid batch financial decisions' using errcode='23514';end if;\n select coalesce(jsonb_agg(d->>'cap' order by n),'[]'::jsonb) into warnings from jsonb_array_elements(expected) with ordinality as x(d,n)\n where d->>'onExceeded'='warn' and (d->>'exceeded')::boolean and not exists(select from alma_batch_warnings w where w.org=new.org and w.uid=new.uid and w.batch_key=new.batch_key and w.cap=d->>'cap');\n if r->'newWarnings' is distinct from warnings then raise exception 'Invalid batch warning receipt' using errcode='23514';end if;\n return new;\nend $financial$;\ncreate or replace function alma_batch_financial_warn() returns trigger language plpgsql as $warn$\nbegin\n insert into alma_batch_warnings(org,uid,batch_key,cap,item_id) select new.org,new.uid,new.batch_key,value,new.item_id from jsonb_array_elements_text(new.receipt->'newWarnings');return new;\nend $warn$;\ncreate or replace function alma_batch_warning_validate() returns trigger language plpgsql as $warning$\nbegin\n if not exists(select from alma_batch_financial_items where org=new.org and uid=new.uid and batch_key=new.batch_key and item_id=new.item_id and receipt->'newWarnings' ? new.cap) then raise exception 'Invalid batch warning association' using errcode='23514';end if;return new;\nend $warning$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_batch_financial_items'::regclass and tgname='alma_batch_financial_validate') then\n create trigger alma_batch_financial_validate before insert on alma_batch_financial_items for each row execute function alma_batch_financial_validate();\n create trigger alma_batch_financial_warn after insert on alma_batch_financial_items for each row execute function alma_batch_financial_warn();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_batch_warnings'::regclass and tgname='alma_batch_warning_validate') then\n create trigger alma_batch_warning_validate before insert on alma_batch_warnings for each row execute function alma_batch_warning_validate();\n end if;\nend $triggers$;\n${rlsPolicySql('alma_batch_financial_items')}${rlsPolicySql('alma_batch_warnings')}\ngrant select,insert on alma_batch_financial_items,alma_batch_warnings to ${role};\n${functionPathSql(\"alma_batch_financial_validate()\",\"alma_batch_financial_warn()\",\"alma_batch_warning_validate()\")}\n`; }\nexport async function migrateBatchAccountingStore(pool:Pool,opts:{role?:string}={}):Promise<void>{await pool.query(batchAccountingMigrationSql(opts.role));}\n"],"mappings":";AAAA,SAAS,kBAAAA,iBAAgB,0BAAAC,yBAAwB,uBAAAC,sBAAqB,wBAAwBC,KAAI,mBAAAC,kBAAiB,mBAAAC,wBAAmC;AACtJ,SAAS,oBAAoB,0BAAAC,yBAAwB,0BAAAC,yBAAwB,yBAAyB,0BAAAC,yBAAwB,sBAAAC,2BAA8K;AAC5S,SAAS,WAAAC,UAAS,kBAAAC,iBAAgB,2BAAAC,gCAAwD;;;ACF1F,SAAS,mBAAAC,wBAAuB;AAEhC,SAAS,sBAAsB,kBAAkB,4BAA4B,oBAAoB;;;ACFjG,SAAS,uBAAuB;AAEzB,IAAM,2BAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAO,GAAG,IAAI;AAAA,IAAM,CAAC;AAAA,EAC9G;AAAA,EACA,MAAM,UAAU,OAAc,UAAkB,OAAmF;AACjI,UAAM,IAAID,iBAAgB,KAAK,GAAG,IAAIC,IAAG,QAAQ,GAAG,IAAIC,oBAAmB,KAAK;AAChF,WAAO,KAAK,OAAO,GAAG,OAAM,OAAM,MAAM,EAAE,MAAe;AAAA,8FACiC,CAAC,EAAE,KAAK,EAAE,KAAK,GAAG,EAAE,cAAc,EAAE,KAAK,CAAC,GAAG,KAAK,IAAI,IAAI,CAAC;AAAA,EACvJ;AAAA,EACA,MAAM,iBAAiB,OAAc,OAA2B,CAAC,GAAmC;AAClG,UAAM,IAAIF,iBAAgB,KAAK,GAAG,QAAQG,iBAAgB,KAAK,KAAK;AACpE,WAAO,KAAK,OAAO,GAAG,OAAM,MAAK;AAC/B,YAAM,QAAQ,MAAM,EAAE,MAAe,UAAU,IAAI,sKAAsK,CAAC,EAAE,KAAK,EAAE,KAAK,KAAK,CAAC,GAAG;AACjP,YAAM,UAAiC,CAAC;AACxC,iBAAW,KAAK,KAAM,SAAQ,KAAK,QAAQ,MAAM,EAAE,MAAe,8IAA8I,IAAI,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,KAAK,CAAC,CAAE,CAAC;AACzP,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":["equalExecution","ExecutionConflictError","ExecutionStateError","id","settlementLimit","settlementScope","checkOperationDeadline","normalizeOperationCall","normalizeOperationRoot","operationCallQuery","inScope","resolveRlsRole","resolveStatementTimeout","functionPathSql","functionPathSql","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","rlsPolicySql","DEFAULT_RLS_ROLE","assertRoleIdentifier","rlsPolicySql","functionPathSql","ExecutionConflictError","ExecutionStateError","id","settlementScope","normalizeOperationRoot","operationCallQuery","assertRoleIdentifier","inScope","resolveRlsRole","resolveStatementTimeout","record","at","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","DEFAULT_RETENTION_ROLE","rlsPolicySql","DEFAULT_RLS_ROLE","DEFAULT_RETENTION_ROLE","assertRoleIdentifier","rlsPolicySql","functionPathSql","equalExecution","ExecutionConflictError","ExecutionStateError","id","settlementScope","inScope","resolveRlsRole","resolveStatementTimeout","record","at","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","executionStoreMigrationSql","rlsPolicySql","equalExecution","ExecutionConflictError","ExecutionStateError","id","settlementScope","normalizeGovernedCostReceipt","inScope","resolveRlsRole","resolveStatementTimeout","receipt","normalizeGovernedCostReceipt","record","resolveRlsRole","resolveStatementTimeout","inScope","ExecutionConflictError","settlementScope","id","equalExecution","ExecutionStateError","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","governedCostSettlementStoreMigrationSql","rlsPolicySql","DEFAULT_RLS_ROLE","assertRoleIdentifier","governedCostSettlementStoreMigrationSql","rlsPolicySql","functionPathSql","ExecutionConflictError","ExecutionStateError","id","settlementScope","operationCallQuery","inScope","resolveRlsRole","resolveStatementTimeout","resolveRlsRole","resolveStatementTimeout","inScope","ExecutionConflictError","settlementScope","id","ExecutionStateError","receipt","w","operationCallQuery","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","rlsPolicySql","DEFAULT_RLS_ROLE","assertRoleIdentifier","rlsPolicySql","functionPathSql","resolveRlsRole","resolveStatementTimeout","inScope","ExecutionConflictError","ExecutionStateError","normalizeOperationRoot","checkOperationDeadline","equalExecution","normalizeOperationCall","settlementScope","id","operationCallQuery","settlementLimit"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/request-schema.ts","../src/rows.ts","../src/accounting.ts","../src/accounting-schema.ts","../src/session.ts","../src/session-schema.ts","../src/batch.ts","../src/batch-schema.ts","../src/batch-usage.ts","../src/batch-usage-schema.ts","../src/batch-pricing-schema.ts","../src/batch-accounting.ts","../src/batch-accounting-schema.ts"],"sourcesContent":["import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementLimit, settlementScope, type Scope } from \"@alma-harness/core\";\nimport { checkOperationCall, checkOperationDeadline, normalizeOperationCall, normalizeOperationFence, normalizeOperationRoot, operationCallQuery, type OperationCallInput, type OperationCallRecord, type OperationFence, type OperationRootInput, type OperationRootRecord, type OperationTreeStore } from \"@alma-harness/execution\";\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from \"@alma-harness/postgres\";\nimport type { Pool, PoolClient } from \"pg\";\nexport { operationTreeMigrationSql, migrateOperationTreeStore } from \"./schema\";\nimport { ROOT, record, call, type RootRow, type CallRow } from \"./rows\";\nconst at = async (c: PoolClient) => (await c.query<{ at: Date }>(\"select clock_timestamp() at\")).rows[0]!.at.toISOString();\nexport class PostgresOperationTreeStore implements OperationTreeStore {\n readonly #role: string | null; readonly #timeout: number | null;\n constructor(readonly pool: Pool, opts: ScopedStoreOptions = {}) { this.#role = resolveRlsRole(opts); this.#timeout = resolveStatementTimeout(opts); }\n async #scope<T>(scope: Scope, fn: (c: PoolClient) => Promise<T>): Promise<T> {\n try { return await inScope(this.pool, this.#role, scope, fn, this.#timeout); }\n catch (e) {\n const code = (e as { code?: string } | null)?.code;\n const mapped = code === \"23505\" ? new ExecutionConflictError() : code === \"23503\" || code === \"23514\" ? new ExecutionStateError() : undefined;\n if (mapped) throw Object.defineProperty(mapped, \"cause\", { value: e, writable: true, configurable: true });\n throw e;\n }\n }\n async #read(c: PoolClient, scope: Scope, key: string, lock = false): Promise<RootRow | undefined> {\n return (await c.query<RootRow>(`select ${ROOT}${lock ? \",token\" : \"\"} from alma_operation_roots where org=$1 and uid=$2 and key=$3${lock ? \" for update\" : \"\"}`, [scope.org, scope.uid, key])).rows[0];\n }\n async claim(value: OperationRootInput) {\n const i = normalizeOperationRoot(value); let insertConflict: unknown;\n try { return await this.#scope(i.scope, async c => {\n let row = await this.#read(c, i.scope, i.key, true);\n if (!row) {\n checkOperationDeadline(i, await at(c));\n try { row = (await c.query<RootRow>(`insert into alma_operation_roots(org,uid,key,id,session_id,policy_version,caps,max_sensitivity,deadline_at,max_calls,status,token,created_at,updated_at,request)\n values($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9::timestamptz,$10,'active',$11,clock_timestamp(),clock_timestamp(),$12::jsonb)\n on conflict(org,uid,key) do nothing returning ${ROOT},token`, [i.scope.org, i.scope.uid, i.key, i.id, i.sessionId, i.policyVersion, JSON.stringify(i.caps), i.maxSensitivity, i.deadlineAt, i.maxCalls, crypto.randomUUID(), i.request ? JSON.stringify(i.request) : null])).rows[0]; }\n catch (e) { if ((e as { code?: string } | null)?.code === \"23505\") insertConflict = e; throw e; }\n if (row) { checkOperationDeadline(i, await at(c)); return { status: \"claimed\" as const, record: record(row), fence: { scope: { ...i.scope }, key: i.key, id: i.id, token: row.token! } }; }\n row = await this.#read(c, i.scope, i.key, true);\n }\n if (!row || !equalExecution(record(row).input, i)) throw new ExecutionConflictError();\n return { status: \"existing\" as const, record: record(row) };\n }); } catch (e) {\n if (!insertConflict || !(e instanceof ExecutionConflictError) || e.cause !== insertConflict) throw e;\n // DECISION: only the failed INSERT permits readback after transaction cleanup.\n // Exact binding returns observation, never a new fence or renewed deadline.\n return this.#scope(i.scope, async c => {\n const row = await this.#read(c, i.scope, i.key); if (!row) throw e;\n const existing = record(row); if (!equalExecution(existing.input, i)) throw e;\n return { status: \"existing\" as const, record: existing };\n });\n }\n }\n async #authorize(c: PoolClient, f: OperationFence, closing = false): Promise<RootRow> {\n const r = await this.#read(c, f.scope, f.key, true);\n if (!r || r.id !== f.id || r.token !== f.token) throw new ExecutionStateError();\n if (closing && r.status === \"closed\") return r;\n if (r.status !== \"active\" || r.deadline_at.toISOString() <= await at(c)) throw new ExecutionStateError(); return r;\n }\n async reserve(value: OperationFence, request: OperationCallInput): Promise<OperationCallRecord> {\n const f = normalizeOperationFence(value), input = normalizeOperationCall(request);\n return this.#scope(f.scope, async c => {\n const r = await this.#authorize(c, f); checkOperationCall(record(r).input, input);\n const old = (await c.query<CallRow>(\"select * from alma_operation_calls where org=$1 and uid=$2 and root_id=$3 and slot=$4\", [f.scope.org, f.scope.uid, f.id, input.slot])).rows[0];\n if (old) { if (!equalExecution(call(old).input, input)) throw new ExecutionConflictError(); return call(old); }\n if (r.call_count >= r.max_calls) throw new ExecutionStateError();\n const e = input.execution;\n const row = (await c.query<CallRow>(`insert into alma_operation_calls(org,uid,root_id,slot,ordinal,kind,parent_call_id,call_id,settlement_id,operation_key,input,reserved_at)\n values($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::jsonb,clock_timestamp()) returning *`, [f.scope.org, f.scope.uid, f.id, input.slot, r.call_count + 1, input.kind, input.parentCallId ?? null, e.callId, e.settlementId, e.operationKey, JSON.stringify(e)])).rows[0]!;\n return call(row);\n });\n }\n async close(value: OperationFence): Promise<OperationRootRecord> {\n const f = normalizeOperationFence(value);\n return this.#scope(f.scope, async c => {\n const row = await this.#authorize(c, f, true); if (row.status === \"closed\") return record(row);\n return record((await c.query<RootRow>(`update alma_operation_roots set status='closed',updated_at=clock_timestamp() where org=$1 and uid=$2 and key=$3 returning ${ROOT}`, [f.scope.org, f.scope.uid, f.key])).rows[0]!);\n });\n }\n async get(scope: Scope, identity: string): Promise<OperationRootRecord | null> {\n const s = settlementScope(scope), k = id(identity);\n return this.#scope(s, async c => { const row = await this.#read(c, s, k); return row ? record(row) : null; });\n }\n async listCalls(scope: Scope, identity: string, query?: { afterOrdinal?: number; limit?: number }): Promise<OperationCallRecord[]> {\n const s = settlementScope(scope), k = id(identity), q = operationCallQuery(query);\n return this.#scope(s, async c => (await c.query<CallRow>(`select c.* from alma_operation_calls c join alma_operation_roots r on (r.org,r.uid,r.id)=(c.org,c.uid,c.root_id)\n where r.org=$1 and r.uid=$2 and r.key=$3 and c.ordinal>$4 order by c.ordinal limit $5`, [s.org, s.uid, k, q.afterOrdinal, q.limit])).rows.map(call));\n }\n async reconcileExpired(scope: Scope, opts: { limit?: number } = {}): Promise<OperationRootRecord[]> {\n const s = settlementScope(scope), limit = settlementLimit(opts.limit);\n return this.#scope(s, async c => {\n const rows = (await c.query<RootRow>(`select ${ROOT} from alma_operation_roots where org=$1 and uid=$2 and status='active' and deadline_at<=clock_timestamp() order by deadline_at,key limit $3 for update skip locked`, [s.org, s.uid, limit])).rows;\n const results: OperationRootRecord[] = [];\n for (const r of rows) results.push(record((await c.query<RootRow>(`update alma_operation_roots set status='reconciliation_required',updated_at=clock_timestamp() where org=$1 and uid=$2 and key=$3 returning ${ROOT}`, [s.org, s.uid, r.key])).rows[0]!));\n return results;\n });\n }\n}\n\nexport { PostgresOperationAccountingStore } from \"./accounting\";\nexport { operationAccountingMigrationSql, migrateOperationAccountingStore } from \"./accounting-schema\";\nexport { PostgresOperationSessionStore } from \"./session\";\nexport { operationSessionMigrationSql, migrateOperationSessionStore } from \"./session-schema\";\nexport { PostgresBatchSubmissionStore } from './batch';\nexport { batchSubmissionMigrationSql, migrateBatchSubmissionStore } from './batch-schema';\nexport { PostgresBatchUsageStore } from './batch-usage';\nexport { batchUsageMigrationSql, migrateBatchUsageStore } from './batch-usage-schema';\nexport { PostgresBatchAccountingStore } from './batch-accounting';\nexport { batchAccountingMigrationSql, migrateBatchAccountingStore } from './batch-accounting-schema';\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from \"pg\";\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, executionStoreMigrationSql, rlsPolicySql } from \"@alma-harness/postgres\";\nimport { operationRequestRootSql, operationRequestShapeSql } from \"./request-schema\";\nexport function operationTreeMigrationSql(role = DEFAULT_RLS_ROLE): string {\n assertRoleIdentifier(role);\n return `${executionStoreMigrationSql(role)}${operationRequestShapeSql}\ncreate or replace function alma_operation_caps(v jsonb) returns boolean language plpgsql immutable as $caps$\ndeclare item record;\nbegin\n if jsonb_typeof(v) <> 'object' then return false; end if;\n for item in select * from jsonb_each(v) loop\n if (item.key in ('perTurnUsd','perSessionUsd','perTenantDayUsd') and jsonb_typeof(item.value)='object'\n and item.value ?& array['usd','onExceeded'] and (item.value-'usd'-'onExceeded')='{}'::jsonb\n and jsonb_typeof(item.value->'usd')='number' and item.value->'usd'>='0'::jsonb\n and item.value->>'onExceeded' in ('warn','block')) is not true then return false; end if;\n end loop; return true;\nend $caps$;\ncreate table if not exists alma_operation_roots (\n org text not null, uid text not null, key text collate \"C\" not null, id text not null,\n session_id text not null, policy_version text not null, caps jsonb not null,\n max_sensitivity text not null check(max_sensitivity in ('public','internal','personal','health')),\n deadline_at timestamptz not null, max_calls int not null check(max_calls between 1 and 512),\n status text not null check(status in ('active','closed','reconciliation_required')),\n token text not null, call_count int not null default 0 check(call_count between 0 and max_calls),\n created_at timestamptz not null, updated_at timestamptz not null,\n primary key(org,uid,key), unique(org,uid,id),\n check((${[\"org\", \"uid\", \"key\", \"id\", \"session_id\", \"policy_version\", \"token\"].map(k => `${k} ~ '^[!-~]{1,200}$'`).join(\" and \")}) is true),\n check(alma_operation_caps(caps) is true)\n);\ncreate index if not exists alma_operation_expired on alma_operation_roots(org,uid,deadline_at,key) where status='active';\ncreate table if not exists alma_operation_calls (\n org text not null, uid text not null, root_id text not null, slot text collate \"C\" not null,\n ordinal int not null check(ordinal between 1 and 512), kind text not null check(kind in ('main','direct','delegate','summary')),\n parent_call_id text, call_id text not null, settlement_id text not null, operation_key text not null,\n input jsonb not null, reserved_at timestamptz not null,\n primary key(org,uid,root_id,slot), unique(org,uid,root_id,ordinal), unique(org,uid,root_id,call_id),\n unique(org,uid,call_id), unique(org,uid,settlement_id), unique(org,uid,operation_key),\n foreign key(org,uid,root_id) references alma_operation_roots(org,uid,id),\n foreign key(org,uid,root_id,parent_call_id) references alma_operation_calls(org,uid,root_id,call_id),\n check((kind='main')=(parent_call_id is null)), check(parent_call_id is null or parent_call_id<>call_id),\n check(slot ~ '^[!-~]{1,200}$'),\n constraint alma_operation_call_shape check((alma_execution_shape_v2(jsonb_set(input,'{controls}',(input->'controls')-'temperature'),'input')\n and input ?& array['scope','operationKey','operationId','attemptId','callId','settlementId','sessionId','inputRevision','policyVersion','outputContractVersion','intent','model','requestedTier','priceVersion','prices','controls','occurredAt','deadlineAt','governance']\n and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid and input->>'callId'=call_id\n and input->>'settlementId'=settlement_id and input->>'operationKey'=operation_key) is true),\n constraint alma_operation_temperature_check check((not (input->'controls' ? 'temperature') or\n (jsonb_typeof(input->'controls'->'temperature')='number' and input->'controls'->'temperature'>='0'::jsonb and input->'controls'->'temperature'<='2'::jsonb)) is true)\n);\n-- Replace only the legacy parent-kind CHECK; old migration replay uses CREATE IF NOT EXISTS.\nalter table alma_operation_calls drop constraint if exists alma_operation_calls_check;\ndo $parent_kind$ begin\n if not exists(select from pg_constraint where conrelid='alma_operation_calls'::regclass and conname='alma_operation_parent_kind') then\n alter table alma_operation_calls add constraint alma_operation_parent_kind\n check((kind='main' and parent_call_id is null) or kind='summary' or (kind in ('direct','delegate') and parent_call_id is not null));\n end if;\nend $parent_kind$;\ncreate or replace function alma_operation_reserve() returns trigger language plpgsql as $reserve$\ndeclare r alma_operation_roots%rowtype;\nbegin\n select * into r from alma_operation_roots where org=new.org and uid=new.uid and id=new.root_id for update;\n if (r.status='active' and r.deadline_at>clock_timestamp() and new.ordinal=r.call_count+1 and new.ordinal<=r.max_calls\n and new.input->>'sessionId'=r.session_id and new.input->>'policyVersion'=r.policy_version\n and new.input->'governance'->'caps'=r.caps and (new.input->>'deadlineAt')::timestamptz<=r.deadline_at\n and array_position(array['public','internal','personal','health'],new.input->'intent'->>'sensitivity')<=array_position(array['public','internal','personal','health'],r.max_sensitivity)) is not true then\n raise exception 'Invalid operation reservation' using errcode='23514';\n end if;\n if new.parent_call_id is not null and not exists(select from alma_operation_calls where org=new.org and uid=new.uid and root_id=new.root_id and call_id=new.parent_call_id and ordinal<new.ordinal) then\n raise exception 'Invalid operation parent' using errcode='23514';\n end if;\n update alma_operation_roots set call_count=new.ordinal,updated_at=clock_timestamp() where org=new.org and uid=new.uid and id=new.root_id;\n return new;\nend $reserve$;\ndo $trigger$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_calls'::regclass and tgname='alma_operation_reserve') then\n create trigger alma_operation_reserve before insert on alma_operation_calls for each row execute function alma_operation_reserve();\n end if;\nend $trigger$;\n${rlsPolicySql(\"alma_operation_roots\")}${rlsPolicySql(\"alma_operation_calls\")}\ngrant select,insert,update on alma_operation_roots to ${role};\ngrant select,insert on alma_operation_calls to ${role};\n${operationRequestRootSql}\n${functionPathSql(\"alma_operation_reserve()\")}\n`;\n}\nexport async function migrateOperationTreeStore(pool: Pool, opts: { role?: string } = {}): Promise<void> { await pool.query(operationTreeMigrationSql(opts.role)); }\n","import { functionPathSql } from \"@alma-harness/postgres\";\n/** Versioned checks survive frozen legacy migration replay (spec: conversation-root-binding). */\nexport const operationRequestShapeSql = `\ncreate or replace function alma_operation_request_v1(v jsonb) returns boolean language plpgsql immutable as $request$\ndeclare field text;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['inputRevision','configRevision','resultContractVersion','resultRetentionMs']\n and (v-array['inputRevision','configRevision','resultContractVersion','resultRetentionMs'])='{}'::jsonb\n and jsonb_typeof(v->'resultRetentionMs')='number' and (v->>'resultRetentionMs')::numeric between 1 and 31536000000\n and trunc((v->>'resultRetentionMs')::numeric)=(v->>'resultRetentionMs')::numeric) is not true then return false; end if;\n foreach field in array array['inputRevision','configRevision','resultContractVersion'] loop\n if (jsonb_typeof(v->field)='string' and v->>field ~ '^[!-~]{1,200}$') is not true then return false; end if;\n end loop; return true;\nexception when others then return false;\nend $request$;\n`;\nexport const operationRequestRootSql = `\nalter table alma_operation_roots add column if not exists request jsonb;\ndo $request_check$ begin\n if not exists(select from pg_constraint where conrelid='alma_operation_roots'::regclass and conname='alma_operation_request_check') then\n alter table alma_operation_roots add constraint alma_operation_request_check check(request is null or alma_operation_request_v1(request) is true);\n end if;\nend $request_check$;\ncreate or replace function alma_operation_binding_immutable() returns trigger language plpgsql as $binding$\nbegin\n if (new.org,new.uid,new.key,new.id,new.session_id,new.policy_version,new.caps,new.max_sensitivity,new.deadline_at,new.max_calls,new.token,new.created_at,new.request)\n is distinct from (old.org,old.uid,old.key,old.id,old.session_id,old.policy_version,old.caps,old.max_sensitivity,old.deadline_at,old.max_calls,old.token,old.created_at,old.request) then\n raise exception 'Immutable operation binding' using errcode='23514';\n end if; return new;\nend $binding$;\ndo $binding_trigger$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_roots'::regclass and tgname='alma_operation_binding_immutable') then\n create trigger alma_operation_binding_immutable before update on alma_operation_roots for each row execute function alma_operation_binding_immutable();\n end if;\nend $binding_trigger$;\n`;\nexport const operationRequestAdmissionSql = `\ncreate or replace function alma_admission_input_v2(v jsonb) returns boolean language sql immutable as $shape$\n select (alma_admission_input(v-'request') and (not(v ? 'request') or alma_operation_request_v1(v->'request'))) is true;\n$shape$;\ndo $admission_check$ declare legacy record;\nbegin\n -- Replace only the original input-shape check, not state, fence or scope controls.\n for legacy in select conname from pg_constraint where conrelid='alma_operation_admissions'::regclass\n and contype='c' and pg_get_constraintdef(oid) like '%alma_admission_input(input)%' loop\n execute format('alter table alma_operation_admissions drop constraint %I',legacy.conname);\n end loop;\n if not exists(select from pg_constraint where conrelid='alma_operation_admissions'::regclass and conname='alma_admission_input_v2_check') then\n alter table alma_operation_admissions add constraint alma_admission_input_v2_check check((alma_admission_input_v2(input)\n and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid and input->>'key'=root_key\n and input->>'id'=root_id and input->>'sessionId'=session_id and (input->>'deadlineAt')::timestamptz=deadline_at) is true);\n end if;\nend $admission_check$;\n${functionPathSql(\"alma_admission_input_v2(jsonb)\")}\n`;\n","import { normalizeOperationRoot, normalizeOperationCall, type OperationRootRecord, type OperationCallInput, type OperationCallRecord } from \"@alma-harness/execution\";\nexport const ROOT = \"org,uid,key,id,session_id,policy_version,caps,max_sensitivity,deadline_at,max_calls,status,call_count,created_at,updated_at,request\";\nexport interface RootRow { request: unknown | null; org: string; uid: string; key: string; id: string; session_id: string; policy_version: string; caps: unknown; max_sensitivity: string; deadline_at: Date; max_calls: number; status: OperationRootRecord[\"status\"]; call_count: number; created_at: Date; updated_at: Date; token?: string }\nexport function record(r: RootRow): OperationRootRecord {\n return { input: normalizeOperationRoot({ ...(r.request === null ? {} : { request: r.request }), scope: { org: r.org, uid: r.uid }, key: r.key, id: r.id, sessionId: r.session_id, policyVersion: r.policy_version, caps: r.caps, maxSensitivity: r.max_sensitivity, deadlineAt: r.deadline_at.toISOString(), maxCalls: r.max_calls }), status: r.status, callCount: r.call_count, createdAt: r.created_at.toISOString(), updatedAt: r.updated_at.toISOString() };\n}\nexport interface CallRow { root_id: string; ordinal: number; slot: string; kind: OperationCallInput[\"kind\"]; parent_call_id: string | null; input: OperationCallInput[\"execution\"]; reserved_at: Date }\nexport function call(r: CallRow): OperationCallRecord {\n return { rootId: r.root_id, ordinal: r.ordinal, input: normalizeOperationCall({ slot: r.slot, kind: r.kind, ...(r.parent_call_id !== null ? { parentCallId: r.parent_call_id } : {}), execution: r.input }), reservedAt: r.reserved_at.toISOString() };\n}\n","import { ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementScope, type Scope } from \"@alma-harness/core\";\nimport { normalizeGovernedCostReceipt, normalizeRootCallReceipt, operationCallQuery, rootCallReceipt, rootWarnings, type GovernedCostReceipt, type OperationAccountingStore, type RootCallReceipt, type RootFinancialSummary } from \"@alma-harness/execution\";\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from \"@alma-harness/postgres\";\nimport type { Pool, PoolClient } from \"pg\";\nimport { ROOT, record, call, type RootRow, type CallRow } from \"./rows\";\ninterface FinancialRow { root_id: string; call_id: string; settlement_id: string; accounting_ordinal: number; reservation_ordinal: number; cost_usd: number; previous_usd: number; current_usd: number; decisions: unknown; new_warnings: string[]; recorded_at: Date }\nfunction receipt(r: FinancialRow): RootCallReceipt { return normalizeRootCallReceipt({ rootId: r.root_id, callId: r.call_id, settlementId: r.settlement_id, accountingOrdinal: r.accounting_ordinal, reservationOrdinal: r.reservation_ordinal, costUsd: r.cost_usd, previousUsd: r.previous_usd, currentUsd: r.current_usd, decisions: r.decisions, newWarnings: r.new_warnings, recordedAt: r.recorded_at.toISOString() }); }\nexport class PostgresOperationAccountingStore implements OperationAccountingStore {\n readonly #role: string | null; readonly #timeout: number | null;\n constructor(readonly pool: Pool, opts: ScopedStoreOptions = {}) { this.#role = resolveRlsRole(opts); this.#timeout = resolveStatementTimeout(opts); }\n async #scope<T>(scope: Scope, fn: (c: PoolClient) => Promise<T>): Promise<T> {\n try { return await inScope(this.pool, this.#role, scope, fn, this.#timeout); }\n catch (e) { if ([\"23505\", \"23503\", \"23514\"].includes((e as { code?: string }).code ?? \"\")) throw new ExecutionConflictError(); throw e; }\n }\n async #root(c: PoolClient, s: Scope, k: string, write: boolean): Promise<RootRow | undefined> {\n return (await c.query<RootRow>(`select ${ROOT} from alma_operation_roots where org=$1 and uid=$2 and key=$3 for ${write ? \"update\" : \"share\"}`, [s.org, s.uid, k])).rows[0];\n }\n async record(scope: Scope, rootKey: string, callId: string) {\n const s = settlementScope(scope), k = id(rootKey), identity = id(callId);\n return this.#scope(s, async c => {\n const root = await this.#root(c, s, k, true); if (!root) throw new ExecutionStateError();\n const args = [s.org, s.uid, root.id];\n const old = (await c.query<FinancialRow>(\"select * from alma_operation_financial_calls where org=$1 and uid=$2 and root_id=$3 and call_id=$4\", [...args, identity])).rows[0];\n if (old) return { status: \"replayed\" as const, receipt: receipt(old) };\n const row = (await c.query<CallRow>(\"select * from alma_operation_calls where org=$1 and uid=$2 and root_id=$3 and call_id=$4\", [...args, identity])).rows[0];\n if (!row) throw new ExecutionStateError(); const member = call(row);\n const cost = (await c.query<{ id: string; request: unknown; decisions: unknown; settlement_payload: unknown; settlement_session_usd: number; settlement_day_usd: number }>(`select c.id,c.settlement_payload,c.settlement_session_usd,c.settlement_day_usd,g.request,g.decisions\n from alma_audit_cost c left join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where c.org=$1 and c.uid=$2 and c.settlement_id=$3 and c.settlement_governed`, [s.org, s.uid, member.input.execution.settlementId])).rows[0];\n if (!cost) return { status: \"pending\" as const };\n const source: GovernedCostReceipt = normalizeGovernedCostReceipt({ request: cost.request, decisions: cost.decisions, receipt: { settlement: cost.settlement_payload, totals: { sessionUsd: cost.settlement_session_usd, tenantDayUsd: cost.settlement_day_usd } } });\n const last = (await c.query<FinancialRow>(\"select * from alma_operation_financial_calls where org=$1 and uid=$2 and root_id=$3 order by accounting_ordinal desc limit 1\", args)).rows[0];\n const warned = (await c.query<{ cap: RootCallReceipt[\"newWarnings\"][number] }>(\"select cap from alma_operation_warnings where org=$1 and uid=$2 and root_id=$3\", args)).rows.map(r => r.cap);\n const now = (await c.query<{ at: Date }>(\"select clock_timestamp() at\")).rows[0]!.at.toISOString();\n const value = rootCallReceipt(record(root).input, member, source, last ? receipt(last) : undefined, warned, now);\n const saved = (await c.query<FinancialRow>(`insert into alma_operation_financial_calls(org,uid,root_id,call_id,settlement_id,cost_id,accounting_ordinal,reservation_ordinal,cost_usd,previous_usd,current_usd,decisions,new_warnings,recorded_at)\n values($1,$2,$3,$4,$5,$6::uuid,$7,$8,$9,$10,$11,$12::jsonb,$13::text[],$14::timestamptz) returning *`, [...args, value.callId, value.settlementId, cost.id, value.accountingOrdinal, value.reservationOrdinal, value.costUsd, value.previousUsd, value.currentUsd, JSON.stringify(value.decisions), value.newWarnings, value.recordedAt])).rows[0]!;\n return { status: \"applied\" as const, receipt: receipt(saved) };\n });\n }\n async get(scope: Scope, rootKey: string): Promise<RootFinancialSummary | null> {\n const s = settlementScope(scope), k = id(rootKey);\n return this.#scope(s, async c => {\n const root = await this.#root(c, s, k, false); if (!root) return null;\n const args = [s.org, s.uid, root.id], last = (await c.query<FinancialRow>(\"select * from alma_operation_financial_calls where org=$1 and uid=$2 and root_id=$3 order by accounting_ordinal desc limit 1\", args)).rows[0];\n const rows = (await c.query<FinancialRow & { cap: string }>(`select f.*,w.cap from alma_operation_warnings w join alma_operation_financial_calls f on (f.org,f.uid,f.root_id,f.call_id)=(w.org,w.uid,w.root_id,w.call_id)\n where w.org=$1 and w.uid=$2 and w.root_id=$3 order by f.accounting_ordinal,w.cap`, args)).rows;\n const warnings = rows.map(r => { const found = rootWarnings(s, receipt(r)).find(w => w.cap === r.cap); if (!found) throw new ExecutionConflictError(); return found; });\n return { rootId: root.id, costUsd: last ? receipt(last).currentUsd : 0, reservedCalls: root.call_count, settledCalls: last?.accounting_ordinal ?? 0, rootStatus: root.status, warnings };\n });\n }\n async list(scope: Scope, rootKey: string, query?: { afterOrdinal?: number; limit?: number }): Promise<RootCallReceipt[]> {\n const s = settlementScope(scope), k = id(rootKey), q = operationCallQuery(query);\n return this.#scope(s, async c => (await c.query<FinancialRow>(`select f.* from alma_operation_financial_calls f join alma_operation_roots r on (r.org,r.uid,r.id)=(f.org,f.uid,f.root_id)\n where r.org=$1 and r.uid=$2 and r.key=$3 and f.accounting_ordinal>$4 order by f.accounting_ordinal limit $5`, [s.org, s.uid, k, q.afterOrdinal, q.limit])).rows.map(receipt));\n }\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from \"pg\";\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, governedCostSettlementStoreMigrationSql, rlsPolicySql } from \"@alma-harness/postgres\";\nimport { operationTreeMigrationSql } from \"./schema\";\nexport function operationAccountingMigrationSql(role = DEFAULT_RLS_ROLE): string {\n assertRoleIdentifier(role);\n return `${operationTreeMigrationSql(role)}${governedCostSettlementStoreMigrationSql(role)}\ncreate table if not exists alma_operation_financial_calls (\n org text not null, uid text not null, root_id text not null, call_id text not null, settlement_id text not null, cost_id uuid not null,\n accounting_ordinal int not null check(accounting_ordinal between 1 and 512), reservation_ordinal int not null check(reservation_ordinal between 1 and 512),\n cost_usd double precision not null, previous_usd double precision not null, current_usd double precision not null,\n decisions jsonb not null, new_warnings text[] not null, recorded_at timestamptz not null,\n primary key(org,uid,root_id,call_id), unique(org,uid,root_id,accounting_ordinal), unique(org,uid,root_id,settlement_id),\n foreign key(org,uid,root_id,call_id) references alma_operation_calls(org,uid,root_id,call_id),\n foreign key(org,uid,cost_id) references alma_audit_cost(org,uid,id),\n check(cost_usd>=0 and cost_usd<'Infinity'::float8 and previous_usd>=0 and previous_usd<'Infinity'::float8 and current_usd=previous_usd+cost_usd and current_usd<'Infinity'::float8),\n check(jsonb_typeof(decisions)='array' and jsonb_array_length(decisions)<=3),\n check(cardinality(new_warnings)<=3 and new_warnings<@array['perTurnUsd','perSessionUsd','perTenantDayUsd']::text[])\n);\ncreate table if not exists alma_operation_warnings (\n org text not null, uid text not null, root_id text not null, cap text not null check(cap in ('perTurnUsd','perSessionUsd','perTenantDayUsd')), call_id text not null,\n primary key(org,uid,root_id,cap), foreign key(org,uid,root_id,call_id) references alma_operation_financial_calls(org,uid,root_id,call_id)\n);\ncreate or replace function alma_operation_financial_validate() returns trigger language plpgsql as $financial$\ndeclare root alma_operation_roots%rowtype; member alma_operation_calls%rowtype; previous alma_operation_financial_calls%rowtype;\n source record; expected jsonb; warnings text[]; field text;\nbegin\n select * into root from alma_operation_roots where org=new.org and uid=new.uid and id=new.root_id for update;\n select * into member from alma_operation_calls where org=new.org and uid=new.uid and root_id=new.root_id and call_id=new.call_id;\n select * into previous from alma_operation_financial_calls where org=new.org and uid=new.uid and root_id=new.root_id order by accounting_ordinal desc limit 1;\n select c.settlement_payload payload,g.request,g.decisions into source from alma_audit_cost c join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where c.org=new.org and c.uid=new.uid and c.id=new.cost_id and c.settlement_governed;\n if (root.id is not null and member.call_id is not null and source.payload is not null\n and new.reservation_ordinal=member.ordinal and new.accounting_ordinal=coalesce(previous.accounting_ordinal,0)+1\n and new.previous_usd=coalesce(previous.current_usd,0) and new.cost_usd=(source.payload->>'costUsd')::float8\n and source.payload->>'callId'=new.call_id and source.payload->>'id'=new.settlement_id\n and source.payload->>'id'=member.input->>'settlementId' and source.payload->'scope'=member.input->'scope'\n and source.payload->'model'=member.input->'model' and source.payload->>'at'=member.input->>'occurredAt'\n and source.payload->'consumers'=member.input->'governance'->'consumers' and source.request->>'policyVersion'=root.policy_version and source.request->'caps'=root.caps\n and (not(source.payload ? 'parentCallId') or source.payload->>'parentCallId'=member.parent_call_id)) is not true then\n raise exception 'Invalid root financial association' using errcode='23514';\n end if;\n foreach field in array array['sessionId','operationId','attemptId','priceVersion'] loop\n if (source.payload->>field=member.input->>field) is not true then raise exception 'Invalid root financial binding' using errcode='23514'; end if;\n end loop;\n select coalesce(jsonb_agg(case when d->>'cap'='perTurnUsd' then d || jsonb_build_object('previousUsd',new.previous_usd,'currentUsd',new.current_usd,'exceeded',new.current_usd>(d->>'thresholdUsd')::float8) else d end order by n),'[]'::jsonb)\n into expected from jsonb_array_elements(source.decisions) with ordinality as x(d,n);\n if new.decisions<>expected then raise exception 'Invalid root financial decisions' using errcode='23514'; end if;\n select coalesce(array_agg(d->>'cap' order by n),array[]::text[]) into warnings from jsonb_array_elements(expected) with ordinality as x(d,n)\n where d->>'onExceeded'='warn' and (d->>'exceeded')::boolean and not exists(select from alma_operation_warnings w where w.org=new.org and w.uid=new.uid and w.root_id=new.root_id and w.cap=d->>'cap');\n if new.new_warnings<>warnings then raise exception 'Invalid root financial warnings' using errcode='23514'; end if;\n return new;\nend $financial$;\ncreate or replace function alma_operation_financial_warn() returns trigger language plpgsql as $warnings$\ndeclare cap text;\nbegin\n foreach cap in array new.new_warnings loop insert into alma_operation_warnings(org,uid,root_id,cap,call_id) values(new.org,new.uid,new.root_id,cap,new.call_id); end loop;\n return new;\nend $warnings$;\ncreate or replace function alma_operation_warning_validate() returns trigger language plpgsql as $validate$\nbegin\n if not exists(select from alma_operation_financial_calls f where f.org=new.org and f.uid=new.uid and f.root_id=new.root_id and f.call_id=new.call_id and new.cap=any(f.new_warnings)) then\n raise exception 'Invalid root warning association' using errcode='23514';\n end if; return new;\nend $validate$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_financial_calls'::regclass and tgname='alma_operation_financial_validate') then\n create trigger alma_operation_financial_validate before insert on alma_operation_financial_calls for each row execute function alma_operation_financial_validate();\n create trigger alma_operation_financial_warn after insert on alma_operation_financial_calls for each row execute function alma_operation_financial_warn();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_operation_warnings'::regclass and tgname='alma_operation_warning_validate') then\n create trigger alma_operation_warning_validate before insert on alma_operation_warnings for each row execute function alma_operation_warning_validate();\n end if;\nend $triggers$;\n${rlsPolicySql(\"alma_operation_financial_calls\")}${rlsPolicySql(\"alma_operation_warnings\")}\ngrant select,insert on alma_operation_financial_calls,alma_operation_warnings to ${role};\n${functionPathSql(\"alma_operation_financial_validate()\",\"alma_operation_financial_warn()\",\"alma_operation_warning_validate()\")}\n`;\n}\nexport async function migrateOperationAccountingStore(pool: Pool, opts: { role?: string } = {}): Promise<void> { await pool.query(operationAccountingMigrationSql(opts.role)); }\n","import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementLimit, settlementScope, type Scope } from \"@alma-harness/core\";\nimport { checkOperationDeadline, normalizeOperationRoot, normalizeOperationSessionFence, operationCallQuery, type OperationRootInput, type OperationSessionClaim, type OperationSessionFence, type OperationSessionRecord, type OperationSessionStore } from \"@alma-harness/execution\";\nimport { assertRoleIdentifier, DEFAULT_RETENTION_ROLE, inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from \"@alma-harness/postgres\";\nimport type { Pool, PoolClient } from \"pg\";\ninterface Row { input: OperationRootInput; token: string; ordinal: string; status: OperationSessionRecord[\"status\"]; created_at: Date; updated_at: Date; resolution_id: string | null }\nconst record = (r: Row): OperationSessionRecord => ({ input: normalizeOperationRoot(r.input), ordinal: Number(r.ordinal), status: r.status, createdAt: r.created_at.toISOString(), updatedAt: r.updated_at.toISOString(), ...(r.resolution_id === null ? {} : { resolutionId: r.resolution_id }) });\nexport class PostgresOperationSessionStore implements OperationSessionStore {\n readonly #role: string | null; readonly #operator: string; readonly #timeout: number | null;\n constructor(readonly pool: Pool, opts: ScopedStoreOptions & { operatorRole?: string } = {}) {\n this.#role = resolveRlsRole(opts); this.#timeout = resolveStatementTimeout(opts);\n this.#operator = opts.operatorRole ?? DEFAULT_RETENTION_ROLE; assertRoleIdentifier(this.#operator);\n if (this.#role === this.#operator) throw new TypeError(\"Admission operator must have a separate role\");\n }\n async #scope<T>(s: Scope, fn: (c: PoolClient) => Promise<T>, operator = false): Promise<T> {\n try { return await inScope(this.pool, operator ? this.#operator : this.#role, s, fn, this.#timeout); }\n catch (e) { const code = (e as { code?: string }).code; if (code === \"23505\") throw new ExecutionConflictError(); if (code === \"23514\" || code === \"23503\") throw new ExecutionStateError(); throw e; }\n }\n async #read(c: PoolClient, s: Scope, k: string, lock = false): Promise<Row | undefined> {\n return (await c.query<Row>(`select * from alma_operation_admissions where org=$1 and uid=$2 and root_key=$3${lock ? \" for update\" : \"\"}`, [s.org, s.uid, k])).rows[0];\n }\n async #lock(c: PoolClient, s: Scope, sessionId: string) {\n await c.query(\"select session_id from alma_operation_sessions where org=$1 and uid=$2 and session_id=$3 for update\", [s.org, s.uid, sessionId]);\n }\n async claim(value: OperationRootInput): Promise<OperationSessionClaim> {\n const i = normalizeOperationRoot(value);\n return this.#scope(i.scope, async c => {\n await c.query(\"insert into alma_operation_sessions(org,uid,session_id) values($1,$2,$3) on conflict do nothing\", [i.scope.org, i.scope.uid, i.sessionId]);\n await this.#lock(c, i.scope, i.sessionId);\n const old = await this.#read(c, i.scope, i.key);\n if (old) { if (!equalExecution(old.input, i)) throw new ExecutionConflictError(); return { status: \"existing\", record: record(old) }; }\n if ((await c.query(\"select 1 from alma_operation_admissions where org=$1 and uid=$2 and root_id=$3\", [i.scope.org, i.scope.uid, i.id])).rowCount) throw new ExecutionConflictError();\n const occupied = (await c.query<Row>(\"select * from alma_operation_admissions where org=$1 and uid=$2 and session_id=$3 and status<>'released'\", [i.scope.org, i.scope.uid, i.sessionId])).rows[0];\n if (occupied) return { status: \"busy\", rootKey: occupied.input.key, rootId: occupied.input.id };\n const at = (await c.query<{ at: Date }>(\"select clock_timestamp() at\")).rows[0]!.at.toISOString(); checkOperationDeadline(i, at);\n const token = crypto.randomUUID();\n const row = (await c.query<Row>(`insert into alma_operation_admissions(org,uid,root_key,root_id,session_id,input,deadline_at,token,ordinal,status,created_at,updated_at)\n values($1,$2,$3,$4,$5,$6::jsonb,$7,$8,(select coalesce(max(ordinal),0)+1 from alma_operation_admissions where org=$1 and uid=$2 and session_id=$5),'active',clock_timestamp(),clock_timestamp()) returning *`,\n [i.scope.org, i.scope.uid, i.key, i.id, i.sessionId, JSON.stringify(i), i.deadlineAt, token])).rows[0]!;\n return { status: \"claimed\", record: record(row), fence: { scope: { ...i.scope }, sessionId: i.sessionId, rootKey: i.key, token } };\n });\n }\n async get(scope: Scope, rootKey: string) {\n const s = settlementScope(scope), k = id(rootKey);\n return this.#scope(s, async c => { const r = await this.#read(c, s, k); return r ? record(r) : null; });\n }\n async list(scope: Scope, sessionId: string, query?: { afterOrdinal?: number; limit?: number }) {\n const s = settlementScope(scope), session = id(sessionId), q = operationCallQuery(query);\n return this.#scope(s, async c => (await c.query<Row>(\"select * from alma_operation_admissions where org=$1 and uid=$2 and session_id=$3 and ordinal>$4 order by ordinal limit $5\", [s.org, s.uid, session, q.afterOrdinal, q.limit])).rows.map(record));\n }\n async #owner(value: OperationSessionFence, finish: boolean): Promise<OperationSessionRecord> {\n const f = normalizeOperationSessionFence(value);\n return this.#scope(f.scope, async c => {\n await this.#lock(c, f.scope, f.sessionId);\n const r = await this.#read(c, f.scope, f.rootKey, true);\n if (!r || r.token !== f.token || r.input.sessionId !== f.sessionId) throw new ExecutionStateError();\n if (finish) {\n if (r.status === \"released\" && r.resolution_id === null) return record(r);\n if (r.status !== \"active\") throw new ExecutionStateError();\n } else if (r.status !== \"active\") return record(r);\n await c.query(\"select set_config('alma.operation_admission_token',$1,true)\", [f.token]);\n return record((await c.query<Row>(\"update alma_operation_admissions set status=$4 where org=$1 and uid=$2 and root_key=$3 returning *\", [f.scope.org, f.scope.uid, f.rootKey, finish ? \"released\" : \"reconciliation_required\"])).rows[0]!);\n });\n }\n finish(fence: OperationSessionFence) { return this.#owner(fence, true); }\n markUncertain(fence: OperationSessionFence) { return this.#owner(fence, false); }\n async reconcileExpired(scope: Scope, opts: { limit?: number } = {}) {\n const s = settlementScope(scope), limit = settlementLimit(opts.limit);\n return this.#scope(s, async c => {\n const sessions = (await c.query<{ session_id: string }>(`select session_id from alma_operation_sessions s where org=$1 and uid=$2\n and exists(select from alma_operation_admissions a where (a.org,a.uid,a.session_id)=(s.org,s.uid,s.session_id) and status='active' and deadline_at<=clock_timestamp())\n order by session_id limit $3 for update of s skip locked`, [s.org, s.uid, limit])).rows;\n const records: OperationSessionRecord[] = [];\n for (const row of sessions) records.push(...(await c.query<Row>(\"update alma_operation_admissions set status='reconciliation_required' where org=$1 and uid=$2 and session_id=$3 and status='active' and deadline_at<=clock_timestamp() returning *\", [s.org, s.uid, row.session_id])).rows.map(record));\n return records;\n });\n }\n async resolve(scope: Scope, rootKey: string, opts: { resolutionId: string }) {\n const s = settlementScope(scope), k = id(rootKey), resolutionId = id(opts.resolutionId);\n return this.#scope(s, async c => {\n const meta = await this.#read(c, s, k); if (!meta) throw new ExecutionStateError();\n await this.#lock(c, s, meta.input.sessionId); const r = (await this.#read(c, s, k, true))!;\n if (r.status === \"released\") { if (r.resolution_id !== resolutionId) throw new ExecutionConflictError(); return record(r); }\n if (r.status !== \"reconciliation_required\") throw new ExecutionStateError();\n return record((await c.query<Row>(\"update alma_operation_admissions set status='released',resolution_id=$4 where org=$1 and uid=$2 and root_key=$3 returning *\", [s.org, s.uid, k, resolutionId])).rows[0]!);\n }, true);\n }\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from \"pg\";\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, DEFAULT_RETENTION_ROLE, rlsPolicySql, roleBootstrapSql } from \"@alma-harness/postgres\";\nimport { operationTreeMigrationSql } from \"./schema\";\nimport { operationRequestAdmissionSql } from \"./request-schema\";\nexport function operationSessionMigrationSql(role = DEFAULT_RLS_ROLE, operatorRole = DEFAULT_RETENTION_ROLE): string {\n assertRoleIdentifier(role); assertRoleIdentifier(operatorRole);\n if (role === operatorRole) throw new TypeError(\"Admission operator must have a separate role\");\n return `${operationTreeMigrationSql(role)}${roleBootstrapSql(operatorRole)}\ncreate table if not exists alma_operation_sessions (\n org text not null, uid text not null, session_id text not null,\n primary key(org,uid,session_id),\n check(org ~ '^[!-~]{1,200}$' and uid ~ '^[!-~]{1,200}$' and session_id ~ '^[!-~]{1,200}$')\n);\ncreate or replace function alma_admission_input(v jsonb) returns boolean language plpgsql immutable as $shape$\ndeclare item record;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['scope','key','id','sessionId','policyVersion','caps','maxSensitivity','deadlineAt','maxCalls']\n and (v-array['scope','key','id','sessionId','policyVersion','caps','maxSensitivity','deadlineAt','maxCalls'])='{}'::jsonb\n and jsonb_typeof(v->'scope')='object' and ((v->'scope')-'org'-'uid')='{}'::jsonb\n and jsonb_typeof(v->'maxCalls')='number' and (v->>'maxCalls')::numeric between 1 and 512\n and trunc((v->>'maxCalls')::numeric)=(v->>'maxCalls')::numeric\n and v->>'maxSensitivity' in ('public','internal','personal','health')\n and jsonb_typeof(v->'deadlineAt')='string' and v->>'deadlineAt' ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{3}Z$'\n and isfinite((v->>'deadlineAt')::timestamptz) and alma_operation_caps(v->'caps')) is not true then return false; end if;\n for item in select value from jsonb_each(v->'scope') union all select value from jsonb_each(v) where key in ('key','id','sessionId','policyVersion') loop\n if (jsonb_typeof(item.value)='string' and (item.value#>>'{}') ~ '^[!-~]{1,200}$') is not true then return false; end if;\n end loop;\n if not (v->'scope' ?& array['org','uid']) then return false; end if;\n for item in select value from jsonb_each(v->'caps') loop\n if (item.value->>'usd')::numeric > 1.7976931348623157e308 then return false; end if;\n end loop;\n return true;\nexception when others then return false;\nend $shape$;\ncreate table if not exists alma_operation_admissions (\n org text not null, uid text not null, root_key text not null, root_id text not null,\n session_id text not null, input jsonb not null, deadline_at timestamptz not null,\n token text not null check(token ~ '^[!-~]{1,200}$'),\n ordinal bigint not null check(ordinal between 1 and 9007199254740991),\n status text not null check(status in ('active','reconciliation_required','released')),\n created_at timestamptz not null, updated_at timestamptz not null,\n resolution_id text check(resolution_id ~ '^[!-~]{1,200}$'),\n primary key(org,uid,root_key), unique(org,uid,root_id), unique(org,uid,session_id,ordinal),\n foreign key(org,uid,session_id) references alma_operation_sessions(org,uid,session_id),\n check((alma_admission_input(input) and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid\n and input->>'key'=root_key and input->>'id'=root_id and input->>'sessionId'=session_id\n and (input->>'deadlineAt')::timestamptz=deadline_at) is true),\n check(resolution_id is null or status='released')\n);\ncreate unique index if not exists alma_admission_occupancy on alma_operation_admissions(org,uid,session_id) where status<>'released';\ncreate or replace function alma_session_lock_immutable() returns trigger language plpgsql as $lock$\nbegin\n if new is distinct from old then raise exception 'Immutable session identity' using errcode='23514'; end if;\n return new;\nend $lock$;\ncreate or replace function alma_admission_transition() returns trigger language plpgsql as $transition$\ndeclare owner boolean; expected bigint;\nbegin\n perform from alma_operation_sessions where org=new.org and uid=new.uid and session_id=new.session_id for update;\n if tg_op='INSERT' then\n select coalesce(max(ordinal),0)+1 into expected from alma_operation_admissions where org=new.org and uid=new.uid and session_id=new.session_id;\n if (new.status='active' and new.resolution_id is null and new.ordinal=expected\n and new.deadline_at>clock_timestamp() and new.deadline_at<=clock_timestamp()+interval '1 hour') is not true then\n raise exception 'Invalid admission' using errcode='23514';\n end if;\n new.created_at=clock_timestamp(); new.updated_at=new.created_at; return new;\n end if;\n if (new.org,new.uid,new.root_key,new.root_id,new.session_id,new.input,new.deadline_at,new.token,new.ordinal,new.created_at)\n is distinct from (old.org,old.uid,old.root_key,old.root_id,old.session_id,old.input,old.deadline_at,old.token,old.ordinal,old.created_at) then\n raise exception 'Immutable admission binding' using errcode='23514';\n end if;\n owner=coalesce(current_setting('alma.operation_admission_token',true)=old.token,false);\n if not (\n (old.status='active' and new.status='released' and new.resolution_id is null and owner and old.deadline_at>clock_timestamp())\n or (old.status='active' and new.status='reconciliation_required' and new.resolution_id is null and (owner or old.deadline_at<=clock_timestamp()))\n or (old.status='reconciliation_required' and new.status='released' and new.resolution_id is not null and pg_has_role(current_user,'${operatorRole}','MEMBER'))\n ) then raise exception 'Invalid admission transition' using errcode='23514'; end if;\n new.updated_at=clock_timestamp(); return new;\nend $transition$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_operation_sessions'::regclass and tgname='alma_session_lock_immutable') then\n create trigger alma_session_lock_immutable before update on alma_operation_sessions for each row execute function alma_session_lock_immutable();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_operation_admissions'::regclass and tgname='alma_admission_transition') then\n create trigger alma_admission_transition before insert or update on alma_operation_admissions for each row execute function alma_admission_transition();\n end if;\nend $triggers$;\n${rlsPolicySql(\"alma_operation_sessions\")}${rlsPolicySql(\"alma_operation_admissions\")}\ngrant select,insert,update on alma_operation_sessions to ${role};\ngrant select,update on alma_operation_sessions to ${operatorRole};\ngrant select,insert,update on alma_operation_admissions to ${role};\ngrant select,update on alma_operation_admissions to ${operatorRole};\n${operationRequestAdmissionSql}\n${functionPathSql(\"alma_admission_input(jsonb)\",\"alma_admission_transition()\")}\n`;\n}\nexport async function migrateOperationSessionStore(pool: Pool, opts: { role?: string; operatorRole?: string } = {}): Promise<void> {\n await pool.query(operationSessionMigrationSql(opts.role, opts.operatorRole));\n}\n","import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementScope, type JobHandle, type Scope } from '@alma-harness/core';\nimport { batchQuery, normalizeBatchSummary, bindBatchHandle, checkBatchDeadline, normalizeBatchFence, normalizeBatchHandle, normalizeBatchRecord, normalizeBatchSubmission, type BatchSubmissionFence, type BatchSubmissionInput, type BatchSubmissionRecord, type BatchSubmissionStore } from '@alma-harness/execution';\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from '@alma-harness/postgres';\nimport type { Pool,PoolClient } from 'pg';\ninterface Row {input:BatchSubmissionInput;state:BatchSubmissionRecord['state'];token:string;created_at:Date;updated_at:Date;dispatched_at:Date|null;accepted_at:Date|null;handle:JobHandle|null}\nconst record=(r:Row)=>normalizeBatchRecord({input:r.input,state:r.state,createdAt:r.created_at.toISOString(),updatedAt:r.updated_at.toISOString(),...(r.dispatched_at?{dispatchedAt:r.dispatched_at.toISOString()}:{}),...(r.accepted_at?{acceptedAt:r.accepted_at.toISOString(),handle:r.handle}:{})});\nexport class PostgresBatchSubmissionStore implements BatchSubmissionStore {\n readonly #role:string|null;readonly #timeout:number|null;\n constructor(readonly pool:Pool,opts:ScopedStoreOptions={}){this.#role=resolveRlsRole(opts);this.#timeout=resolveStatementTimeout(opts);}\n async #scope<T>(s:Scope,fn:(c:PoolClient)=>Promise<T>):Promise<T>{try{return await inScope(this.pool,this.#role,s,fn,this.#timeout);}catch(e){const code=(e as {code?:string}|null)?.code;const mapped=code==='23505'?new ExecutionConflictError():code==='23514'||code==='23503'?new ExecutionStateError():undefined;if(mapped)throw Object.defineProperty(mapped,'cause',{value:e,writable:true,configurable:true});throw e;}}\n async #read(c:PoolClient,s:Scope,k:string,lock=false){return (await c.query<Row>(`select * from alma_batch_submissions where org=$1 and uid=$2 and key=$3${lock?' for update':''}`,[s.org,s.uid,k])).rows[0];}\n async claim(value:BatchSubmissionInput){const input=normalizeBatchSubmission(value);let insertConflict:unknown;\n try{return await this.#scope(input.scope,async c=>{\n let row=await this.#read(c,input.scope,input.key,true);\n if(!row){const at=(await c.query<{at:Date}>('select clock_timestamp() at')).rows[0]!.at.toISOString();checkBatchDeadline(input,at);\n try{row=(await c.query<Row>(`insert into alma_batch_submissions(org,uid,key,id,input,state,token,created_at,updated_at) values($1,$2,$3,$4,$5::jsonb,'prepared',$6,clock_timestamp(),clock_timestamp()) on conflict(org,uid,key) do nothing returning *`,[input.scope.org,input.scope.uid,input.key,input.id,JSON.stringify(input),crypto.randomUUID()])).rows[0];}\n catch(e){if((e as {code?:string}|null)?.code==='23505')insertConflict=e;throw e;}\n if(row)return {status:'claimed' as const,record:record(row),fence:{scope:{...input.scope},key:input.key,id:input.id,token:row.token}};\n row=await this.#read(c,input.scope,input.key,true);\n }\n if(!row||!equalExecution(record(row).input,input))throw new ExecutionConflictError();return {status:'existing' as const,record:record(row)};\n });}catch(e){\n if(!insertConflict||!(e instanceof ExecutionConflictError)||e.cause!==insertConflict)throw e;\n // DECISION: uniqueness outside the ON CONFLICT arbiter can lose an identical\n // claim. Cleanup has finished; a fresh scoped read grants observation only.\n return this.#scope(input.scope,async c=>{const row=await this.#read(c,input.scope,input.key);if(!row)throw e;const existing=record(row);if(!equalExecution(existing.input,input))throw e;return {status:'existing' as const,record:existing};});\n }}\n async #owner<T>(value:BatchSubmissionFence,fn:(c:PoolClient,r:Row,f:BatchSubmissionFence)=>Promise<T>){const f=normalizeBatchFence(value);return this.#scope(f.scope,async c=>{const r=await this.#read(c,f.scope,f.key,true);if(!r||r.token!==f.token||r.input.id!==f.id)throw new ExecutionStateError();await c.query(\"select set_config('alma.batch_token',$1,true)\",[f.token]);return fn(c,r,f);});}\n async beginDispatch(fence:BatchSubmissionFence){return this.#owner(fence,async(c,r,f)=>{\n if(r.state!=='prepared')return {dispatch:false,record:record(r)};\n const row=(await c.query<Row>(\"update alma_batch_submissions set state='dispatching' where org=$1 and uid=$2 and key=$3 returning *\",[f.scope.org,f.scope.uid,f.key])).rows[0]!;\n return {dispatch:true,record:record(row)};\n });}\n async accept(value:BatchSubmissionFence,raw:JobHandle){const f=normalizeBatchFence(value),handle=normalizeBatchHandle(raw);return this.#owner(f,async(c,r)=>{\n bindBatchHandle(record(r).input,handle);if(r.handle){if(!equalExecution(r.handle,handle))throw new ExecutionConflictError();return record(r);}if(!r.dispatched_at)throw new ExecutionStateError();\n return record((await c.query<Row>(`update alma_batch_submissions set handle=$4::jsonb,state=case when state='dispatching' and (input->>'submitDeadlineAt')::timestamptz>clock_timestamp() then 'submitted' else 'reconciliation_required' end where org=$1 and uid=$2 and key=$3 returning *`,[f.scope.org,f.scope.uid,f.key,JSON.stringify(handle)])).rows[0]!);\n });}\n async markUncertain(fence:BatchSubmissionFence){return this.#owner(fence,async(c,r,f)=>r.state==='reconciliation_required'?record(r):record((await c.query<Row>(\"update alma_batch_submissions set state='reconciliation_required' where org=$1 and uid=$2 and key=$3 returning *\",[f.scope.org,f.scope.uid,f.key])).rows[0]!));}\n async get(scope:Scope,identity:string){const s=settlementScope(scope),k=id(identity);return this.#scope(s,async c=>{const r=await this.#read(c,s,k);return r?record(r):null;});}\n async list(scope:Scope,query?:{afterKey?:string;limit?:number}){const s=settlementScope(scope),q=batchQuery(query);return this.#scope(s,async c=>(await c.query<Omit<Row,'input'|'token'>&{key:string;id:string;session_id:string;deadline:string;item_count:number}>(`select key,id,input->>'sessionId' session_id,input->>'submitDeadlineAt' deadline,jsonb_array_length(input->'items') item_count,state,created_at,updated_at,dispatched_at,accepted_at,handle from alma_batch_submissions where org=$1 and uid=$2 and ($3::text is null or key>$3 collate \"C\") order by key limit $4`,[s.org,s.uid,q.afterKey??null,q.limit])).rows.map(r=>normalizeBatchSummary({key:r.key,id:r.id,sessionId:r.session_id,submitDeadlineAt:r.deadline,itemCount:r.item_count,state:r.state,createdAt:r.created_at.toISOString(),updatedAt:r.updated_at.toISOString(),...(r.dispatched_at?{dispatchedAt:r.dispatched_at.toISOString()}:{}),...(r.accepted_at?{acceptedAt:r.accepted_at.toISOString(),handle:r.handle}:{})})));}\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from 'pg';\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, executionStoreMigrationSql, rlsPolicySql } from '@alma-harness/postgres';\nexport function batchSubmissionMigrationSql(role=DEFAULT_RLS_ROLE):string {\n assertRoleIdentifier(role);\n return `${executionStoreMigrationSql(role)}\ncreate or replace function alma_batch_input_v1(v jsonb) returns boolean language plpgsql immutable as $shape$\ndeclare item jsonb; e jsonb; first jsonb; field text;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['scope','key','id','sessionId','configRevision','submitDeadlineAt','items']\n and (v-array['scope','key','id','sessionId','configRevision','submitDeadlineAt','items'])='{}'::jsonb\n and jsonb_typeof(v->'scope')='object' and v->'scope' ?& array['org','uid'] and ((v->'scope')-'org'-'uid')='{}'::jsonb\n and jsonb_typeof(v->'items')='array' and jsonb_array_length(v->'items') between 1 and 512\n and octet_length(v::text)<=4194304) is not true then return false; end if;\n foreach field in array array['key','id','sessionId','configRevision'] loop\n if (jsonb_typeof(v->field)='string' and v->>field ~ '^[!-~]{1,200}$') is not true then return false; end if;\n end loop;\n first=v->'items'->0->'execution';\n for item in select value from jsonb_array_elements(v->'items') loop\n e=item->'execution';\n if (jsonb_typeof(item)='object' and item ?& array['id','execution'] and (item-'id'-'execution')='{}'::jsonb\n and jsonb_typeof(item->'id')='string' and item->>'id' ~ '^[!-~]{1,200}$'\n and alma_execution_shape_v2(jsonb_set(e,'{controls}',(e->'controls')-'temperature'),'input')\n and e ?& array['scope','operationKey','operationId','attemptId','callId','settlementId','sessionId','inputRevision','policyVersion','outputContractVersion','intent','model','requestedTier','priceVersion','prices','controls','occurredAt','deadlineAt','governance']\n and (not(e->'controls' ? 'temperature') or (jsonb_typeof(e->'controls'->'temperature')='number' and (e->'controls'->>'temperature')::numeric between 0 and 2))\n and e->'scope'=v->'scope' and e->>'sessionId'=v->>'sessionId' and e->>'requestedTier'='batch'\n and e->>'deadlineAt'=v->>'submitDeadlineAt' and e->'model'=first->'model'\n and e->>'policyVersion'=first->>'policyVersion' and e->'governance'->'caps'=first->'governance'->'caps') is not true then return false; end if;\n end loop; return true;\nexception when others then return false;\nend $shape$;\ncreate table if not exists alma_batch_submissions (\n org text not null,uid text not null,key text collate \"C\" not null,id text not null,input jsonb not null,\n state text not null check(state in ('prepared','dispatching','submitted','reconciliation_required')),\n token text not null check(token ~ '^[!-~]{1,200}$'),created_at timestamptz not null,updated_at timestamptz not null,\n dispatched_at timestamptz,accepted_at timestamptz,handle jsonb,\n primary key(org,uid,key),unique(org,uid,id),\n check((alma_batch_input_v1(input) and input->'scope'->>'org'=org and input->'scope'->>'uid'=uid and input->>'key'=key and input->>'id'=id) is true),\n check((handle is null)=(accepted_at is null)),\n check(handle is null or (jsonb_typeof(handle)='object' and handle ?& array['provider','id','model'] and (handle-'provider'-'id'-'model')='{}'::jsonb\n and jsonb_typeof(handle->'id')='string' and handle->>'id' ~ '^[!-~]{1,200}$'\n and handle->'model'=input->'items'->0->'execution'->'model' and handle->>'provider'=handle->'model'->>'provider') is true),\n check(state<>'prepared' or (dispatched_at is null and handle is null)),\n check(state<>'dispatching' or (dispatched_at is not null and handle is null)),\n check(state<>'submitted' or (handle is not null and accepted_at<(input->>'submitDeadlineAt')::timestamptz)),\n check(accepted_at is null or (dispatched_at is not null and accepted_at>=dispatched_at)),\n check(dispatched_at is null or (dispatched_at>=created_at and dispatched_at<(input->>'submitDeadlineAt')::timestamptz)),\n check(updated_at>=created_at and (accepted_at is null or updated_at>=accepted_at) and (dispatched_at is null or updated_at>=dispatched_at))\n);\ncreate table if not exists alma_batch_items (\n org text not null,uid text not null,batch_key text not null,ordinal int not null check(ordinal between 1 and 512),\n item_id text not null,operation_key text not null,operation_id text not null,call_id text not null,settlement_id text not null,\n primary key(org,uid,batch_key,ordinal),unique(org,uid,batch_key,item_id),\n unique(org,uid,operation_key),unique(org,uid,operation_id),unique(org,uid,call_id),unique(org,uid,settlement_id),\n foreign key(org,uid,batch_key) references alma_batch_submissions(org,uid,key)\n);\ncreate or replace function alma_batch_transition() returns trigger language plpgsql as $transition$\ndeclare at timestamptz; deadline timestamptz;\nbegin\n at=clock_timestamp();deadline=(new.input->>'submitDeadlineAt')::timestamptz;\n if tg_op='INSERT' then\n if (new.state='prepared' and new.dispatched_at is null and new.accepted_at is null and new.handle is null and deadline>at and deadline<=at+interval '1 hour') is not true then raise exception 'Invalid batch claim' using errcode='23514'; end if;\n new.created_at=at;new.updated_at=at;return new;\n end if;\n if (new.org,new.uid,new.key,new.id,new.input,new.token,new.created_at) is distinct from (old.org,old.uid,old.key,old.id,old.input,old.token,old.created_at)\n or coalesce(current_setting('alma.batch_token',true)=old.token,false) is not true then raise exception 'Invalid batch binding or fence' using errcode='23514'; end if;\n if old.state='prepared' and new.state='dispatching' and deadline>at and new.handle is null and new.accepted_at is null then\n new.dispatched_at=at;\n elsif old.handle is null and new.handle is not null and old.dispatched_at is not null\n and new.dispatched_at=old.dispatched_at and new.state in ('submitted','reconciliation_required') then\n new.state=case when old.state='dispatching' and deadline>at then 'submitted' else 'reconciliation_required' end;new.accepted_at=at;\n elsif old.state<>'reconciliation_required' and new.state='reconciliation_required' and (new.dispatched_at,new.accepted_at,new.handle) is not distinct from (old.dispatched_at,old.accepted_at,old.handle) then null;\n else raise exception 'Invalid batch transition' using errcode='23514';\n end if;\n new.updated_at=at;return new;\nend $transition$;\ncreate or replace function alma_batch_member() returns trigger language plpgsql as $member$\ndeclare item jsonb;\nbegin\n select input->'items'->(new.ordinal-1) into item from alma_batch_submissions where org=new.org and uid=new.uid and key=new.batch_key;\n if (item->>'id'=new.item_id and item->'execution'->>'operationKey'=new.operation_key and item->'execution'->>'operationId'=new.operation_id\n and item->'execution'->>'callId'=new.call_id and item->'execution'->>'settlementId'=new.settlement_id) is not true then raise exception 'Invalid batch member' using errcode='23514'; end if;return new;\nend $member$;\ncreate or replace function alma_batch_members() returns trigger language plpgsql as $members$\nbegin\n insert into alma_batch_items(org,uid,batch_key,ordinal,item_id,operation_key,operation_id,call_id,settlement_id)\n select new.org,new.uid,new.key,n,value->>'id',value->'execution'->>'operationKey',value->'execution'->>'operationId',value->'execution'->>'callId',value->'execution'->>'settlementId'\n from jsonb_array_elements(new.input->'items') with ordinality as x(value,n);return new;\nend $members$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_batch_submissions'::regclass and tgname='alma_batch_transition') then\n create trigger alma_batch_transition before insert or update on alma_batch_submissions for each row execute function alma_batch_transition();\n create trigger alma_batch_members after insert on alma_batch_submissions for each row execute function alma_batch_members();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_batch_items'::regclass and tgname='alma_batch_member') then\n create trigger alma_batch_member before insert on alma_batch_items for each row execute function alma_batch_member();\n end if;\nend $triggers$;\n${rlsPolicySql('alma_batch_submissions')}${rlsPolicySql('alma_batch_items')}\ngrant select,insert,update on alma_batch_submissions to ${role};\ngrant select,insert on alma_batch_items to ${role};\n${functionPathSql(\"alma_batch_input_v1(jsonb)\",\"alma_batch_member()\",\"alma_batch_members()\")}\n`;\n}\nexport async function migrateBatchSubmissionStore(pool:Pool,opts:{role?:string}={}):Promise<void>{await pool.query(batchSubmissionMigrationSql(opts.role));}\n","import { equalExecution, ExecutionConflictError, ExecutionStateError, settlementIdentifier as id, settlementScope, type Scope } from '@alma-harness/core';\nimport { batchUsageMember, batchUsageQuery, batchUsageSettlement, bindBatchUsageReceipt, normalizeBatchUsage, normalizeBatchUsageRecord, normalizeGovernedCostReceipt, type BatchUsageInput, type BatchUsageRecord, type BatchUsageQuery, type BatchUsageStore } from '@alma-harness/execution';\nimport { inScope, resolveRlsRole, resolveStatementTimeout, type ScopedStoreOptions } from '@alma-harness/postgres';\nimport type { Pool,PoolClient } from 'pg';\nimport { PostgresBatchSubmissionStore } from './batch';\ninterface Row {org:string;uid:string;batch_key:string;input:BatchUsageInput;execution:BatchUsageRecord['execution'];received_at:Date;cost_id:string|null;request:unknown;decisions:unknown;settlement_payload:unknown;settlement_session_usd:number;settlement_day_usd:number}\nconst select=`select u.*,b.input->'items'->(i.ordinal-1)->'execution' execution,c.settlement_payload,c.settlement_session_usd,c.settlement_day_usd,g.request,g.decisions\n from alma_batch_usage u join alma_batch_items i on (i.org,i.uid,i.batch_key,i.item_id)=(u.org,u.uid,u.batch_key,u.item_id)\n join alma_batch_submissions b on (b.org,b.uid,b.key)=(u.org,u.uid,u.batch_key)\n left join alma_audit_cost c on (c.org,c.uid,c.id)=(u.org,u.uid,u.cost_id)\n left join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)`;\nconst receipt=(r:Pick<Row,'request'|'decisions'|'settlement_payload'|'settlement_session_usd'|'settlement_day_usd'>)=>normalizeGovernedCostReceipt({request:r.request,decisions:r.decisions,receipt:{settlement:r.settlement_payload,totals:{sessionUsd:r.settlement_session_usd,tenantDayUsd:r.settlement_day_usd}}});\nconst record=(r:Row)=>normalizeBatchUsageRecord({scope:{org:r.org,uid:r.uid},batchKey:r.batch_key,input:r.input,execution:r.execution,receivedAt:r.received_at.toISOString(),...(r.cost_id?{receipt:receipt(r)}:{})});\nexport class PostgresBatchUsageStore implements BatchUsageStore {\n readonly #role:string|null;readonly #timeout:number|null;readonly #batches:PostgresBatchSubmissionStore;\n constructor(readonly pool:Pool,opts:ScopedStoreOptions={}){this.#role=resolveRlsRole(opts);this.#timeout=resolveStatementTimeout(opts);this.#batches=new PostgresBatchSubmissionStore(pool,opts);}\n async #scope<T>(s:Scope,fn:(c:PoolClient)=>Promise<T>):Promise<T>{try{return await inScope(this.pool,this.#role,s,fn,this.#timeout);}catch(e){if(['23505','23514','23503'].includes((e as {code?:string}).code??''))throw new ExecutionConflictError();throw e;}}\n async #read(c:PoolClient,s:Scope,k:string,i:string,lock=false){\n const args=[s.org,s.uid,k,i];\n // Read joined receipts in a fresh statement after waiting for a concurrent adoption.\n if(lock)await c.query('select id from alma_batch_usage where org=$1 and uid=$2 and batch_key=$3 and id=$4 for update',args);\n return (await c.query<Row>(`${select} where u.org=$1 and u.uid=$2 and u.batch_key=$3 and u.id=$4`,args)).rows[0];\n }\n async append(scope:Scope,batchKey:string,value:BatchUsageInput){\n const s=settlementScope(scope),k=id(batchKey),input=normalizeBatchUsage(value);batchUsageMember(await this.#batches.get(s,k),input);\n return this.#scope(s,async c=>{\n await c.query('insert into alma_batch_usage(org,uid,batch_key,id,item_id,input,received_at) values($1,$2,$3,$4,$5,$6::jsonb,clock_timestamp()) on conflict(org,uid,batch_key,id) do nothing',[s.org,s.uid,k,input.id,input.itemId,JSON.stringify(input)]);\n const r=record((await this.#read(c,s,k,input.id))!);if(!equalExecution(r.input,input))throw new ExecutionConflictError();return r;\n });\n }\n async get(scope:Scope,batchKey:string,identity:string){const s=settlementScope(scope),k=id(batchKey),i=id(identity);return this.#scope(s,async c=>{const r=await this.#read(c,s,k,i);return r?record(r):null;});}\n async list(scope:Scope,batchKey:string,query?:BatchUsageQuery){const s=settlementScope(scope),k=id(batchKey),q=batchUsageQuery(query);return this.#scope(s,async c=>(await c.query<Row>(`${select} where u.org=$1 and u.uid=$2 and u.batch_key=$3 and ($4::text is null or u.id>$4 collate \"C\") and (not $5::boolean or u.cost_id is null) order by u.id limit $6`,[s.org,s.uid,k,q.afterId??null,q.pendingOnly,q.limit])).rows.map(record));}\n async recordSettlement(scope:Scope,batchKey:string,identity:string){\n const s=settlementScope(scope),k=id(batchKey),i=id(identity);return this.#scope(s,async c=>{\n const row=await this.#read(c,s,k,i,true);if(!row)throw new ExecutionStateError();const r=record(row);\n if(r.receipt)return {status:'replayed' as const,record:r};if(!batchUsageSettlement(r))return {status:'pending' as const};\n const source=(await c.query<Row&{id:string}>(`select c.id,c.settlement_payload,c.settlement_session_usd,c.settlement_day_usd,g.request,g.decisions from alma_audit_cost c join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id) where c.org=$1 and c.uid=$2 and c.settlement_id=$3 and c.settlement_governed`,[s.org,s.uid,r.execution.settlementId])).rows[0];\n if(!source)return {status:'pending' as const};bindBatchUsageReceipt(r,receipt(source));\n await c.query('update alma_batch_usage set cost_id=$5::uuid where org=$1 and uid=$2 and batch_key=$3 and id=$4',[s.org,s.uid,k,i,source.id]);\n return {status:'applied' as const,record:record((await this.#read(c,s,k,i))!)};\n });\n }\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from 'pg';\nimport { assertRoleIdentifier, DEFAULT_RLS_ROLE, governedCostSettlementStoreMigrationSql, rlsPolicySql } from '@alma-harness/postgres';\nimport { batchSubmissionMigrationSql } from './batch-schema';\nimport { batchPricingSql } from './batch-pricing-schema';\nexport function batchUsageMigrationSql(role=DEFAULT_RLS_ROLE):string {\n assertRoleIdentifier(role);return `${batchSubmissionMigrationSql(role)}${governedCostSettlementStoreMigrationSql(role)}${batchPricingSql}\ncreate or replace function alma_batch_usage_shape(v jsonb) returns boolean language plpgsql immutable as $shape$\ndeclare e jsonb; u jsonb; field text; child jsonb;\nbegin\n if (jsonb_typeof(v)='object' and v ?& array['id','itemId','handle','evidence','outcome']\n and (v-array['id','itemId','handle','evidence','outcome','providerRequestId'])='{}'::jsonb\n and v->>'outcome' in ('succeeded','errored','cancelled','expired','unusable')) is not true then return false;end if;\n foreach field in array array['id','itemId','providerRequestId'] loop\n if (v ? field) and (jsonb_typeof(v->field)='string' and v->>field ~ '^[!-~]{1,200}$') is not true then return false;end if;\n end loop;\n e=v->'evidence';u=e->'usage';\n if alma_execution_shape_v2(e,'evidence') is not true then return false;end if;\n if e->>'status'='unknown' then return (e ? 'reason' and (e-'status'-'reason')='{}'::jsonb and e->>'reason' in ('missing','invalid','interrupted')) is true;end if;\n if (e->>'status' in ('known','unpriced') and u ?& array['inputTokens','outputTokens']) is not true then return false;end if;\n if e->>'status'='known' and ((e-'status'-'usage')<>'{}'::jsonb or u->>'serviceTier' is distinct from 'batch') then return false;end if;\n if e->>'status'='unpriced' then\n if (e ? 'issues' and jsonb_array_length(e->'issues') between 1 and 2 and not(e ? 'reason')) is not true then return false;end if;\n for child in select value from jsonb_array_elements(e->'issues') loop if child not in ('\"service_tier\"'::jsonb,'\"cache_ttl\"'::jsonb) then return false;end if;end loop;\n if e ? 'reportedServiceTier' and (e->>'reportedServiceTier' ~ '^[!-~]{1,200}$') is not true then return false;end if;\n end if;\n if u ? 'serviceTier' and u->>'serviceTier' not in ('batch','standard','priority','flex') then return false;end if;\n if u ? 'cacheWriteTtl' and u->>'cacheWriteTtl' not in ('5m','1h') then return false;end if;\n foreach field in array array['inputTokens','outputTokens','cacheReadInputTokens','cacheWriteInputTokens','reasoningTokens','webSearchRequests'] loop\n if u ? field and ((u->>field)::numeric between 0 and 9007199254740991 and trunc((u->>field)::numeric)=(u->>field)::numeric) is not true then return false;end if;\n end loop;\n if e ? 'cacheWriteTokensByTtl' then\n if (e->'cacheWriteTokensByTtl' ?& array['5m','1h']) is not true then return false;end if;\n for child in select value from jsonb_each(e->'cacheWriteTokensByTtl') loop if ((child#>>'{}')::numeric between 0 and 9007199254740991 and trunc((child#>>'{}')::numeric)=(child#>>'{}')::numeric) is not true then return false;end if;end loop;\n end if;return true;\nexception when others then return false;\nend $shape$;\ncreate table if not exists alma_batch_usage (\n org text not null,uid text not null,batch_key text not null,id text collate \"C\" not null,item_id text not null,\n input jsonb not null,received_at timestamptz not null,cost_id uuid,\n primary key(org,uid,batch_key,id),\n foreign key(org,uid,batch_key,item_id) references alma_batch_items(org,uid,batch_key,item_id),\n foreign key(org,uid,cost_id) references alma_audit_cost(org,uid,id),\n check((alma_batch_usage_shape(input) and input->>'id'=id and input->>'itemId'=item_id) is true)\n);\ncreate or replace function alma_batch_usage_validate() returns trigger language plpgsql as $validate$\ndeclare batch alma_batch_submissions%rowtype; e jsonb; source record; field text;\nbegin\n select * into batch from alma_batch_submissions where org=new.org and uid=new.uid and key=new.batch_key;\n select batch.input->'items'->(ordinal-1)->'execution' into e from alma_batch_items where org=new.org and uid=new.uid and batch_key=new.batch_key and item_id=new.item_id;\n if (batch.state in ('submitted','reconciliation_required') and batch.handle is not null and batch.handle=new.input->'handle' and e is not null) is not true then raise exception 'Invalid batch observation binding' using errcode='23514';end if;\n if tg_op='INSERT' then\n if new.cost_id is not null then raise exception 'Observe before adopting receipt' using errcode='23514';end if;\n new.received_at=clock_timestamp();return new;\n end if;\n if (new.org,new.uid,new.batch_key,new.id,new.item_id,new.input,new.received_at) is distinct from (old.org,old.uid,old.batch_key,old.id,old.item_id,old.input,old.received_at)\n or old.cost_id is not null or new.cost_id is null then raise exception 'Immutable batch observation' using errcode='23514';end if;\n select c.settlement_payload payload,g.request into source from alma_audit_cost c join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where c.org=new.org and c.uid=new.uid and c.id=new.cost_id and c.settlement_governed;\n if (source.payload is not null and new.input->'evidence'->>'status'='known' and source.payload->>'id'=e->>'settlementId'\n and source.payload->'scope'=e->'scope' and source.payload->'model'=e->'model' and source.payload->>'at'=e->>'occurredAt'\n and (source.payload->>'costUsd')::float8=alma_batch_price(e,new.input->'evidence'->'usage')\n and source.payload->>'serviceTier'='batch' and source.payload->'usage'=new.input->'evidence'->'usage'\n and source.payload->'consumers'=e->'governance'->'consumers'\n and source.request->>'policyVersion'=e->>'policyVersion' and source.request->'caps'=e->'governance'->'caps'\n and not(source.payload ? 'parentCallId')) is not true then raise exception 'Invalid batch financial association' using errcode='23514';end if;\n if source.payload->'providerRequestId' is distinct from new.input->'providerRequestId' then raise exception 'Invalid provider reference' using errcode='23514';end if;\n foreach field in array array['sessionId','operationId','attemptId','callId','priceVersion'] loop\n if (source.payload->>field=e->>field) is not true then raise exception 'Invalid financial identity' using errcode='23514';end if;\n end loop;return new;\nend $validate$;\ndo $trigger$ begin\n if not exists(select from pg_trigger where tgrelid='alma_batch_usage'::regclass and tgname='alma_batch_usage_validate') then\n create trigger alma_batch_usage_validate before insert or update on alma_batch_usage for each row execute function alma_batch_usage_validate();\n end if;\nend $trigger$;\n${rlsPolicySql('alma_batch_usage')}\ngrant select,insert,update on alma_batch_usage to ${role};\n${functionPathSql(\"alma_batch_usage_shape(jsonb)\",\"alma_batch_usage_validate()\")}\n`; }\nexport async function migrateBatchUsageStore(pool:Pool,opts:{role?:string}={}):Promise<void>{await pool.query(batchUsageMigrationSql(opts.role));}\n","/** SQL defense for receipt association; arithmetic order mirrors core priceUsage. */\nexport const batchPricingSql=`\ncreate or replace function alma_batch_price(e jsonb,u jsonb) returns double precision language plpgsql immutable as $price$\ndeclare price jsonb; rates jsonb; band jsonb; prompt double precision; best double precision;\n searches double precision; hour_rate double precision; write_rate double precision; amount double precision;\nbegin\n select value into price from jsonb_array_elements(e->'prices') where value->'model'=e->'model' and value->>'serviceTier'='batch' limit 1;\n if price is null then return null;end if;\n prompt=(u->>'inputTokens')::float8+coalesce((u->>'cacheReadInputTokens')::float8,0)+coalesce((u->>'cacheWriteInputTokens')::float8,0);\n rates=price;\n for band in select value from jsonb_array_elements(coalesce(price->'bands','[]'::jsonb)) loop\n if prompt>(band->>'aboveInputTokens')::float8 and (best is null or (band->>'aboveInputTokens')::float8>best) then rates=band;best=(band->>'aboveInputTokens')::float8;end if;\n end loop;\n searches=coalesce((u->>'webSearchRequests')::float8,0);\n if searches>0 and not(price ? 'webSearchUsdPerRequest') then return null;end if;\n hour_rate=coalesce((rates->>'cacheWrite1hUsdPerMTok')::float8,(price->>'cacheWrite1hUsdPerMTok')::float8);\n if u->>'cacheWriteTtl'='1h' and coalesce((u->>'cacheWriteInputTokens')::float8,0)>0 then\n if hour_rate is null then return null;end if;write_rate=hour_rate;\n else write_rate=coalesce((rates->>'cacheWriteUsdPerMTok')::float8,(rates->>'inputUsdPerMTok')::float8);end if;\n amount=((u->>'inputTokens')::float8/1000000::float8)*(rates->>'inputUsdPerMTok')::float8\n +((u->>'outputTokens')::float8/1000000::float8)*(rates->>'outputUsdPerMTok')::float8\n +(coalesce((u->>'cacheReadInputTokens')::float8,0)/1000000::float8)*coalesce((rates->>'cacheReadUsdPerMTok')::float8,(rates->>'inputUsdPerMTok')::float8)\n +(coalesce((u->>'cacheWriteInputTokens')::float8,0)/1000000::float8)*write_rate\n +searches*coalesce((price->>'webSearchUsdPerRequest')::float8,0);\n if amount>=0 and amount<'Infinity'::float8 then return amount;end if;return null;\nexception when others then return null;\nend $price$;\n`;\n","import { ExecutionConflictError,ExecutionStateError,settlementIdentifier as id,settlementScope,type Scope } from '@alma-harness/core';\nimport { bindBatchAccounting,batchFinancialReceipt,batchFinancialWarnings,normalizeBatchFinancialReceipt,operationCallQuery,type BatchAccountingStore,type BatchFinancialReceipt,type BatchFinancialSummary } from '@alma-harness/execution';\nimport { inScope,resolveRlsRole,resolveStatementTimeout,type ScopedStoreOptions } from '@alma-harness/postgres';\nimport type { Pool,PoolClient } from 'pg';\nimport { PostgresBatchSubmissionStore } from './batch';\nimport { PostgresBatchUsageStore } from './batch-usage';\nexport class PostgresBatchAccountingStore implements BatchAccountingStore {\n readonly #role:string|null;readonly #timeout:number|null;readonly #batches:PostgresBatchSubmissionStore;readonly #usage:PostgresBatchUsageStore;\n constructor(readonly pool:Pool,opts:ScopedStoreOptions={}){this.#role=resolveRlsRole(opts);this.#timeout=resolveStatementTimeout(opts);this.#batches=new PostgresBatchSubmissionStore(pool,opts);this.#usage=new PostgresBatchUsageStore(pool,opts);}\n async #scope<T>(s:Scope,fn:(c:PoolClient)=>Promise<T>):Promise<T>{try{return await inScope(this.pool,this.#role,s,fn,this.#timeout);}catch(e){if(['23505','23514','23503'].includes((e as {code?:string}).code??''))throw new ExecutionConflictError();throw e;}}\n async record(scope:Scope,batchKey:string,observationId:string){\n const s=settlementScope(scope),k=id(batchKey),i=id(observationId),batch=await this.#batches.get(s,k);if(!batch)throw new ExecutionStateError();\n const value=await this.#usage.get(s,k,i);if(!value)return {status:'pending' as const};const source=bindBatchAccounting(batch,value);if(!source.receipt)return {status:'pending' as const};\n return this.#scope(s,async c=>{\n const args=[s.org,s.uid,k];await c.query('select key from alma_batch_submissions where org=$1 and uid=$2 and key=$3 for update',args);\n const old=(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 and item_id=$4',[...args,source.input.itemId])).rows[0];if(old)return {status:'replayed' as const,receipt:normalizeBatchFinancialReceipt(old.receipt)};\n const previous=(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 order by ordinal desc limit 1',args)).rows[0];\n const warned=(await c.query<{cap:BatchFinancialReceipt['newWarnings'][number]}>('select cap from alma_batch_warnings where org=$1 and uid=$2 and batch_key=$3',args)).rows.map(r=>r.cap);\n const now=(await c.query<{at:Date}>('select clock_timestamp() at')).rows[0]!.at.toISOString();\n const receipt=batchFinancialReceipt(batch,source,previous?normalizeBatchFinancialReceipt(previous.receipt):undefined,warned,now);\n await c.query('insert into alma_batch_financial_items(org,uid,batch_key,item_id,observation_id,ordinal,receipt) values($1,$2,$3,$4,$5,$6,$7::jsonb)',[...args,receipt.itemId,i,receipt.accountingOrdinal,JSON.stringify(receipt)]);\n return {status:'applied' as const,receipt};\n });\n }\n async get(scope:Scope,batchKey:string):Promise<BatchFinancialSummary|null>{\n const s=settlementScope(scope),k=id(batchKey),batch=await this.#batches.get(s,k);if(!batch)return null;\n return this.#scope(s,async c=>{\n const args=[s.org,s.uid,k],state=(await c.query<{state:typeof batch.state}>('select state from alma_batch_submissions where org=$1 and uid=$2 and key=$3 for share',args)).rows[0]!.state;\n const last=(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 order by ordinal desc limit 1',args)).rows[0];\n const rows=(await c.query<{receipt:BatchFinancialReceipt;cap:string}>('select f.receipt,w.cap from alma_batch_warnings w join alma_batch_financial_items f on (f.org,f.uid,f.batch_key,f.item_id)=(w.org,w.uid,w.batch_key,w.item_id) where w.org=$1 and w.uid=$2 and w.batch_key=$3 order by f.ordinal,w.cap',args)).rows;\n const warnings=rows.map(r=>{const w=batchFinancialWarnings(s,r.receipt).find(w=>w.cap===r.cap);if(!w)throw new ExecutionConflictError();return w;});\n const receipt=last?normalizeBatchFinancialReceipt(last.receipt):undefined;return {batchId:batch.input.id,costUsd:receipt?.currentUsd??0,expectedItems:batch.input.items.length,accountedItems:receipt?.accountingOrdinal??0,batchState:state,warnings};\n });\n }\n async list(scope:Scope,batchKey:string,query?:{afterOrdinal?:number;limit?:number}){const s=settlementScope(scope),k=id(batchKey),q=operationCallQuery(query);return this.#scope(s,async c=>(await c.query<{receipt:BatchFinancialReceipt}>('select receipt from alma_batch_financial_items where org=$1 and uid=$2 and batch_key=$3 and ordinal>$4 order by ordinal limit $5',[s.org,s.uid,k,q.afterOrdinal,q.limit])).rows.map(r=>normalizeBatchFinancialReceipt(r.receipt)));}\n}\n","import { functionPathSql } from \"@alma-harness/postgres\";\nimport type { Pool } from 'pg';\nimport { assertRoleIdentifier,DEFAULT_RLS_ROLE,rlsPolicySql } from '@alma-harness/postgres';\nimport { batchUsageMigrationSql } from './batch-usage-schema';\nexport function batchAccountingMigrationSql(role=DEFAULT_RLS_ROLE):string {\n assertRoleIdentifier(role);return `${batchUsageMigrationSql(role)}\ncreate table if not exists alma_batch_financial_items (\n org text not null,uid text not null,batch_key text not null,item_id text not null,observation_id text not null,\n ordinal int not null check(ordinal between 1 and 512),receipt jsonb not null,\n primary key(org,uid,batch_key,item_id),unique(org,uid,batch_key,ordinal),\n foreign key(org,uid,batch_key,item_id) references alma_batch_items(org,uid,batch_key,item_id),\n foreign key(org,uid,batch_key,observation_id) references alma_batch_usage(org,uid,batch_key,id)\n);\ncreate table if not exists alma_batch_warnings (\n org text not null,uid text not null,batch_key text not null,cap text not null check(cap in ('perTurnUsd','perSessionUsd','perTenantDayUsd')),item_id text not null,\n primary key(org,uid,batch_key,cap),foreign key(org,uid,batch_key,item_id) references alma_batch_financial_items(org,uid,batch_key,item_id)\n);\ncreate or replace function alma_batch_financial_validate() returns trigger language plpgsql as $financial$\ndeclare batch alma_batch_submissions%rowtype; member alma_batch_items%rowtype; prior alma_batch_financial_items%rowtype;\n source record; r jsonb; before_usd double precision; cost double precision; after_usd double precision; expected jsonb; warnings jsonb; field text;\nbegin\n select * into batch from alma_batch_submissions where org=new.org and uid=new.uid and key=new.batch_key for update;\n select * into member from alma_batch_items where org=new.org and uid=new.uid and batch_key=new.batch_key and item_id=new.item_id;\n select * into prior from alma_batch_financial_items where org=new.org and uid=new.uid and batch_key=new.batch_key order by ordinal desc limit 1;\n select u.item_id,c.settlement_payload payload,g.decisions into source from alma_batch_usage u\n join alma_audit_cost c on (c.org,c.uid,c.id)=(u.org,u.uid,u.cost_id) join alma_governed_cost g on (g.org,g.uid,g.cost_id)=(c.org,c.uid,c.id)\n where u.org=new.org and u.uid=new.uid and u.batch_key=new.batch_key and u.id=new.observation_id;\n r=new.receipt;before_usd=coalesce((prior.receipt->>'currentUsd')::float8,0);cost=(source.payload->>'costUsd')::float8;after_usd=before_usd+cost;\n foreach field in array array['batchId','itemId','callId','settlementId','recordedAt'] loop\n if jsonb_typeof(r->field) is distinct from 'string' then raise exception 'Invalid financial string' using errcode='23514';end if;\n end loop;\n foreach field in array array['accountingOrdinal','reservationOrdinal','costUsd','previousUsd','currentUsd'] loop\n if jsonb_typeof(r->field) is distinct from 'number' then raise exception 'Invalid financial amount' using errcode='23514';end if;\n end loop;\n if (source.item_id=new.item_id and source.payload is not null and batch.id is not null\n and jsonb_typeof(r)='object' and r ?& array['batchId','itemId','callId','settlementId','accountingOrdinal','reservationOrdinal','costUsd','previousUsd','currentUsd','decisions','newWarnings','recordedAt']\n and (r-array['batchId','itemId','callId','settlementId','accountingOrdinal','reservationOrdinal','costUsd','previousUsd','currentUsd','decisions','newWarnings','recordedAt'])='{}'::jsonb\n and r->>'batchId'=batch.id and r->>'itemId'=new.item_id and r->>'callId'=member.call_id and r->>'settlementId'=member.settlement_id\n and new.ordinal=coalesce(prior.ordinal,0)+1 and (r->>'accountingOrdinal')::numeric=new.ordinal and (r->>'reservationOrdinal')::numeric=member.ordinal\n and (r->>'previousUsd')::float8=before_usd and (r->>'costUsd')::float8=cost and (r->>'currentUsd')::float8=after_usd and after_usd<'Infinity'::float8\n and to_char((r->>'recordedAt')::timestamptz at time zone 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')=r->>'recordedAt'\n and isfinite((r->>'recordedAt')::timestamptz) and r->>'recordedAt' ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{3}Z$') is not true then raise exception 'Invalid batch financial binding' using errcode='23514';end if;\n select coalesce(jsonb_agg(case when d->>'cap'='perTurnUsd' then d||jsonb_build_object('previousUsd',before_usd,'currentUsd',after_usd,'exceeded',after_usd>(d->>'thresholdUsd')::float8) else d end order by n),'[]'::jsonb) into expected from jsonb_array_elements(source.decisions) with ordinality as x(d,n);\n if r->'decisions' is distinct from expected then raise exception 'Invalid batch financial decisions' using errcode='23514';end if;\n select coalesce(jsonb_agg(d->>'cap' order by n),'[]'::jsonb) into warnings from jsonb_array_elements(expected) with ordinality as x(d,n)\n where d->>'onExceeded'='warn' and (d->>'exceeded')::boolean and not exists(select from alma_batch_warnings w where w.org=new.org and w.uid=new.uid and w.batch_key=new.batch_key and w.cap=d->>'cap');\n if r->'newWarnings' is distinct from warnings then raise exception 'Invalid batch warning receipt' using errcode='23514';end if;\n return new;\nend $financial$;\ncreate or replace function alma_batch_financial_warn() returns trigger language plpgsql as $warn$\nbegin\n insert into alma_batch_warnings(org,uid,batch_key,cap,item_id) select new.org,new.uid,new.batch_key,value,new.item_id from jsonb_array_elements_text(new.receipt->'newWarnings');return new;\nend $warn$;\ncreate or replace function alma_batch_warning_validate() returns trigger language plpgsql as $warning$\nbegin\n if not exists(select from alma_batch_financial_items where org=new.org and uid=new.uid and batch_key=new.batch_key and item_id=new.item_id and receipt->'newWarnings' ? new.cap) then raise exception 'Invalid batch warning association' using errcode='23514';end if;return new;\nend $warning$;\ndo $triggers$ begin\n if not exists(select from pg_trigger where tgrelid='alma_batch_financial_items'::regclass and tgname='alma_batch_financial_validate') then\n create trigger alma_batch_financial_validate before insert on alma_batch_financial_items for each row execute function alma_batch_financial_validate();\n create trigger alma_batch_financial_warn after insert on alma_batch_financial_items for each row execute function alma_batch_financial_warn();\n end if;\n if not exists(select from pg_trigger where tgrelid='alma_batch_warnings'::regclass and tgname='alma_batch_warning_validate') then\n create trigger alma_batch_warning_validate before insert on alma_batch_warnings for each row execute function alma_batch_warning_validate();\n end if;\nend $triggers$;\n${rlsPolicySql('alma_batch_financial_items')}${rlsPolicySql('alma_batch_warnings')}\ngrant select,insert on alma_batch_financial_items,alma_batch_warnings to ${role};\n${functionPathSql(\"alma_batch_financial_validate()\",\"alma_batch_financial_warn()\",\"alma_batch_warning_validate()\")}\n`; }\nexport async function migrateBatchAccountingStore(pool:Pool,opts:{role?:string}={}):Promise<void>{await pool.query(batchAccountingMigrationSql(opts.role));}\n"],"mappings":";AAAA,SAAS,kBAAAA,iBAAgB,0BAAAC,yBAAwB,uBAAAC,sBAAqB,wBAAwBC,KAAI,mBAAAC,kBAAiB,mBAAAC,wBAAmC;AACtJ,SAAS,oBAAoB,0BAAAC,yBAAwB,0BAAAC,yBAAwB,yBAAyB,0BAAAC,yBAAwB,sBAAAC,2BAA8K;AAC5S,SAAS,WAAAC,UAAS,kBAAAC,iBAAgB,2BAAAC,gCAAwD;;;ACF1F,SAAS,mBAAAC,wBAAuB;AAEhC,SAAS,sBAAsB,kBAAkB,4BAA4B,oBAAoB;;;ACFjG,SAAS,uBAAuB;AAEzB,IAAM,2BAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcjC,IAAM,0BAA0B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBhC,IAAM,+BAA+B;AAAA;AAAA;AAAA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oBAAmB,KAAK;AAChF,WAAO,KAAK,OAAO,GAAG,OAAM,OAAM,MAAM,EAAE,MAAe;AAAA,8FACiC,CAAC,EAAE,KAAK,EAAE,KAAK,GAAG,EAAE,cAAc,EAAE,KAAK,CAAC,GAAG,KAAK,IAAI,IAAI,CAAC;AAAA,EACvJ;AAAA,EACA,MAAM,iBAAiB,OAAc,OAA2B,CAAC,GAAmC;AAClG,UAAM,IAAIF,iBAAgB,KAAK,GAAG,QAAQG,iBAAgB,KAAK,KAAK;AACpE,WAAO,KAAK,OAAO,GAAG,OAAM,MAAK;AAC/B,YAAM,QAAQ,MAAM,EAAE,MAAe,UAAU,IAAI,sKAAsK,CAAC,EAAE,KAAK,EAAE,KAAK,KAAK,CAAC,GAAG;AACjP,YAAM,UAAiC,CAAC;AACxC,iBAAW,KAAK,KAAM,SAAQ,KAAK,QAAQ,MAAM,EAAE,MAAe,8IAA8I,IAAI,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,KAAK,CAAC,CAAE,CAAC;AACzP,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":["equalExecution","ExecutionConflictError","ExecutionStateError","id","settlementLimit","settlementScope","checkOperationDeadline","normalizeOperationCall","normalizeOperationRoot","operationCallQuery","inScope","resolveRlsRole","resolveStatementTimeout","functionPathSql","functionPathSql","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","rlsPolicySql","DEFAULT_RLS_ROLE","assertRoleIdentifier","rlsPolicySql","functionPathSql","ExecutionConflictError","ExecutionStateError","id","settlementScope","normalizeOperationRoot","operationCallQuery","assertRoleIdentifier","inScope","resolveRlsRole","resolveStatementTimeout","record","at","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","DEFAULT_RETENTION_ROLE","rlsPolicySql","DEFAULT_RLS_ROLE","DEFAULT_RETENTION_ROLE","assertRoleIdentifier","rlsPolicySql","functionPathSql","equalExecution","ExecutionConflictError","ExecutionStateError","id","settlementScope","inScope","resolveRlsRole","resolveStatementTimeout","record","at","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","executionStoreMigrationSql","rlsPolicySql","equalExecution","ExecutionConflictError","ExecutionStateError","id","settlementScope","normalizeGovernedCostReceipt","inScope","resolveRlsRole","resolveStatementTimeout","receipt","normalizeGovernedCostReceipt","record","resolveRlsRole","resolveStatementTimeout","inScope","ExecutionConflictError","settlementScope","id","equalExecution","ExecutionStateError","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","governedCostSettlementStoreMigrationSql","rlsPolicySql","DEFAULT_RLS_ROLE","assertRoleIdentifier","governedCostSettlementStoreMigrationSql","rlsPolicySql","functionPathSql","ExecutionConflictError","ExecutionStateError","id","settlementScope","operationCallQuery","inScope","resolveRlsRole","resolveStatementTimeout","resolveRlsRole","resolveStatementTimeout","inScope","ExecutionConflictError","settlementScope","id","ExecutionStateError","receipt","w","operationCallQuery","functionPathSql","assertRoleIdentifier","DEFAULT_RLS_ROLE","rlsPolicySql","DEFAULT_RLS_ROLE","assertRoleIdentifier","rlsPolicySql","functionPathSql","resolveRlsRole","resolveStatementTimeout","inScope","ExecutionConflictError","ExecutionStateError","normalizeOperationRoot","checkOperationDeadline","equalExecution","normalizeOperationCall","settlementScope","id","operationCallQuery","settlementLimit"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alma-harness/postgres-execution",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "PostgreSQL operation lineage for Alma.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -20,9 +20,9 @@
20
20
  },
21
21
  "peerDependencies": {
22
22
  "pg": ">=8",
23
- "@alma-harness/core": "^0.6.1",
24
- "@alma-harness/execution": "^0.6.1",
25
- "@alma-harness/postgres": "^0.6.1"
23
+ "@alma-harness/core": "^0.8.0",
24
+ "@alma-harness/execution": "^0.8.0",
25
+ "@alma-harness/postgres": "^0.8.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^24.1.0",
@@ -30,10 +30,10 @@
30
30
  "vitest": "^3.2.4",
31
31
  "pg": "^8.16.3",
32
32
  "@types/pg": "^8.15.4",
33
- "@alma-harness/core": "^0.6.1",
34
- "@alma-harness/execution": "^0.6.1",
35
- "@alma-harness/postgres": "^0.6.1",
36
- "@alma-harness/testing": "^0.6.1"
33
+ "@alma-harness/execution": "^0.8.0",
34
+ "@alma-harness/postgres": "^0.8.0",
35
+ "@alma-harness/core": "^0.8.0",
36
+ "@alma-harness/testing": "^0.8.0"
37
37
  },
38
38
  "files": [
39
39
  "dist"