diff --git a/backend/drizzle/0059_server_poll_journal_limits.sql b/backend/drizzle/0059_server_poll_journal_limits.sql new file mode 100644 index 00000000..5e754ac1 --- /dev/null +++ b/backend/drizzle/0059_server_poll_journal_limits.sql @@ -0,0 +1,97 @@ +BEGIN; + +ALTER TABLE public.server_poll_storage_usage + DROP CONSTRAINT server_poll_storage_usage_check2, + DROP CONSTRAINT server_poll_storage_usage_admissions_check, + DROP CONSTRAINT server_poll_storage_rows_charge, + DROP CONSTRAINT server_poll_storage_bytes_charge, + ADD CONSTRAINT server_poll_storage_usage_admissions_check CHECK (admissions >= 0), + ADD CONSTRAINT server_poll_storage_rows_charge CHECK (reserved_rows = admissions * 4019 + compacted_admissions * 2), + ADD CONSTRAINT server_poll_storage_bytes_charge CHECK (reserved_bytes = admissions * 8421376 + compacted_admissions * 32768 + archive_bytes); + +CREATE OR REPLACE FUNCTION server_poll_storage_admission_guard() RETURNS trigger LANGUAGE plpgsql SET TimeZone='UTC' SET search_path=pg_catalog,public AS $$ +DECLARE retention integer; charged integer; r public.server_poll_archives%ROWTYPE; +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended('server-poll-storage-v1',0)); + IF TG_OP='DELETE' THEN + IF NOT public.server_poll_storage_gc_allowed(OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id) + OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id) + OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id) + OR EXISTS(SELECT 1 FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id) THEN RAISE EXCEPTION 'poll lifetime or children prevent admission deletion'; END IF; + UPDATE public.server_poll_storage_usage SET admissions=admissions-CASE WHEN OLD.storage_state='full' THEN 1 ELSE 0 END, + compacted_admissions=compacted_admissions-CASE WHEN OLD.storage_state='compacted' THEN 1 ELSE 0 END, + archive_bytes=archive_bytes-COALESCE(OLD.archive_bytes,0), + reserved_rows=reserved_rows-CASE WHEN OLD.storage_state='full' THEN 4019 ELSE 2 END, + reserved_bytes=reserved_bytes-CASE WHEN OLD.storage_state='full' THEN 8421376 ELSE 32768+OLD.archive_bytes END + WHERE scope IN('global','owner:'||OLD.owner_id); + GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll quota refund mismatch'; END IF; RETURN OLD; + END IF; + IF TG_OP='UPDATE' THEN + IF OLD.storage_state='compacted' AND NEW.storage_state='compacted' + AND current_setting('mm.poll_retire_receipt',true)=OLD.receipt_id::text + AND (to_jsonb(OLD)-'archive_bytes')=(to_jsonb(NEW)-'archive_bytes') THEN + SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND version=2; + IF NOT FOUND OR r.ciphertext_bytes<>NEW.archive_bytes OR NEW.archive_bytes>OLD.archive_bytes + OR r.execution_id<>OLD.execution_id OR r.connection_id<>OLD.connection_id OR r.owner_id<>OLD.owner_id + THEN RAISE EXCEPTION 'retired poll charge source mismatch'; END IF; + UPDATE public.server_poll_storage_usage + SET archive_bytes=archive_bytes-OLD.archive_bytes+NEW.archive_bytes, + reserved_bytes=reserved_bytes-OLD.archive_bytes+NEW.archive_bytes + WHERE scope IN ('global','owner:'||OLD.owner_id) AND compacted_admissions>=1 AND archive_bytes>=OLD.archive_bytes; + GET DIAGNOSTICS charged=ROW_COUNT; + IF charged<>2 THEN RAISE EXCEPTION 'retired poll charge adjustment mismatch'; END IF; + RETURN NEW; + END IF; + -- This durable one-shot marker is written and ACKed in its OWN transaction + -- before archive construction. A committed/unknown claim never resets and + -- the worker never retries destructive work against an already claimed full + -- source. Claim time is maintenance metadata, not renewed execution activity. + IF OLD.storage_state='full' AND NEW.storage_state='full' AND OLD.compaction_claim IS NULL AND OLD.compaction_claimed_at IS NULL AND OLD.compaction_claim_xid IS NULL + AND NEW.compaction_claim IS NOT NULL AND NEW.compaction_claim_xid IS NULL + AND(to_jsonb(OLD)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid'])=(to_jsonb(NEW)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid']) + AND public.server_poll_storage_compact_allowed(OLD.receipt_id) + THEN NEW.compaction_claimed_at:=clock_timestamp(); NEW.compaction_claim_xid:=pg_current_xact_id(); RETURN NEW; END IF; + IF(to_jsonb(OLD)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) IS DISTINCT FROM + (to_jsonb(NEW)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) THEN RAISE EXCEPTION 'poll admission identity is immutable'; END IF; + IF OLD.storage_state<>'full' THEN RAISE EXCEPTION 'compacted poll identity cannot reopen or change'; END IF; + IF NEW.storage_state='compacted' THEN + SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND compaction_xid=pg_current_xact_id(); + IF NOT FOUND OR NEW.used_rows<>OLD.used_rows OR NEW.used_bytes<>OLD.used_bytes OR NEW.claim_token IS DISTINCT FROM OLD.claim_token + OR NEW.claim_attempted_at IS DISTINCT FROM OLD.claim_attempted_at OR NEW.archive_bytes<>r.ciphertext_bytes OR NEW.original_activity_at<>r.original_activity_at + OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id) + OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id) + OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id) + THEN RAISE EXCEPTION 'poll compaction requires the complete current-transaction archive'; END IF; + NEW.compact_at:=r.created_at; + UPDATE public.server_poll_storage_usage SET admissions=admissions-1,compacted_admissions=compacted_admissions+1, + archive_bytes=archive_bytes+r.ciphertext_bytes,reserved_rows=reserved_rows-4019+2,reserved_bytes=reserved_bytes-8421376+32768+r.ciphertext_bytes + WHERE scope IN('global','owner:'||OLD.owner_id) AND admissions>=1; + GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll compaction charge mismatch'; END IF; + RETURN NEW; + END IF; + IF NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL THEN RAISE EXCEPTION 'full poll cannot carry archive metadata'; END IF; + IF OLD.claim_token IS NOT NULL AND NEW.claim_token IS NULL AND OLD.claim_attempted_at IS NULL AND NEW.claim_attempted_at IS NOT NULL + AND NEW.used_rows=OLD.used_rows AND NEW.used_bytes=OLD.used_bytes AND OLD.authority_expires_at>clock_timestamp() + THEN NEW.claim_attempted_at:=clock_timestamp(); RETURN NEW; END IF; + IF OLD.claim_token IS NOT DISTINCT FROM NEW.claim_token AND OLD.claim_attempted_at IS NOT DISTINCT FROM NEW.claim_attempted_at + AND NEW.used_rows=OLD.used_rows+1 AND NEW.used_bytes>OLD.used_bytes THEN RETURN NEW; END IF; + RAISE EXCEPTION 'poll admission cannot refresh, reopen or refund itself'; + END IF; + IF NEW.storage_state<>'full' OR NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL + OR NEW.compaction_claim IS NOT NULL OR NEW.compaction_claimed_at IS NOT NULL OR NEW.compaction_claim_xid IS NOT NULL + OR NOT public.server_poll_storage_accounting_valid() THEN RAISE EXCEPTION 'new poll requires full reservation and exact ledger'; END IF; + SELECT requests_retention_days INTO retention FROM public.mcp_settings WHERE id=1; + IF retention IS NULL OR retention NOT BETWEEN 1 AND 365 OR NEW.authority_issued_at>clock_timestamp() OR NEW.authority_expires_at<=clock_timestamp() + OR NEW.claim_token IS NULL OR NEW.claim_attempted_at IS NOT NULL OR NEW.used_rows<>0 OR NEW.used_bytes<>0 THEN RAISE EXCEPTION 'new poll admission needs original live authority'; END IF; + IF EXISTS(SELECT 1 FROM public.server_poll_storage_admissions WHERE receipt_id=NEW.receipt_id OR(identity_kind=NEW.identity_kind AND execution_id=NEW.execution_id)) THEN RAISE EXCEPTION 'poll identity already spent'; END IF; + NEW.created_at:=clock_timestamp(); NEW.retention_days:=retention; NEW.safety_ms:=60000; + NEW.gc_not_before:=NEW.authority_expires_at+make_interval(days=>retention)+interval '60 seconds'; + INSERT INTO public.server_poll_storage_usage(scope) VALUES('owner:'||NEW.owner_id) ON CONFLICT DO NOTHING; + UPDATE public.server_poll_storage_usage SET admissions=admissions+1,reserved_rows=reserved_rows+4019,reserved_bytes=reserved_bytes+8421376 WHERE scope IN('global','owner:'||NEW.owner_id); + GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll admission counters unavailable'; END IF; + RETURN NEW; +END $$; + +INSERT INTO public.schema_migrations (id) VALUES ('0059_server_poll_journal_limits') ON CONFLICT (id) DO NOTHING; + +COMMIT; diff --git a/backend/scripts/build-database-operator.test.mjs b/backend/scripts/build-database-operator.test.mjs index 4a92443a..ccd9522a 100644 --- a/backend/scripts/build-database-operator.test.mjs +++ b/backend/scripts/build-database-operator.test.mjs @@ -20,11 +20,11 @@ test('fixed artifact is reproducible, resolves the compiled backend graph, and r const packageJson=JSON.parse(await readFile(path.join(backend,'package.json'),'utf8')) await mkdir(projectBackend,{recursive:true});await writeFile(path.join(projectBackend,'package.json'),JSON.stringify({type:'module',dependencies:packageJson.dependencies})) const first=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}),second=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}) - assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,33);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,32) + assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,34);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,33) assert(first.modules.some(item=>item.file==='writer-profile/registry-enrollment.mjs')) assert(first.modules.some(item=>item.file==='writer-profile/marker-fence-enrollment.mjs')) assert(first.modules.some(item=>item.file==='writer-profile/fixed58-build-definition.js')) - assert(first.modules.some(item=>item.file==='writer-profile/fixed59-build-definition.js')) + assert(first.modules.some(item=>item.file==='writer-profile/fixed60-build-definition.js')) assert(first.backendDistImports.includes('db/database-restore-quarantine-profile.js')) assert(first.backendDistImports.includes('db/database-source-activation-record.js')) assert(first.backendDistImports.includes('services/server-probe-legacy-source-inventory.js')) diff --git a/backend/scripts/database-operator-sources.mjs b/backend/scripts/database-operator-sources.mjs index 444332b8..393eb007 100644 --- a/backend/scripts/database-operator-sources.mjs +++ b/backend/scripts/database-operator-sources.mjs @@ -13,5 +13,5 @@ export const OPERATOR_SOURCES=Object.freeze([ 'writer-profile/catalogue.mts','writer-profile/catalogue-value-bridge.ts','writer-profile/catalogue-projection.ts','writer-profile/catalogue-leaves.ts', 'writer-profile/application-writer-profile-catalogue.ts','writer-profile/application-writer-profile-catalogue-values.ts', 'writer-profile/application-writer-profile-catalogue-parent-policy.ts','writer-profile/application-writer-profile-canonical.ts', - 'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/fixed59-build-definition.ts','writer-profile/fixed59-ix-delta.ts','writer-profile/expanded44-data-policy.ts', + 'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/fixed59-build-definition.ts','writer-profile/fixed59-ix-delta.ts','writer-profile/fixed60-build-definition.ts','writer-profile/expanded44-data-policy.ts', ]) diff --git a/backend/scripts/database-writer-profile-operator.mts b/backend/scripts/database-writer-profile-operator.mts index ec92dc77..6fe2c289 100644 --- a/backend/scripts/database-writer-profile-operator.mts +++ b/backend/scripts/database-writer-profile-operator.mts @@ -57,11 +57,11 @@ export async function main(args:string[]){ // import so a newly loaded NODE_PG_FORCE_NATIVE cannot select another driver. const {createProtectedDatabaseSourceBindingVerifier}=await import('./writer-profile/protected-source-registry.mjs') assertJsDriverEnvironment(process.env) - const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,collectSource59Catalogue,approvedDefinition}]=await Promise.all([ + const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,collectSource59Catalogue,collectSource60Catalogue,approvedDefinition}]=await Promise.all([ import('pg'),import('./writer-profile/publisher.mjs'),import('./writer-profile/catalogue.mjs')]) assertJsDriverEnvironment(process.env) const reviewedDefinition=legacyInspection?undefined:approvedDefinition(definition) - const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue,59:collectSource59Catalogue} + const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue,59:collectSource59Catalogue,60:collectSource60Catalogue} const collectCatalogue=collectCatalogues[reviewedDefinition&&'edition' in reviewedDefinition?reviewedDefinition.edition:44] if(!legacyInspection&&!catalogueInspection){ assert.equal(reviewedDefinition!.definitionSha256,pinned!.definitionSha256) diff --git a/backend/scripts/writer-profile/application-writer-profile-catalogue.ts b/backend/scripts/writer-profile/application-writer-profile-catalogue.ts index d1b6fe14..983ed623 100644 --- a/backend/scripts/writer-profile/application-writer-profile-catalogue.ts +++ b/backend/scripts/writer-profile/application-writer-profile-catalogue.ts @@ -8,6 +8,7 @@ import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definiti import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js' import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE,normalizeFixed58RestoreRows} from './fixed58-build-definition.js' import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js' +import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js' import {GLOBALS,GROUPS,object,rows,sorted,text,projectCatalogueData,type CatalogueEdition,type Inventory,type Row,type Json} from './catalogue-projection.js' import {validateCatalogueLeafData} from './catalogue-leaves.js' import {catalogueTopologyPolicy,Expanded44TopologyBudgetData} from './expanded44-data-policy.js' @@ -22,6 +23,7 @@ const definitions = { 57: { provenance: BUILD57_PROVENANCE, template: FIXED57_ROLE_TEMPLATE }, 58: { provenance: BUILD58_PROVENANCE, template: FIXED58_ROLE_TEMPLATE }, 59: { provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE }, + 60: { provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE }, } const exact=(a:unknown,b:unknown,label:string)=>{if(canonical(a)!==canonical(b))throw Error('Writer catalogue refused: '+label)} function captureBindings(input:InstallationRoleBindingsData):Readonly> { diff --git a/backend/scripts/writer-profile/catalogue-projection.ts b/backend/scripts/writer-profile/catalogue-projection.ts index 6990a7d3..d97b8dfa 100644 --- a/backend/scripts/writer-profile/catalogue-projection.ts +++ b/backend/scripts/writer-profile/catalogue-projection.ts @@ -4,7 +4,7 @@ export type Json=null|boolean|number|string|Json[]|{[key:string]:Json} export type Row=Record export type Inventory=Record export const GROUPS=['columns','triggers','constraints','indexes','roleGrants','inheritance'] as const -export type CatalogueEdition = 44 | 56 | 57 | 58 | 59 +export type CatalogueEdition = 44 | 56 | 57 | 58 | 59 | 60 export const GLOBALS=['database','effectiveDatabase','effectiveFunctions','effectiveSchemas','effectiveSequences','events','functions','identities','memberships','parameters','roles','schemas','settings','sequences'] as const export const sorted=(rows:Row[])=>rows.slice().sort((a,b)=>canonical(a)canonical(b)?1:0) export const omit=(row:Row,names:readonly string[]):Row=>Object.fromEntries(Object.entries(row).filter(([key])=>!names.includes(key))) diff --git a/backend/scripts/writer-profile/catalogue.mts b/backend/scripts/writer-profile/catalogue.mts index e556144b..efe1c33b 100644 --- a/backend/scripts/writer-profile/catalogue.mts +++ b/backend/scripts/writer-profile/catalogue.mts @@ -6,6 +6,7 @@ import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definiti import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js' import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE} from './fixed58-build-definition.js' import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js' +import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js' import {assertRestoreProfileQuarantine} from '../../src/db/database-restore-quarantine-profile.js' import {canonical,sha} from './application-writer-profile-canonical.js' import type {CatalogueEdition} from './catalogue-projection.js' @@ -28,6 +29,10 @@ export function approvedDefinition(value:unknown){ assert.equal(canonical(v.provenance),canonical(BUILD59_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED59_ROLE_TEMPLATE)) return Object.freeze({edition:59 as const,definitionSha256:BUILD59_PROVENANCE.templateSha256,manifestSha256:BUILD59_PROVENANCE.manifestSha256}) } + if(v.format==='application-writer-source60-definition-approval-v1'){ + assert.equal(canonical(v.provenance),canonical(BUILD60_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED60_ROLE_TEMPLATE)) + return Object.freeze({edition:60 as const,definitionSha256:BUILD60_PROVENANCE.templateSha256,manifestSha256:BUILD60_PROVENANCE.manifestSha256}) + } assert.equal(v.format,'application-writer-source56-definition-approval-v1') assert.equal(canonical(v.provenance),canonical(BUILD56_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED56_ROLE_TEMPLATE)) return Object.freeze({edition:56 as const,definitionSha256:BUILD56_PROVENANCE.templateSha256,manifestSha256:BUILD56_PROVENANCE.manifestSha256}) @@ -43,6 +48,7 @@ export const collectSource56Catalogue = (s:CatalogueSession, installation:Catalo export const collectSource57Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 57) export const collectSource58Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 58) export const collectSource59Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 59) +export const collectSource60Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 60) async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstallation,edition:CatalogueEdition){ const settings=(await s.query("SELECT pg_catalog.current_setting('search_path') AS path,pg_catalog.current_setting('TimeZone') AS zone,pg_catalog.current_setting('DateStyle') AS dates")).rows assert.equal(settings.length,1);assert(['path','zone','dates'].every(k=>typeof settings[0][k]==='string')) @@ -52,7 +58,7 @@ async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstall const bindings=installation.roleBindings,values=['operator','runtime','capture','publisher','control'].map(k=>bindings[k as keyof typeof bindings].name) if(edition>=58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name) const bridge=new Fixed44CatalogueValueBridgeData(bindings,edition) - await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:edition===59?fixed59Sql:fixed56Sql),values);cursor=true + await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:edition>=59?fixed59Sql:fixed56Sql),values);cursor=true for(;;){const page=(await s.query('FETCH FORWARD 128 FROM mm_publisher44')).rows;bridge.acceptPage(page);if(page.length===0)break} const result=bridge.finish();await s.query('CLOSE mm_publisher44');cursor=false return {catalogSha256:sha(canonical({values:result.values.snapshotSha256,catalogue:result.catalogue})),definitionSha256:result.catalogue.definitionSha256,manifestSha256:result.catalogue.manifestSha256,leafCount:result.catalogue.leafRelations} diff --git a/backend/scripts/writer-profile/expanded44-data-policy.ts b/backend/scripts/writer-profile/expanded44-data-policy.ts index ee45c186..5f6f2973 100644 --- a/backend/scripts/writer-profile/expanded44-data-policy.ts +++ b/backend/scripts/writer-profile/expanded44-data-policy.ts @@ -4,6 +4,7 @@ import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definiti import {BUILD57_PROVENANCE} from './fixed57-build-definition.js' import {BUILD58_PROVENANCE} from './fixed58-build-definition.js' import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js' +import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js' import {fixedCatalogueParentPeriodData} from './application-writer-profile-catalogue-parent-policy.js' import {GROUPS,type CatalogueEdition,type Inventory} from './catalogue-projection.js' export const EXPANDED44_POLICY_VERSION='source44-managed-leaves-3000-data-v1' as const @@ -66,8 +67,19 @@ const EXPANDED59_DATA_POLICY = Object.freeze({ maxRows: Object.freeze(Object.fromEntries(GROUPS.map(group => [group,source59BaseRows[group] + LEAVES * leafMax[group]])) as Record), definitionSha256: BUILD59_PROVENANCE.templateSha256, }) -const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY, 59: EXPANDED59_DATA_POLICY} -const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation, 59: source59PerRelation} +const source60PerRelation = new Map(source59PerRelation) +const storageUsage = source59PerRelation.get('server_poll_storage_usage')! +const removed = FIXED59_ROLE_TEMPLATE.constraints.length - FIXED60_ROLE_TEMPLATE.constraints.length +source60PerRelation.set('server_poll_storage_usage', {...storageUsage, constraints: storageUsage.constraints - removed}) +const EXPANDED60_DATA_POLICY = Object.freeze({ + ...EXPANDED59_DATA_POLICY, + version: 'source60-managed-leaves-3000-data-v1', + baseRows: Object.freeze({...source59BaseRows, constraints: source59BaseRows.constraints - removed}), + maxRows: Object.freeze({...EXPANDED59_DATA_POLICY.maxRows, constraints: EXPANDED59_DATA_POLICY.maxRows.constraints - removed}), + definitionSha256: BUILD60_PROVENANCE.templateSha256, +}) +const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY, 59: EXPANDED59_DATA_POLICY, 60: EXPANDED60_DATA_POLICY} +const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation, 59: source59PerRelation, 60: source60PerRelation} export const catalogueTopologyPolicy = (edition: CatalogueEdition) => policies[edition] export const expanded44ParentRowCountsData=()=>Object.freeze(Object.fromEntries(parents.map(name=>[name,Object.freeze({...perRelation.get(name)!})]))) export interface ManagedLeafData {readonly parent:string;readonly name:string} diff --git a/backend/scripts/writer-profile/fixed59-build-definition.test.mts b/backend/scripts/writer-profile/fixed59-build-definition.test.mts index 1dce5ed4..e40cb151 100644 --- a/backend/scripts/writer-profile/fixed59-build-definition.test.mts +++ b/backend/scripts/writer-profile/fixed59-build-definition.test.mts @@ -1,14 +1,16 @@ import assert from "node:assert/strict" import { test } from "node:test" -import { migrationManifestDigest } from "../../src/db/migration-manifest.js" +import { createHash } from "node:crypto" +import { MIGRATION_MANIFEST, migrationManifestDigest } from "../../src/db/migration-manifest.js" import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js" import { approvedDefinition } from "./catalogue.mjs" import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js" import { BUILD59_PROVENANCE, FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js" +import { BUILD60_PROVENANCE, FIXED60_ROLE_TEMPLATE } from "./fixed60-build-definition.js" import { catalogueTopologyPolicy } from "./expanded44-data-policy.js" test("source59 pins migration 0058 and alters only the IX catalogue and its existing servers references", () => { - assert.equal(BUILD59_PROVENANCE.manifestSha256, migrationManifestDigest()) + assert.equal(BUILD59_PROVENANCE.manifestSha256, createHash("sha256").update(JSON.stringify(MIGRATION_MANIFEST.slice(0, 58))).digest("hex")) assert.equal(catalogueTopologyPolicy(59).baseRelations, catalogueTopologyPolicy(58).baseRelations + 3) const added = new Set(FIXED59_ROLE_TEMPLATE.tables.filter(row => String(row.relname).startsWith("ix_segment")).map(row => row.relname)) assert.deepEqual([...added].sort(), ["ix_segment_devices", "ix_segment_revisions", "ix_segments"]) @@ -19,6 +21,15 @@ test("source59 pins migration 0058 and alters only the IX catalogue and its exis assert.equal(FIXED59_ROLE_TEMPLATE.constraints.length - FIXED58_ROLE_TEMPLATE.constraints.length, 24) }) +test("source60 changes poll storage constraints without changing writer grants or table topology", () => { + assert.equal(BUILD60_PROVENANCE.manifestSha256, migrationManifestDigest()) + const approval = { format: "application-writer-source60-definition-approval-v1", provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE } + assert.equal(approvedDefinition(approval).definitionSha256, BUILD60_PROVENANCE.templateSha256) + assert.deepEqual(FIXED60_ROLE_TEMPLATE.tables, FIXED59_ROLE_TEMPLATE.tables) + assert.deepEqual(FIXED60_ROLE_TEMPLATE.roleGrants, FIXED59_ROLE_TEMPLATE.roleGrants) + assert.equal(catalogueTopologyPolicy(60).baseRows.constraints, catalogueTopologyPolicy(59).baseRows.constraints - 1) +}) + test("source59 accepts the exact independently reviewed definition and restricts IX runtime grants", () => { const approval = { format: "application-writer-source59-definition-approval-v1", provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE } assert.equal(approvedDefinition(approval).definitionSha256, BUILD59_PROVENANCE.templateSha256) diff --git a/backend/scripts/writer-profile/fixed60-build-definition.ts b/backend/scripts/writer-profile/fixed60-build-definition.ts new file mode 100644 index 00000000..91bd2279 --- /dev/null +++ b/backend/scripts/writer-profile/fixed60-build-definition.ts @@ -0,0 +1,34 @@ +import { canonical, sha } from "./application-writer-profile-canonical.js" +import { sorted, type Inventory } from "./catalogue-projection.js" +import { FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js" +import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "../../src/db/server-poll-writer-profile.js" + +const quotaConstraint = "server_poll_storage_usage_check2" +const definitions = new Map([ + ["server_poll_storage_usage_admissions_check", "CHECK ((admissions >= 0))"], + ["server_poll_storage_rows_charge", "CHECK ((reserved_rows = ((admissions * 4019) + (compacted_admissions * 2))))"], + ["server_poll_storage_bytes_charge", "CHECK ((reserved_bytes = (((admissions * 8421376) + (compacted_admissions * 32768)) + archive_bytes)))"], +]) + +export const FIXED60_ROLE_TEMPLATE: Readonly = Object.freeze({ + ...FIXED59_ROLE_TEMPLATE, + constraints: sorted(FIXED59_ROLE_TEMPLATE.constraints.filter(row => row.conname !== quotaConstraint || row.relname !== "server_poll_storage_usage").map(row => { + const definition = row.relname === "server_poll_storage_usage" ? definitions.get(String(row.conname)) : undefined + return definition ? { ...row, definition } : row + })), + functions: sorted(FIXED59_ROLE_TEMPLATE.functions.map(row => row.proname !== "server_poll_storage_admission_guard" ? row : { + ...row, + definition: String(row.definition) + .replace(/^ IF\(SELECT count\(\*\) FROM public\.server_poll_storage_usage WHERE scope IN\('global','owner:'\|\|NEW\.owner_id\)\n[^]*?THEN RAISE EXCEPTION 'poll admission quota exhausted'; END IF;\n/m, "") + .replace("poll admission quota unavailable", "poll admission counters unavailable"), + })), +}) + +export const BUILD60_PROVENANCE = Object.freeze({ + format: "source60-poll-journal-profile-v1", + manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256, + templateSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256, +}) + +const digest = sha(canonical(FIXED60_ROLE_TEMPLATE)) +if (digest !== BUILD60_PROVENANCE.templateSha256) throw new Error("Fixed60 writer catalogue changed: " + digest) diff --git a/backend/scripts/writer-profile/operator-contract.mjs b/backend/scripts/writer-profile/operator-contract.mjs index acfbaca9..8de1b17c 100644 --- a/backend/scripts/writer-profile/operator-contract.mjs +++ b/backend/scripts/writer-profile/operator-contract.mjs @@ -13,8 +13,9 @@ export const UPGRADE_APPROVAL_FORMAT='application-writer-upgrade44-to56-approval export const UPGRADE57_APPROVAL_FORMAT='application-writer-upgrade56-to57-approval-v1' export const UPGRADE58_APPROVAL_FORMAT='application-writer-upgrade57-to58-approval-v1' export const UPGRADE59_APPROVAL_FORMAT='application-writer-upgrade58-to59-approval-v1' +export const UPGRADE60_APPROVAL_FORMAT='application-writer-upgrade59-to60-approval-v1' export const REBIND58_APPROVAL_FORMAT='application-writer-rebind58-after-restore-approval-v1' -export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format) +export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format) function parsedApproval(value,format=publicationFormat){ const upgrade=isUpgradeApprovalFormat(format) const keys=['format','manifestSha256','definitionSha256','catalogSha256','expectedHeadSha256','validityMs','expiresAt'] diff --git a/backend/scripts/writer-profile/publisher.mjs b/backend/scripts/writer-profile/publisher.mjs index 4caf7a72..0560f595 100644 --- a/backend/scripts/writer-profile/publisher.mjs +++ b/backend/scripts/writer-profile/publisher.mjs @@ -3,12 +3,13 @@ import pg from 'pg' import {createPrivateKey,createPublicKey,sign,X509Certificate} from 'node:crypto' import {open,lstat,realpath,unlink} from 'node:fs/promises' import {readProtected,writeFile,withJournalLease} from './operator-files.mjs' -import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs' +import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs' import {BUILD44_PROVENANCE} from './fixed44-build-definition.js' import {BUILD56_PROVENANCE} from './fixed56-build-definition.js' import {BUILD57_PROVENANCE} from './fixed57-build-definition.js' import {BUILD58_PROVENANCE} from './fixed58-build-definition.js' import {BUILD59_PROVENANCE} from './fixed59-build-definition.js' +import {BUILD60_PROVENANCE} from './fixed60-build-definition.js' import path from 'node:path' import {captureDatabaseSourceObservation,assertDatabaseSourceObservationCurrent} from '../../src/db/database-source-observation.js' import {MIGRATION_MANIFEST,migrationManifestDigest} from '../../src/db/migration-manifest.js' @@ -21,6 +22,7 @@ const upgradeTransitions = { [UPGRADE57_APPROVAL_FORMAT]: { predecessor: BUILD56_PROVENANCE, successor: BUILD57_PROVENANCE, oldEdition: 56, newEdition: 57 }, [UPGRADE58_APPROVAL_FORMAT]: { predecessor: BUILD57_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 57, newEdition: 58 }, [UPGRADE59_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD59_PROVENANCE, oldEdition: 58, newEdition: 59 }, + [UPGRADE60_APPROVAL_FORMAT]: { predecessor: BUILD59_PROVENANCE, successor: BUILD60_PROVENANCE, oldEdition: 59, newEdition: 60 }, [REBIND58_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 58, newEdition: 58 }, } export function requireCurrentCatalogueDefinition(approval,definition){ @@ -253,7 +255,7 @@ async function preflightCurrentProfile(pool,{deadlineAt=Date.now()+120000}={}){ } async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){ const manifestSha256=migrationManifestDigest() - const expected=definition?.edition===59?BUILD59_PROVENANCE:definition?.edition===58?BUILD58_PROVENANCE:undefined + const expected={58:BUILD58_PROVENANCE,59:BUILD59_PROVENANCE,60:BUILD60_PROVENANCE}[definition?.edition] if(!expected||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==expected.templateSha256)throw Error('Approved current writer definition required') return session(pool,deadlineAt,async s=>{ s.phase('source-catalogue-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true) @@ -264,7 +266,7 @@ async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){ const initial=await sourceVerifier.verify(facade,observation,options) const {security,catalogSha256}=await observeCurrentCatalogue(s,manifestSha256) const current=await readCurrent(s,installation,{validNow:false}) - const allowedHeads=definition.edition===59?[BUILD58_PROVENANCE,BUILD59_PROVENANCE]:[BUILD58_PROVENANCE] + const allowedHeads=definition.edition===60?[BUILD59_PROVENANCE,BUILD60_PROVENANCE]:definition.edition===59?[BUILD58_PROVENANCE,BUILD59_PROVENANCE]:[BUILD58_PROVENANCE] if(!current||!allowedHeads.some(head=>head.templateSha256===current.policy.definitionSha256&&head.manifestSha256===current.policy.manifestSha256)|| canonical(current.policy.source)!==canonical(sourceCoordinates(first))||canonical(current.policy.roles)!==canonical(security.roles)){ throw Error('Approved same-installation writer predecessor required') diff --git a/backend/src/db/controlled-migration-history.ts b/backend/src/db/controlled-migration-history.ts index c73e8c3a..0679211c 100644 --- a/backend/src/db/controlled-migration-history.ts +++ b/backend/src/db/controlled-migration-history.ts @@ -9,8 +9,9 @@ export const REVIEWED_PREDECESSORS = [ { length: 44, manifestSha256: "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5" }, { length: 56, manifestSha256: "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521" }, { length: 57, manifestSha256: "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc" }, + { length: 58, manifestSha256: "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb" }, ] as const -export const REVIEWED_SUCCESSOR_MANIFEST = "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb" +export const REVIEWED_SUCCESSOR_MANIFEST = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9" export const canonical = (value: unknown): string => JSON.stringify(value, (_key, item: unknown) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item) export async function observation(intent: DatabaseSchemaIntent, pin: MigrationReview, existingKey = false) { // Fixed, purpose-separated server-keyed ACK issuer. Caller-supplied hashes @@ -56,7 +57,7 @@ export async function exactHistory(rows: Record[], current: Ret return refuse("Migration release is not the exact internally recorded legacy release") } if (pin ? terminal.observationSha256 !== await observation(terminal.intent, pin, existingKey) : - terminal.intent.manifestSha256 !== manifest || terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) { + terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) { return refuse("Migration receipt is not the exact internally recorded file ACK") } pin ??= MIGRATION_MANIFEST[36] diff --git a/backend/src/db/controlled-migrations.test.ts b/backend/src/db/controlled-migrations.test.ts index 10b213ff..81df254c 100644 --- a/backend/src/db/controlled-migrations.test.ts +++ b/backend/src/db/controlled-migrations.test.ts @@ -200,13 +200,13 @@ test("reviewed 44 migration history keeps its original keyed receipts and resume assert(f.events.every(event => !event.startsWith("file:"))) }) -test("complete 56 receipts with or without the inherited 44 prefix dispatch the remaining two files", async () => { +test("complete 56 receipts with or without the inherited 44 prefix dispatch the remaining files", async () => { for (const mixed of [false, true]) { const f = fixture() f.seedCompletedHistory(56, index => mixed && index < 44 ? reviewed44 : reviewed56) const previous = structuredClone([...f.history.values()]) assert.equal((await f.run()).completedFiles, pins.length) - assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql", "file:0058_internet_exchange.sql"]) + assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql", "file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"]) assert.deepEqual([...f.history.values()].slice(0, 56), previous) f.events.length = 0 assert.equal((await f.run()).completedFiles, pins.length) @@ -214,15 +214,23 @@ test("complete 56 receipts with or without the inherited 44 prefix dispatch the } }) -test("the source58 migration history needs only the IX migration", async () => { +test("the source58 migration history advances through IX and the poll journal migration", async () => { const f = fixture() f.seedCompletedHistory(57, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : reviewed57) const previous = structuredClone([...f.history.values()]) assert.equal((await f.run()).completedFiles, pins.length) - assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0058_internet_exchange.sql"]) + assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"]) assert.deepEqual([...f.history.values()].slice(0, 57), previous) }) +test("the source59 production prefix advances only through the poll journal migration", async () => { + const f = fixture() + f.seedCompletedHistory(58, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : index < 57 ? reviewed57 : + "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb") + assert.equal((await f.run()).completedFiles, pins.length) + assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0059_server_poll_journal_limits.sql"]) +}) + test("history 56 cannot omit a receipt or interleave another manifest", async () => { for (const invalid of ["incomplete", "interleaved"] as const) { const f = fixture() diff --git a/backend/src/db/database-runtime-writer-profile.test.ts b/backend/src/db/database-runtime-writer-profile.test.ts index 99bf9c70..e28ba458 100644 --- a/backend/src/db/database-runtime-writer-profile.test.ts +++ b/backend/src/db/database-runtime-writer-profile.test.ts @@ -2,10 +2,10 @@ import assert from "node:assert/strict" import { HEAD_DOMAIN, POLICY_DOMAIN, sha } from "./application-writer-profile-format.js" import { stagedModelClient, syntheticFixture } from "./application-writer-profile-registry-read-model.test.js" import { approvedRuntimeWriterProfile } from "./database-runtime-writer-profile.js" -import { IX_WRITER_PROFILE_DEFINITION_SHA256, IX_WRITER_PROFILE_MANIFEST_SHA256 } from "./internet-exchange-writer-profile.js" +import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js" const { subject, policy: basePolicy, state, signBody } = syntheticFixture("1") -const policy = { ...basePolicy, definitionSha256: IX_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: IX_WRITER_PROFILE_MANIFEST_SHA256 } +const policy = { ...basePolicy, definitionSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256 } const expected = { installationId: subject.installationId, source: policy.source, roles: policy.roles } function publish(next: typeof policy, previous = state.latest[0]) { diff --git a/backend/src/db/database-runtime-writer-profile.ts b/backend/src/db/database-runtime-writer-profile.ts index 7c5d8a02..2815bb62 100644 --- a/backend/src/db/database-runtime-writer-profile.ts +++ b/backend/src/db/database-runtime-writer-profile.ts @@ -1,7 +1,7 @@ import { z } from "zod" import { canonical, epoch, publicKey, type ApplicationWriterPolicy } from "./application-writer-profile-format.js" import { readCurrentApplicationWriterProfile, type ApplicationWriterRegistryReadSql } from "./application-writer-profile-registry-read.js" -import { IX_WRITER_PROFILE_DEFINITION_SHA256, IX_WRITER_PROFILE_MANIFEST_SHA256 } from "./internet-exchange-writer-profile.js" +import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js" const digest = z.string().regex(/^[a-f0-9]{64}$/) const approvalSchema = z.object({ @@ -26,8 +26,8 @@ export function approvedRuntimeWriterProfile( async check(client: ApplicationWriterRegistryReadSql) { const current = await readCurrentApplicationWriterProfile(client, subject) const policy = current?.policy - if (!current || !policy || policy.definitionSha256 !== IX_WRITER_PROFILE_DEFINITION_SHA256 || - policy.manifestSha256 !== IX_WRITER_PROFILE_MANIFEST_SHA256 || + if (!current || !policy || policy.definitionSha256 !== POLL_WRITER_PROFILE_DEFINITION_SHA256 || + policy.manifestSha256 !== POLL_WRITER_PROFILE_MANIFEST_SHA256 || canonical(policy.source) !== canonical(expected.source) || canonical(policy.roles) !== canonical(expected.roles)) { throw new Error("Текущий подписанный профиль записи PostgreSQL не подтверждён") } diff --git a/backend/src/db/migration-manifest.test.ts b/backend/src/db/migration-manifest.test.ts index 51c2b918..36c0a2a3 100644 --- a/backend/src/db/migration-manifest.test.ts +++ b/backend/src/db/migration-manifest.test.ts @@ -12,10 +12,10 @@ const reviewed = (source: string, extra: Partial = {}) => { const bytes = Buffer.from(source), file = "9000_fixture.sql" return () => analyzeMigration(file, bytes, { file, sha256: createHash("sha256").update(bytes).digest("hex"), transaction: "owner-transaction", selfMarker: false, opaqueBodies: 0, bodyReview: [], effects: ["Explicit inert fixture review"], ...extra }) } -await test("all 58 exact file pins and every top-level schema operation are inventoried", () => { - assert.equal(inventory.length, 58); assert.equal(MIGRATION_MANIFEST.length, 58) +await test("all 59 exact file pins and every top-level schema operation are inventoried", () => { + assert.equal(inventory.length, 59); assert.equal(MIGRATION_MANIFEST.length, 59) assert.equal(inventory.filter(file => file.transaction === "owner-transaction").length, 17) - assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 41) + assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 42) assert(inventory.every(file => file.operations.length === file.statementCount && file.effects.length > 0)) let tables = new Set() for (const file of inventory) { @@ -32,8 +32,8 @@ await test("DO BEGIN and stored function BEGIN are never transaction boundaries" assert.equal(endpoint.topLevelTransactionControls.length, 2); assert.equal(endpoint.opaqueBodies.length, 2) assert.deepEqual(endpoint.opaqueBodies.map(body => body.kind), ["stored-function-body", "executed-do-body"]) }) -await test("0035 through 0058 have exact atomic file-owned terminal markers", () => { - assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index", "0058_internet_exchange"]) +await test("0035 through 0059 have exact atomic file-owned terminal markers", () => { + assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index", "0058_internet_exchange", "0059_server_poll_journal_limits"]) for (const file of inventory.filter(file => file.selfMarker)) { assert.equal(file.selfMarker!.atomicWithAllFileEffects, true); assert.equal(file.selfMarker!.statement, file.statementCount - 2); assert.equal(file.currentOuterMarkerGap, false) } assert.equal(inventory.filter(file => file.currentOuterMarkerGap).length, 34) }) diff --git a/backend/src/db/migration-manifest.ts b/backend/src/db/migration-manifest.ts index c58c5f49..e2fc5ff1 100644 --- a/backend/src/db/migration-manifest.ts +++ b/backend/src/db/migration-manifest.ts @@ -891,6 +891,19 @@ const classifiedMigrationPins: readonly MigrationReview[] = [ "Allows the IX Node server type without changing existing rows.", "Adds versioned IX configuration and device references." ] + }, + { + "file": "0059_server_poll_journal_limits.sql", + "sha256": "9b638ed5649ef75359b24ef61c80bf59390372c98c713447ddb6e32e61b6f5be", + "transaction": "self-managed-single-transaction", + "selfMarker": true, + "opaqueBodies": 1, + "bodyReview": [ + "Replaces the existing invoker admission trigger function and removes only the aggregate count, row and byte ceilings from the insertion path. Authority, locking, accounting, compaction and GC checks remain enforced." + ], + "effects": [ + "Removes the journal quota while preserving exact reconciliation constraints and all previously retained histories." + ] } ] diff --git a/backend/src/db/server-poll-writer-profile.ts b/backend/src/db/server-poll-writer-profile.ts new file mode 100644 index 00000000..8ad73376 --- /dev/null +++ b/backend/src/db/server-poll-writer-profile.ts @@ -0,0 +1,2 @@ +export const POLL_WRITER_PROFILE_MANIFEST_SHA256 = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9" +export const POLL_WRITER_PROFILE_DEFINITION_SHA256 = "0bf9596d6fec209959bb00761e1396ad292d50a1e7d4c9f17d1222da75007a49" diff --git a/backend/src/modules/mcp/server-poll-registration.test.ts b/backend/src/modules/mcp/server-poll-registration.test.ts index 3165b196..4730b26b 100644 --- a/backend/src/modules/mcp/server-poll-registration.test.ts +++ b/backend/src/modules/mcp/server-poll-registration.test.ts @@ -10,9 +10,8 @@ test("registration exposes one actual global write plan and fixed nondiagnostic registerServerPollAction(((...args: Parameters) => { calls.push(args) }) as typeof add) assert.equal(calls.length, 1) const [id, tool, description, section, permission, effect, scope, schema, handlers] = calls[0] - assert.match(description, /8 на владельца, 128 на приложение/) - assert.match(description, /Архивирование сохраняет аудит/) - assert.match(description, /pollStorageCapacity/) + assert.doesNotMatch(description, /8 на владельца|128 на приложение/) + assert.match(description, /pollStorageUsage/) assert.equal(mcpOperationDescriptorSchema.shape.title.safeParse(description).success, true) assert.equal(id, "servers.poll"); assert.equal(tool, "mm_server_poll_plan"); assert.equal(section, "servers") assert.equal(permission, "mm:servers:write"); assert.equal(effect, "write"); assert.equal(scope, "global"); assert.equal(handlers.version, 1) diff --git a/backend/src/modules/mcp/server-poll-registration.ts b/backend/src/modules/mcp/server-poll-registration.ts index aa6ed6a5..cba4746b 100644 --- a/backend/src/modules/mcp/server-poll-registration.ts +++ b/backend/src/modules/mcp/server-poll-registration.ts @@ -3,12 +3,11 @@ import { SERVER_POLL_OPERATION } from "../../services/server-poll-authority.js" import { SERVER_POLL_MCP_OPERATION_VERSION } from "./server-poll-actions.js" import { createProductionServerPollMcpAdapter } from "./server-poll-production.js" import { registerMcpService } from "./service-registry.js" -import { SERVER_POLL_STORAGE_POLICY } from "../../services/server-poll-storage-model.js" -/** Normal startup enrolls quota-bound storage before public tools are served. */ +/** Normal startup enrolls durable storage before public tools are served. */ export function registerServerPollAction(register: typeof add) { const adapter = createProductionServerPollMcpAdapter() registerMcpService(SERVER_POLL_OPERATION, adapter.service) - register(SERVER_POLL_OPERATION, "mm_server_poll_plan", `Полный опрос и история. Резерв: ${SERVER_POLL_STORAGE_POLICY.ownerAttempts} на владельца, ${SERVER_POLL_STORAGE_POLICY.globalAttempts} на приложение. Архивирование сохраняет аудит; остаток зависит от объёма истории. Статус: pollStorageCapacity в MCP overview.`, "servers", "mm:servers:write", "write", "global", adapter.schema, + register(SERVER_POLL_OPERATION, "mm_server_poll_plan", "Полный опрос и история. Число журналов отображается в pollStorageUsage в MCP overview.", "servers", "mm:servers:write", "write", "global", adapter.schema, { version: SERVER_POLL_MCP_OPERATION_VERSION, target: adapter.target, prepare: adapter.prepare }) } diff --git a/backend/src/routes/mcp.ts b/backend/src/routes/mcp.ts index 354ca30c..bc66bb85 100644 --- a/backend/src/routes/mcp.ts +++ b/backend/src/routes/mcp.ts @@ -39,7 +39,7 @@ import { humanWireguardExportMetadata, readHumanWireguardExportArtifact } from " import { humanArtifactReceipts } from "../modules/mcp/human-artifact-receipts.js" import { readHumanHostFilesArtifact } from "../modules/mcp/host-files-artifact.js" import { loadLogExportArtifactMetadata } from "../modules/mcp/log-artifacts.js" -import { readServerPollCapacity } from "../services/server-poll-capacity.js" +import { readServerPollUsage } from "../services/server-poll-capacity.js" import { connectProbeStorage } from "../services/server-probe-storage-connection.js" const uuid = z.string().uuid() @@ -56,12 +56,12 @@ export function mcpDevicePlanArguments(serverId: number, input: z.infer z.object({ id: uuid }).parse(params).id const actorOf = (actor?: AuthUser) => { if (!actor) throw new McpError("UNAUTHORIZED", "Требуется вход", 401); return actor } -async function pollCapacityForPortal(ownerId:string,admin:boolean){ +async function pollUsageForPortal(ownerId:string,admin:boolean){ const options={deadlineAt:Date.now()+3000} let connection:Awaited>|undefined try{ connection=await connectProbeStorage(options) - return await readServerPollCapacity({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin) + return await readServerPollUsage({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin) }catch{return {status:"unavailable" as const}} finally{connection?.release()} } @@ -254,7 +254,7 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent = (SELECT count(*)::int FROM mcp_requests r JOIN mcp_connections c ON c.id=r.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND r.created_at>now()-interval '24 hours' AND r.status IN ('error','denied')) AS errors, (SELECT count(*)::int FROM mcp_plans p JOIN mcp_connections c ON c.id=p.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND p.state='awaiting-approval' AND p.expires_at>now()) AS approvals, (SELECT count(*)::int FROM mcp_operations o JOIN mcp_connections c ON c.id=o.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND o.state IN ('running','pending')) AS running`, [admin, actor.id]) - return { ...summary, pollStorageCapacity:await pollCapacityForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() } + return { ...summary, pollStorageUsage:await pollUsageForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() } }) for (const table of ["requests", "plans", "operations", "audit", "drift"] as const) { app.get(`/mcp/${table}`, async request => { diff --git a/backend/src/services/server-poll-archive-accounting.test.ts b/backend/src/services/server-poll-archive-accounting.test.ts index a1960d24..2d293d24 100644 --- a/backend/src/services/server-poll-archive-accounting.test.ts +++ b/backend/src/services/server-poll-archive-accounting.test.ts @@ -114,7 +114,7 @@ test("empty/global0 and full128 ledgers use complete exact global/owner counters const empty = fixture([]); await empty.run(); assert.deepEqual(empty.counts(), { factories: 0, charges: 0 }) const f = fixture(Array.from({ length: 128 }, (_, n) => full(n + 1, "owner-" + Math.floor(n / 8)))) await f.run(); assert.deepEqual(f.batches, [128, 0]); assert.deepEqual(f.counts(), { factories: 0, charges: 0 }) - assert.equal(Number(f.usage.find(row => row.scope === "global")!.reserved_bytes), policy.globalBytes) + assert.equal(Number(f.usage.find(row => row.scope === "global")!.reserved_bytes), 128 * (policy.attemptBytes + policy.admissionBytes)) }) test("compact336 plus full reservations and multiowner usage paginate in128-row bounded metadata batches", async () => { @@ -197,14 +197,13 @@ test("archive/admission identity, binding, context, timestamps and retention met } }) -test("full heavy-count global129 and owner9 refuse even if usage counters claim conservation", async () => { - await refused(fixture(Array.from({ length: 129 }, (_, n) => full(n + 1, "owner-" + Math.floor(n / 8)))).run()) - await refused(fixture(Array.from({ length: 9 }, (_, n) => full(n + 1, "one-owner"))).run()) +test("130 full reservations for one owner pass exact accounting", async () => { + await fixture(Array.from({ length: 130 }, (_, n) => full(n + 1, "one-owner"))).run() }) -test("compacted rows still pay retained bytes and cannot share an already fully charged owner", async () => { +test("compacted rows and full reservations share the same exact owner accounting", async () => { const f = fixture([...Array.from({ length: 8 }, (_, n) => full(n + 1, "owner")), await compact(100, "owner")]) - await refused(f.run()) + await f.run() }) test("nonadjacent duplicate receipt IDs cannot count twice even when cardinality/owner counters agree", async () => { @@ -218,12 +217,12 @@ test("compacted timestamp must be an actual finite SQL timestamp", async () => { } }) -test("retained archive bytes can exhaust global budget before heavy-count or row-count limits", async () => { +test("paid archive bytes above the former global budget retain exact accounting", async () => { const compacts = await Promise.all(Array.from({ length: 336 }, (_, n) => compact(1000 + n, "archive-owner-" + n))) const f = fixture([...Array.from({ length: 127 }, (_, n) => full(n + 1, "full-owner-" + Math.floor(n / 8))), ...compacts]) const global = f.usage.find(row => row.scope === "global")! - assert.equal(global.admissions, 127); assert(Number(global.reserved_rows) < policy.globalRows); assert(Number(global.reserved_bytes) > policy.globalBytes) - await refused(f.run()) + assert.equal(global.admissions, 127); assert(Number(global.reserved_bytes) > 128 * (policy.attemptBytes + policy.admissionBytes)) + await f.run() }) test("invalid numeric counters cannot hide through coercion or extra scopes", async () => { diff --git a/backend/src/services/server-poll-archive-accounting.ts b/backend/src/services/server-poll-archive-accounting.ts index 3c15f26a..f69eaa0a 100644 --- a/backend/src/services/server-poll-archive-accounting.ts +++ b/backend/src/services/server-poll-archive-accounting.ts @@ -6,7 +6,6 @@ import { createServerPollArchiveChargeVerifier, type verifyServerPollArchiveChar import type { createServerPollRetiredArchiveChargeVerifier } from "./server-poll-retired-archive.js" const BATCH = 128 -const MAX_ENTRIES = Math.floor(policy.globalBytes / policy.admissionBytes) const fail: () => never = () => { throw new PollStorageRefused() } const uuid = /^[a-f\d]{8}-[a-f\d]{4}-[1-8][a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12}$/i function integer(value: unknown): number { @@ -40,8 +39,7 @@ const QUERY = `SELECT a.receipt_id AS admission_receipt_id,a.identity_kind,a.exe async function verify(sql: ProbeStorageSql, factory: () => Promise, retiredFactory: typeof createServerPollRetiredArchiveChargeVerifier) { const global = zero(), owners = new Map() - const seenReceipts = new Set() - let cursor: string | null = null, count = 0, charge: typeof verifyServerPollArchiveCharge | undefined + let cursor: string | null = null, charge: typeof verifyServerPollArchiveCharge | undefined let retiredCharge: Awaited> | undefined // All queries are fixed. Only metadata, hashes and actual lengths cross the // driver boundary; even a full global history never becomes a JS blob. @@ -50,11 +48,10 @@ async function verify(sql: ProbeStorageSql, factory: () => Promise BATCH) fail() for (const raw of rows) { const row: Record = structuredClone(raw) - if (++count > MAX_ENTRIES || typeof row.admission_receipt_id !== "string" || !uuid.test(row.admission_receipt_id) || - seenReceipts.has(row.admission_receipt_id) || typeof row.admission_owner_id !== "string" || !row.admission_owner_id.length || + if (typeof row.admission_receipt_id !== "string" || !uuid.test(row.admission_receipt_id) || + cursor !== null && row.admission_receipt_id <= cursor || typeof row.admission_owner_id !== "string" || !row.admission_owner_id.length || row.admission_owner_id.length > 200 || row.admission_owner_id.trim() !== row.admission_owner_id || /[\x00-\x1f\x7f]/.test(row.admission_owner_id)) fail() cursor = row.admission_receipt_id - seenReceipts.add(cursor) let addition: Total if (row.storage_state === "full") { if (row.receipt_id !== null || row.compact_at !== null || row.admission_archive_bytes !== null || row.admission_activity_at !== null) fail() @@ -78,22 +75,20 @@ async function verify(sql: ProbeStorageSql, factory: () => Promise policy.globalAttempts || global.bytes > policy.globalBytes || global.rows > policy.globalRows || - owned.heavy > policy.ownerAttempts || owned.bytes > policy.ownerBytes || owned.rows > policy.ownerRows) fail() + for (const total of [global, owned]) for (const key of Object.keys(total) as (keyof Total)[]) total[key] = integer(total[key] + addition[key]) } if (rows.length < BATCH) break } // Orphan archives cannot disappear from the allocation scan and manufacture // credit. Admission identity is retained until the original retention GC. if ((await sql.query("SELECT r.receipt_id FROM server_poll_archives r LEFT JOIN server_poll_storage_admissions a USING(receipt_id) WHERE a.receipt_id IS NULL LIMIT 1")).rows.length) fail() - let scopeCursor: string | null = null, seenGlobal = false, usageCount = 0 + let scopeCursor: string | null = null, seenGlobal = false const seenOwners = new Set() for (;;) { const rows: Record[] = (await sql.query("SELECT scope,admissions,compacted_admissions,archive_bytes,reserved_rows,reserved_bytes FROM server_poll_storage_usage WHERE ($1::text IS NULL OR scope>$1) ORDER BY scope LIMIT 128 FOR SHARE", [scopeCursor])).rows if (!Array.isArray(rows) || rows.length > BATCH) fail() for (const row of rows) { - if (++usageCount > MAX_ENTRIES + 1 || typeof row.scope !== "string" || row.scope === scopeCursor) fail() + if (typeof row.scope !== "string" || row.scope === scopeCursor) fail() scopeCursor = row.scope let expected: Total if (row.scope === "global") { if (seenGlobal) fail(); seenGlobal = true; expected = global } diff --git a/backend/src/services/server-poll-capacity.test.ts b/backend/src/services/server-poll-capacity.test.ts index a609c950..38743e85 100644 --- a/backend/src/services/server-poll-capacity.test.ts +++ b/backend/src/services/server-poll-capacity.test.ts @@ -1,8 +1,8 @@ import assert from "node:assert/strict" import { test } from "node:test" -import { readServerPollCapacity, type ServerPollCapacitySql } from "./server-poll-capacity.js" +import { readServerPollUsage, type ServerPollCapacitySql } from "./server-poll-capacity.js" import { SERVER_POLL_STORAGE_POLICY as policy } from "./server-poll-storage-model.js" -import { mcpPollStorageCapacitySchema } from "@mmapp/contracts/mcp" +import { mcpPollStorageUsageSchema } from "@mmapp/contracts/mcp" const row = (owner: number | null = 2, global = 10) => ({ retention_days: 30, global_compacted_admissions:"0",global_archive_bytes:"0",owner_compacted_admissions:owner===null?null:"0",owner_archive_bytes:owner===null?null:"0", @@ -16,8 +16,8 @@ function fixture(rows: Record[] = [row()]) { test("one parameterized bounded snapshot reads only settings and exact owner/global usage without maintenance or locks", async () => { const f = fixture(), owner = "operator' OR true--" - const result = await readServerPollCapacity(f.sql, owner, true) - assert.deepEqual(result, { status: "observed", owner: { used: 2, limit: 8, remaining: 6 }, global: { exhausted: false, usage: { used: 10, limit: 128, remaining: 118 } }, retentionDays: 30 }) + const result = await readServerPollUsage(f.sql, owner, true) + assert.deepEqual(result, { status: "observed", ownerFull: 2, globalFull: 10, retentionDays: 30 }) assert.equal(f.calls.length, 1); const { text, values } = f.calls[0] assert.deepEqual(values, ["owner:" + owner]); assert(!text.includes(owner)); assert.match(text, /^SELECT\b/) assert.match(text, /FROM public\.mcp_settings\b/); assert.equal((text.match(/LEFT JOIN public\.server_poll_storage_usage\b/g) ?? []).length, 2) @@ -26,44 +26,44 @@ test("one parameterized bounded snapshot reads only settings and exact owner/glo assert(!text.includes("server_poll_storage_admissions")) }) -test("non-admin hides all global counts while reporting exhaustion; admin alone receives numbers", async () => { - for (const used of [0, 127, 128]) { - const f = fixture([row(0, used)]), result = await readServerPollCapacity(f.sql, "one-owner", false) - assert.deepEqual(result, { status: "observed", owner: { used: 0, limit: 8, remaining: 8 }, global: { exhausted: used === 128, usage: null }, retentionDays: 30 }) +test("non-admin hides all global counts", async () => { + for (const used of [0, 128, 2000]) { + const f = fixture([row(0, used)]), result = await readServerPollUsage(f.sql, "one-owner", false) + assert.deepEqual(result, { status: "observed", ownerFull: 0, globalFull: null, retentionDays: 30 }) assert(!JSON.stringify(result).includes("one-owner")); assert(!JSON.stringify(result).includes('"ready"')) } }) -test("owner eight/full global128 expose zero remaining and only entirely null missing owner is zero", async () => { - const full = await readServerPollCapacity(fixture([row(8, 128)]).sql, "owner", true) - assert.deepEqual(full, { status: "observed", owner: { used: 8, limit: 8, remaining: 0 }, global: { exhausted: true, usage: { used: 128, limit: 128, remaining: 0 } }, retentionDays: 30 }) - assert.deepEqual(await readServerPollCapacity(fixture([row(null, 0)]).sql, "new-owner", false), { status: "observed", owner: { used: 0, limit: 8, remaining: 8 }, global: { exhausted: false, usage: null }, retentionDays: 30 }) +test("observes twenty owner journals and more than 128 global journals", async () => { + const full = await readServerPollUsage(fixture([row(20, 130)]).sql, "owner", true) + assert.deepEqual(full, { status: "observed", ownerFull: 20, globalFull: 130, retentionDays: 30 }) + assert.deepEqual(await readServerPollUsage(fixture([row(null, 0)]).sql, "new-owner", false), { status: "observed", ownerFull: 0, globalFull: null, retentionDays: 30 }) }) test("SQL failure/missing relation or settings/global accounting is unavailable and never zero", async () => { for (const code of ["42P01", "08006", "57014"]) { let calls = 0 - assert.deepEqual(await readServerPollCapacity({ async query() { calls++; throw Object.assign(Error("private SQL failure"), { code }) } }, "owner", true), { status: "unavailable" }) + assert.deepEqual(await readServerPollUsage({ async query() { calls++; throw Object.assign(Error("private SQL failure"), { code }) } }, "owner", true), { status: "unavailable" }) assert.equal(calls, 1) } for (const rows of [[], [row(), row()], [{}], [{ ...row(), global_admissions: null, global_reserved_rows: null, global_reserved_bytes: null }], [{ ...row(), retention_days: undefined }]]) - assert.deepEqual(await readServerPollCapacity(fixture(rows).sql, "owner", true), { status: "unavailable" }) + assert.deepEqual(await readServerPollUsage(fixture(rows).sql, "owner", true), { status: "unavailable" }) }) test("invalid owner/admin values refuse before query; trimmed Unicode identity remains exact", async () => { for (const owner of ["", " ", " owner", "owner ", "a\nb", "a\0b", "a\x7fb", "a\x85b", "a".repeat(201), undefined, 42]) { - const f = fixture(); assert.deepEqual(await readServerPollCapacity(f.sql, owner as string, false), { status: "unavailable" }); assert.equal(f.calls.length, 0) + const f = fixture(); assert.deepEqual(await readServerPollUsage(f.sql, owner as string, false), { status: "unavailable" }); assert.equal(f.calls.length, 0) } - const invalid = fixture(); assert.deepEqual(await readServerPollCapacity(invalid.sql, "owner", "true" as unknown as boolean), { status: "unavailable" }); assert.equal(invalid.calls.length, 0) - const unicode = fixture(); assert.equal((await readServerPollCapacity(unicode.sql, "Оператор😀", false)).status, "observed"); assert.deepEqual(unicode.calls[0].values, ["owner:Оператор😀"]) + const invalid = fixture(); assert.deepEqual(await readServerPollUsage(invalid.sql, "owner", "true" as unknown as boolean), { status: "unavailable" }); assert.equal(invalid.calls.length, 0) + const unicode = fixture(); assert.equal((await readServerPollUsage(unicode.sql, "Оператор😀", false)).status, "observed"); assert.deepEqual(unicode.calls[0].values, ["owner:Оператор😀"]) }) -test("counter triples reject malformed canonical bigint values, partial NULL, mismatch, excessive limits and owner greater than global", async () => { +test("counter triples reject malformed canonical bigint values, partial NULL, mismatch and owner greater than global", async () => { const invalid = [undefined, null, true, false, {}, [], 1n, NaN, Infinity, -1, -0, 1.5, Number.MAX_SAFE_INTEGER + 1, "", " 0", "0 ", "00", "01", "+1", "-0", "1.0", "1e0", "0x1", "9007199254740992"] for (const field of ["global_admissions", "global_reserved_rows", "global_reserved_bytes", "owner_admissions", "owner_reserved_rows", "owner_reserved_bytes","global_compacted_admissions","global_archive_bytes","owner_compacted_admissions","owner_archive_bytes"]) - for (const value of invalid) assert.deepEqual(await readServerPollCapacity(fixture([{ ...row(), [field]: value }]).sql, "owner", true), { status: "unavailable" }, field + ":" + String(value)) - for (const candidate of [row(9, 10), row(8, 7), row(0, 129), { ...row(), owner_reserved_rows: "0" }, { ...row(), global_reserved_bytes: "0" }, { ...row(null), owner_reserved_bytes: "0" }]) - assert.deepEqual(await readServerPollCapacity(fixture([candidate]).sql, "owner", true), { status: "unavailable" }) + for (const value of invalid) assert.deepEqual(await readServerPollUsage(fixture([{ ...row(), [field]: value }]).sql, "owner", true), { status: "unavailable" }, field + ":" + String(value)) + for (const candidate of [row(8, 7), { ...row(), owner_reserved_rows: "0" }, { ...row(), global_reserved_bytes: "0" }, { ...row(null), owner_reserved_bytes: "0" }]) + assert.deepEqual(await readServerPollUsage(fixture([candidate]).sql, "owner", true), { status: "unavailable" }) }) function compactRow(ownerHeavy:number,ownerCompact:number,globalHeavy=ownerHeavy,globalCompact=ownerCompact,encoded=59075){ @@ -73,27 +73,10 @@ function compactRow(ownerHeavy:number,ownerCompact:number,globalHeavy=ownerHeavy global_reserved_rows:String(globalHeavy*4019+globalCompact*2),global_reserved_bytes:String(globalHeavy*8421376+globalCompact*(32768+encoded))} } -test("336 retained histories remain paid while DTO used counts heavy slots and remaining obeys all caps",async()=>{ - const result=await readServerPollCapacity(fixture([compactRow(1,336)]).sql,"owner",true) - assert.deepEqual(result,{status:"observed",owner:{used:1,limit:8,remaining:3},global:{exhausted:false,usage:{used:1,limit:128,remaining:123}},retentionDays:30}) -}) - -test("largest permitted archives still allow one new poll after336 histories; shared contract accepts the byte-limited remainder",async()=>{ - const before=await readServerPollCapacity(fixture([compactRow(0,336,0,336,131072)]).sql,"owner",true) - assert(before.status==="observed");assert.equal(before.owner.remaining,1) - assert.deepEqual(mcpPollStorageCapacitySchema.parse(before),before) - const occupied=await readServerPollCapacity(fixture([compactRow(1,336,1,336,131072)]).sql,"owner",true) - assert(occupied.status==="observed");assert.equal(occupied.owner.used,1);assert.equal(occupied.owner.remaining,0) - assert.deepEqual(mcpPollStorageCapacitySchema.parse(occupied),occupied) - assert.equal(mcpPollStorageCapacitySchema.safeParse({...occupied,owner:{used:8,limit:8,remaining:1}}).success,false) -}) - -test("byte-full retained history cannot report available admission despite unused heavy slots",async()=>{ - const ownerFull=await readServerPollCapacity(fixture([compactRow(0,2000,0,2000,40)]).sql,"owner",false) - assert(ownerFull.status==="observed");assert.equal(ownerFull.owner.used,0);assert.equal(ownerFull.owner.remaining,0) - assert.equal(ownerFull.global.exhausted,false);assert.equal(ownerFull.global.usage,null) - const globalFull=await readServerPollCapacity(fixture([compactRow(0,0,0,32600,40)]).sql,"owner",false) - assert(globalFull.status==="observed");assert.equal(globalFull.global.exhausted,true);assert.equal(globalFull.global.usage,null) +test("retained archive accounting does not impose a cumulative quota", async () => { + const result = await readServerPollUsage(fixture([compactRow(20, 2000, 130, 32600, 131072)]).sql, "owner", true) + assert.deepEqual(result, {status:"observed", ownerFull:20, globalFull:130, retentionDays:30}) + assert.deepEqual(mcpPollStorageUsageSchema.parse(result), result) }) test("missing 0041 fields, malformed archive accounting and owner/global mismatch fail unavailable",async()=>{ @@ -101,24 +84,24 @@ test("missing 0041 fields, malformed archive accounting and owner/global mismatc for(const value of [legacy,{...row(),owner_compacted_admissions:null},{...row(),global_archive_bytes:"1"}, compactRow(0,1,0,1,39),compactRow(0,1,0,1,131073),compactRow(0,2,0,1), {...compactRow(0,1),owner_reserved_rows:"0"},{...compactRow(0,1),global_reserved_bytes:"0"}]) - assert.deepEqual(await readServerPollCapacity(fixture([value]).sql,"owner",true),{status:"unavailable"}) + assert.deepEqual(await readServerPollUsage(fixture([value]).sql,"owner",true),{status:"unavailable"}) }) test("canonical PostgreSQL bigint strings and safe integer numbers are accepted; retention current1..365 only", async () => { const numeric = Object.fromEntries(Object.entries(row()).map(([key, value]) => [key, Number(value)])) - assert.equal((await readServerPollCapacity(fixture([numeric]).sql, "owner", true)).status, "observed") + assert.equal((await readServerPollUsage(fixture([numeric]).sql, "owner", true)).status, "observed") for (const days of [1, "1", 365, "365"]) { - const result = await readServerPollCapacity(fixture([{ ...row(), retention_days: days }]).sql, "owner", false) + const result = await readServerPollUsage(fixture([{ ...row(), retention_days: days }]).sql, "owner", false) assert(result.status === "observed"); assert.equal(result.retentionDays, Number(days)) } - for (const days of [0, 366, -1, 1.5, "01", null, undefined]) assert.deepEqual(await readServerPollCapacity(fixture([{ ...row(), retention_days: days }]).sql, "owner", false), { status: "unavailable" }) + for (const days of [0, 366, -1, 1.5, "01", null, undefined]) assert.deepEqual(await readServerPollUsage(fixture([{ ...row(), retention_days: days }]).sql, "owner", false), { status: "unavailable" }) }) test("returned DTO is deeply frozen and independent of later SQL row/result mutations", async () => { - const original = row(), rows = [original], f = fixture(rows), result = await readServerPollCapacity(f.sql, "owner", true) + const original = row(), rows = [original], f = fixture(rows), result = await readServerPollUsage(f.sql, "owner", true) assert(result.status === "observed"); const expected = structuredClone(result) Object.assign(original, row(8, 128), { retention_days: 365 }); rows.splice(0) - assert.deepEqual(result, expected); assert(Object.isFrozen(result)); assert(Object.isFrozen(result.owner)); assert(Object.isFrozen(result.global)); assert(Object.isFrozen(result.global.usage)) - assert.throws(() => { (result.owner as { used: number }).used = 7 }) - assert(Object.isFrozen(await readServerPollCapacity(fixture([]).sql, "owner", false))) + assert.deepEqual(result, expected); assert(Object.isFrozen(result)) + assert.throws(() => { (result as { ownerFull: number }).ownerFull = 7 }) + assert(Object.isFrozen(await readServerPollUsage(fixture([]).sql, "owner", false))) }) diff --git a/backend/src/services/server-poll-capacity.ts b/backend/src/services/server-poll-capacity.ts index 2eb308b2..e1bd5a75 100644 --- a/backend/src/services/server-poll-capacity.ts +++ b/backend/src/services/server-poll-capacity.ts @@ -1,10 +1,6 @@ -import { pollStorageUsageRemaining, type PollStorageUsage } from "./server-poll-storage-model.js" +import type { McpPollStorageUsage } from "@mmapp/contracts/mcp" +import { validatePollStorageUsage } from "./server-poll-storage-model.js" -export type ServerPollCapacity = - | Readonly<{ status: "unavailable" }> - | Readonly<{ status: "observed"; owner: Readonly<{ used: number; limit: 8; remaining: number }>; - global: Readonly<{ exhausted: boolean; usage: Readonly<{ used: number; limit: 128; remaining: number }> | null }>; - retentionDays: number }> export interface ServerPollCapacitySql { query(text: string, values: unknown[]): Promise<{ rows: Record[] }> } // A single bounded MVCC snapshot. No admission enumeration, maintenance, locks @@ -16,28 +12,22 @@ FROM public.mcp_settings s LEFT JOIN public.server_poll_storage_usage g ON g.scope='global' LEFT JOIN public.server_poll_storage_usage o ON o.scope=$1 WHERE s.id=1 LIMIT 2` -const unavailable: ServerPollCapacity = Object.freeze({ status: "unavailable" }) +const unavailable: McpPollStorageUsage = Object.freeze({ status: "unavailable" }) function integer(value: unknown): number | undefined { if (typeof value === "number") return Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0) ? value : undefined if (typeof value !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(value) || value.length > 16) return undefined const parsed = Number(value) return Number.isSafeInteger(parsed) ? parsed : undefined } -function usage(admissions: unknown, rows: unknown, bytes: unknown, compacted:unknown, archive:unknown, scope:"global"|"owner") { +function usage(admissions: unknown, rows: unknown, bytes: unknown, compacted:unknown, archive:unknown) { const used=integer(admissions),reservedRows=integer(rows),reservedBytes=integer(bytes),compactedAttempts=integer(compacted),archiveBytes=integer(archive) if(used===undefined||reservedRows===undefined||reservedBytes===undefined||compactedAttempts===undefined||archiveBytes===undefined)return undefined - const value:PollStorageUsage={attempts:used,rows:reservedRows,bytes:reservedBytes,compactedAttempts,archiveBytes} - const remaining=pollStorageUsageRemaining(value,scope) - return remaining===undefined?undefined:{value,remaining} + return validatePollStorageUsage({attempts:used,rows:reservedRows,bytes:reservedBytes,compactedAttempts,archiveBytes}) } -/** Read-only heavy reservation availability with paid retained history. Used - * counts heavy slots; remaining also accounts for archive bytes/rows. This - * observation does not verify archive MACs and is never an admission promise. - * Missing or - * inconsistent accounting is unavailable rather than a fabricated free slot. +/** Read-only count of full journals. Missing or inconsistent accounting is unavailable. * Non-admin callers receive no global usage numbers or other owner identities. */ -export async function readServerPollCapacity(sql: ServerPollCapacitySql, ownerId: string, admin: boolean): Promise { +export async function readServerPollUsage(sql: ServerPollCapacitySql, ownerId: string, admin: boolean): Promise { if (typeof ownerId !== "string" || ownerId.trim() !== ownerId || !ownerId.length || [...ownerId].length > 200 || /[\u0000-\u001f\u007f-\u009f]/.test(ownerId) || typeof admin !== "boolean") return unavailable try { @@ -48,16 +38,14 @@ export async function readServerPollCapacity(sql: ServerPollCapacitySql, ownerId // Capture primitive fields synchronously. DTOs never alias mutable driver // rows and are frozen independently of the SQL adapter's result lifetime. const retentionDays = integer(row.retention_days) - const globalUsed=usage(row.global_admissions,row.global_reserved_rows,row.global_reserved_bytes,row.global_compacted_admissions,row.global_archive_bytes,"global") + const globalUsed=usage(row.global_admissions,row.global_reserved_rows,row.global_reserved_bytes,row.global_compacted_admissions,row.global_archive_bytes) const ownerFields=[row.owner_admissions,row.owner_reserved_rows,row.owner_reserved_bytes,row.owner_compacted_admissions,row.owner_archive_bytes] - const ownerUsed=ownerFields.every(value=>value===null)?usage(0,0,0,0,0,"owner"):usage(...ownerFields as [unknown,unknown,unknown,unknown,unknown],"owner") + const ownerUsed=ownerFields.every(value=>value===null)?usage(0,0,0,0,0):usage(...ownerFields as [unknown,unknown,unknown,unknown,unknown]) if(retentionDays===undefined||retentionDays<1||retentionDays>365||!globalUsed||!ownerUsed)return unavailable for(const field of ["attempts","rows","bytes","compactedAttempts","archiveBytes"] as const) - if(ownerUsed.value[field]! > globalUsed.value[field]!)return unavailable - const otherCount=globalUsed.value.compactedAttempts!-ownerUsed.value.compactedAttempts!,otherBytes=globalUsed.value.archiveBytes!-ownerUsed.value.archiveBytes! + if(ownerUsed[field] > globalUsed[field])return unavailable + const otherCount=globalUsed.compactedAttempts-ownerUsed.compactedAttempts,otherBytes=globalUsed.archiveBytes-ownerUsed.archiveBytes if(otherBytesotherCount*131072)return unavailable - return Object.freeze({status:"observed",owner:Object.freeze({used:ownerUsed.value.attempts,limit:8,remaining:ownerUsed.remaining}), - global:Object.freeze({exhausted:globalUsed.remaining===0, - usage:admin?Object.freeze({used:globalUsed.value.attempts,limit:128,remaining:globalUsed.remaining}):null}),retentionDays}) + return Object.freeze({status:"observed",ownerFull:ownerUsed.attempts,globalFull:admin?globalUsed.attempts:null,retentionDays}) } catch { return unavailable } } diff --git a/backend/src/services/server-poll-operation-retirement.owned.test.ts b/backend/src/services/server-poll-operation-retirement.owned.test.ts index 08e85bc1..b3cbea81 100644 --- a/backend/src/services/server-poll-operation-retirement.owned.test.ts +++ b/backend/src/services/server-poll-operation-retirement.owned.test.ts @@ -22,7 +22,7 @@ const { PARTITION_WRITER_ADVISORY_KEY } = await import("./partition-write-transa const { collectExpiredServerPollStorage,collectExpiredServerPollStorageForTests } = await import("./server-poll-storage-retention.js") const { connectProbeStorage } = await import("./server-probe-storage-connection.js") const { createServerPollStorage,PollStorageRefused,PollStorageUnknown } = await import("./server-poll-storage.js") -const { readServerPollCapacity } = await import("./server-poll-capacity.js") +const { readServerPollUsage } = await import("./server-poll-capacity.js") const { tickMcpWorkers } = await import("../modules/mcp/workers.js") const { Client } = await import("pg") const proof=(domain:string,value:unknown)=>privateSecretFingerprint(fingerprint(value),domain) @@ -380,8 +380,8 @@ try{ const before = await usage() assert.equal(Number(before.compacted_admissions), 336) assert.equal(Number(before.admissions), 0) - const capacity = await readServerPollCapacity(pool, first.ownerId, true) - assert(capacity.status === "observed" && capacity.owner.remaining >= 1) + const capacity = await readServerPollUsage(pool, first.ownerId, true) + assert(capacity.status === "observed" && capacity.ownerFull >= 0) const now = Date.now() const scope = { receiptId: randomUUID(), executionId: randomUUID(), kind: "mcp" as const, ownerId: first.ownerId, issuedAt: now - 1000, expiresAt: now + 300000, bindingProof: "a".repeat(64), contextProof: "b".repeat(64) } diff --git a/backend/src/services/server-poll-rest-authority.sql-helper.ts b/backend/src/services/server-poll-rest-authority.sql-helper.ts index 7078ba6d..6f52140e 100644 --- a/backend/src/services/server-poll-rest-authority.sql-helper.ts +++ b/backend/src/services/server-poll-rest-authority.sql-helper.ts @@ -18,6 +18,7 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr const { executeDurableServerPollRest } = await import("./server-poll-rest.js") const ownerId = "owned-rest-authority-" + randomUUID(), name = "owned-rest-authority" let serverId: number | undefined, requests = 0, checkedAdmissions = 0, dispatchFailure = false + const batchIds: number[] = [] let app: Awaited> | undefined let httpOrigin = "" const paths: string[] = [] @@ -25,15 +26,17 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr requests++; paths.push(request.url ?? "") try { assert.equal(request.method, "GET") - const rows = (await pool.query(`SELECT a.receipt_id,a.claim_token,a.claim_attempted_at,a.used_rows, + if (!batchIds.length) { + const rows = (await pool.query(`SELECT a.receipt_id,a.claim_token,a.claim_attempted_at,a.used_rows, u.admissions,u.reserved_rows,u.reserved_bytes::text FROM server_poll_storage_admissions a JOIN server_poll_storage_usage u ON u.scope='owner:'||a.owner_id JOIN server_poll_executions e USING(receipt_id) WHERE a.owner_id=$1 AND a.identity_kind='rest' AND e.context_proof=a.context_proof`, [ownerId])).rows - assert.equal(rows.length, 1); assert.equal(rows[0].claim_token, null) - assert(rows[0].claim_attempted_at); assert(Number(rows[0].used_rows) >= 1) - assert.equal(Number(rows[0].admissions), 1); assert.equal(Number(rows[0].reserved_rows), 4019) - assert.equal(rows[0].reserved_bytes, "8421376"); checkedAdmissions++ + assert.equal(rows.length, 1); assert.equal(rows[0].claim_token, null) + assert(rows[0].claim_attempted_at); assert(Number(rows[0].used_rows) >= 1) + assert.equal(Number(rows[0].admissions), 1); assert.equal(Number(rows[0].reserved_rows), 4019) + assert.equal(rows[0].reserved_bytes, "8421376"); checkedAdmissions++ + } const result = request.url === "/rest/system/identity" ? { name } : request.url === "/rest/system/resource" ? { version: "7.synthetic", "board-name": "owned", uptime: "1h", "cpu-load": "2", "free-memory": "1024", "total-memory": "2048" } : request.url === "/rest/interface" ? [{ type: "ether", name: "owned-interface" }] @@ -107,6 +110,26 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr assert.equal(typeof reply.body.latencyMs, "number"); assert(Number(reply.body.latencyMs) >= 0) const serialized = JSON.stringify(reply.body) for (const secret of ["SYNTHETIC-USER", "SYNTHETIC-PRIVATE-PASSWORD", "rawInterfaces", "rawIpAddresses", "192.0.2.1", "owned-interface"]) assert.equal(serialized.includes(secret), false) + if (options.httpRoute) { + const { rows } = await pool.query(`INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) + SELECT $1||'-'||n,'127.0.0.1',$2,true,'SYNTHETIC-USER','SYNTHETIC-PRIVATE-PASSWORD',false,true + FROM generate_series(1,20) AS n RETURNING id`, [ownerId, port]) + batchIds.push(...rows.map(row => Number(row.id))) + const { rows: [mcpBefore] } = await pool.query("SELECT count(*)::int AS n FROM mcp_requests") + for (const id of batchIds) { + // The WebUI queues one full poll at a time. + const result = await call(String(id), context()) + assert.equal(result.statusCode, 200, JSON.stringify(result.body)) + assert.equal(result.body.serverId, id) + assert.equal(result.body.status, "online") + } + assert.equal(requests, 4 * (1 + batchIds.length)) + assert.equal(dispatchFailure, false) + const { rows: [usage] } = await pool.query("SELECT admissions::int AS n FROM server_poll_storage_usage WHERE scope=$1", ["owner:" + ownerId]) + assert.equal(usage.n, 1 + batchIds.length) + assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_requests")).rows[0].n, mcpBefore.n) + console.log("Owned WebUI HTTP poll batch:", JSON.stringify({ successfulServers: batchIds.length, ownerJournals: usage.n, mcpRequestsAdded: 0 })) + } const result = { statusCode: reply.statusCode, elapsedMs, nativeGets: requests, dispatchesAfterConsumedAdmission: checkedAdmissions, actualRestAuthorityFactory: true, actualProductionSession: true, actualRegisteredHttpRoute: options.httpRoute === true, actualSignedJwt: options.httpRoute === true, httpAppSchedulerStarted: false, negativeStatuses: negative.map(value => value.statusCode), exactLegacySnapshotShape: true, privateFieldsAbsent: true, automaticReplay: false } @@ -114,6 +137,6 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr } finally { await app?.close() listener.closeAllConnections(); if (listener.listening) await new Promise(yes => listener.close(() => yes())) - if (serverId !== undefined) await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId]) + if (serverId !== undefined) await pool.query("UPDATE servers SET enabled=false WHERE id=ANY($1::bigint[])", [[serverId, ...batchIds]]) } } diff --git a/backend/src/services/server-poll-storage-fill.sql-helper.ts b/backend/src/services/server-poll-storage-fill.sql-helper.ts index f1a893a4..40648368 100644 --- a/backend/src/services/server-poll-storage-fill.sql-helper.ts +++ b/backend/src/services/server-poll-storage-fill.sql-helper.ts @@ -1,24 +1,31 @@ import assert from "node:assert/strict" import { randomUUID } from "node:crypto" -import { writeFile } from "node:fs/promises" +import { mkdir, writeFile } from "node:fs/promises" import { resolve } from "node:path" -/** Owned normal/historical SQL profiles only; fixed global quota evidence. */ -export async function acceptPollStorageGlobalCapSql(){ +/** Owned normal/historical SQL profiles only; acceptance across the former quotas. */ +export async function acceptPollStorageScaleSql(){ assert([process.env.MMAPP_OWN_SERVER_POLL_STORAGE,process.env.MMAPP_OWN_SERVER_POLL_STORAGE_FRESH].includes("true")) const {pool}=await import("../db/index.js") const {createServerPollStorage}=await import("./server-poll-storage.js") const globalBefore=Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions) - const fill=await Promise.allSettled(Array.from({length:130-globalBefore},async()=>{ - const scope={receiptId:randomUUID(),kind:"rest" as const,executionId:randomUUID(),ownerId:"owned-fill-"+randomUUID(),bindingProof:"a".repeat(64),contextProof:"b".repeat(64),issuedAt:Date.now()-1000,expiresAt:Date.now()+180000} + const ownerId="owned-fill-"+randomUUID() + const claim = async () => { + const scope={receiptId:randomUUID(),kind:"rest" as const,executionId:randomUUID(),ownerId,bindingProof:"a".repeat(64),contextProof:"b".repeat(64),issuedAt:Date.now()-1000,expiresAt:Date.now()+180000} return createServerPollStorage({scope,connectionId:null,maxStages:8,authorize:async()=>{}}).claim({deadlineAt:Date.now()+60000},async sql=>{ await sql.query("INSERT INTO server_poll_executions(receipt_id,identity_kind,execution_id,binding_proof,context_ciphertext,context_proof) VALUES($1,'rest',$2,$3,'SYNTHETIC',$4)",[scope.receiptId,scope.executionId,scope.bindingProof,scope.contextProof]) }) - })) - assert.equal(fill.filter(row=>row.status==="fulfilled").length,128-globalBefore) - assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions),128) - assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n,128) + } + const additional = 130 + for (let index = 0; index < additional; index += 5) { + await Promise.all(Array.from({ length: 5 }, claim)) + } + assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope=$1",["owner:"+ownerId])).rows[0].admissions),additional) + assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions),globalBefore + additional) + assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n,globalBefore + additional) assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=0")).rows[0].n,0) const evidence=await(await import("./server-poll-storage-restore-evidence.sql-helper.js")).pollStorageRestoreEvidence(pool) - await writeFile(resolve(process.env.MCP_STATE_DIR!,"poll-storage-owned-restore-evidence.json"),JSON.stringify(evidence),{flag:"wx",mode:0o600}) - return {globalAdmissions:128,actualAdmissions:128,concurrentIndependentOwners:true,attemptsRefused:2,zeroOrphanCounters:true} + const stateDir = resolve(process.env.MCP_STATE_DIR!) + await mkdir(stateDir, { recursive: true, mode: 0o700 }) + await writeFile(resolve(stateDir,"poll-storage-owned-restore-evidence.json"),JSON.stringify(evidence),{flag:"wx",mode:0o600}) + return {globalAdmissions:globalBefore + additional,ownerAdmissions:additional,concurrentAdmissions:true,zeroOrphanCounters:true} } diff --git a/backend/src/services/server-poll-storage-fresh.sql.test.ts b/backend/src/services/server-poll-storage-fresh.sql.test.ts index ac33a2e8..91b514c6 100644 --- a/backend/src/services/server-poll-storage-fresh.sql.test.ts +++ b/backend/src/services/server-poll-storage-fresh.sql.test.ts @@ -16,6 +16,13 @@ try{ assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n,MIGRATION_MANIFEST.length) assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage")).rows,[{scope:"global",admissions:0,reserved_rows:0,reserved_bytes:0,compacted_admissions:0,archive_bytes:0}]) assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n,0) + const { FIXED60_ROLE_TEMPLATE } = await import("../../scripts/writer-profile/fixed60-build-definition.js") + const constraints = (await pool.query(`SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint + WHERE conrelid='public.server_poll_storage_usage'::regclass AND contype='c' ORDER BY conname`)).rows + assert.deepEqual(constraints, FIXED60_ROLE_TEMPLATE.constraints.filter(row => row.relname === "server_poll_storage_usage" && row.contype === "c") + .map(({ conname, definition }) => ({ conname, definition })).sort((a,b) => String(a.conname).localeCompare(String(b.conname)))) + const guard = await pool.query("SELECT pg_get_functiondef('public.server_poll_storage_admission_guard()'::regprocedure) AS definition") + assert.equal(guard.rows[0].definition, FIXED60_ROLE_TEMPLATE.functions.find(row => row.proname === "server_poll_storage_admission_guard")?.definition) const migration=await readFile(new URL("../../drizzle/0039_server_poll_storage.sql",import.meta.url),"utf8") const name="owned_poll_enroll_"+randomUUID().replaceAll("-","") await pool.query(`CREATE DATABASE "${name}" TEMPLATE template0`) @@ -68,7 +75,9 @@ try{ await pool.query("DELETE FROM mcp_artifacts WHERE id=$1", [freshArtifactId]) await pool.query("DELETE FROM mcp_connections WHERE id=$1", [artifactConnectionId]) console.log("Owned fresh poll storage:",JSON.stringify({normalStartupTwice:true,migrations:MIGRATION_MANIFEST.length,globalZeroSeed:true,legacyPrefix:38,nonemptyJournalRefusedBeforeDdl:true,oldRowsPreserved:true,noForgedMarker:true,actualWorkerTickWithMcpDisabled:true,boundedRequestAuditAndArtifactRetention:true})) - if (process.env.MMAPP_OWN_SERVER_POLL_SETTINGS_EPOCH === "true") { + if (process.env.MMAPP_OWN_SERVER_POLL_SCALE_ONLY === "true") { + console.log("Owned fresh poll scale:", JSON.stringify(await (await import("./server-poll-storage-fill.sql-helper.js")).acceptPollStorageScaleSql())) + } else if (process.env.MMAPP_OWN_SERVER_POLL_SETTINGS_EPOCH === "true") { await (await import("../db/server-poll-settings-epoch.owned-helper.js")).acceptServerPollSettingsEpochMigrationSql(pool) } else if (process.env.MMAPP_OWN_SERVER_POLL_ATOMIC_MAINTENANCE === "true") { await (await import("./server-poll-atomic-owned-helper.js")).acceptAtomicServerPollOwned() @@ -89,6 +98,6 @@ try{ if(!publicOnly&&process.env.MMAPP_OWN_SERVER_POLL_AUTHORITY_ONLY!=="true")await(await import("./server-poll-storage-execution.sql-helper.js")).acceptServerPollStorageExecutionSql() if(!publicOnly)await(await import("./server-poll-rest-authority.sql-helper.js")).acceptServerPollRestAuthoritySql() if(process.env.MMAPP_OWN_SERVER_POLL_AUTHORITY_ONLY!=="true")await(await import("../modules/mcp/server-poll-http.sql-helper.js")).acceptServerPollPublicRuntimeSql() - console.log("Owned fresh poll quota:",JSON.stringify(await(await import("./server-poll-storage-fill.sql-helper.js")).acceptPollStorageGlobalCapSql())) + console.log("Owned fresh poll scale:",JSON.stringify(await(await import("./server-poll-storage-fill.sql-helper.js")).acceptPollStorageScaleSql())) } }finally{await closePool()} diff --git a/backend/src/services/server-poll-storage-model.test.ts b/backend/src/services/server-poll-storage-model.test.ts index f180a3c7..02c04c78 100644 --- a/backend/src/services/server-poll-storage-model.test.ts +++ b/backend/src/services/server-poll-storage-model.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import { test } from "node:test" import { SERVER_POLL_STORAGE_POLICY as policy, PollStorageRefused, pollStoragePolicy, pollStorageScope, - pollStorageQuotaFit, pollStorageUsageRemaining, pollStorageGcEligible, type PollStorageScope, type PollStorageGcCandidate } from "./server-poll-storage-model.js" + validatePollStorageUsage, pollStorageGcEligible, type PollStorageScope, type PollStorageGcCandidate } from "./server-poll-storage-model.js" const DAY = 86400000 const scope: PollStorageScope = { receiptId: "5f4aaf7b-cc19-4b36-b693-5ce092a03852", executionId: "b332191d-bf58-4196-a629-f30367a48ef7", @@ -18,13 +18,10 @@ test("reservations cover all journal rows and metadata independently, with immut assert.equal(policy.attemptRows, 1 + 2008 + 2008 + 1 + 1) assert.equal(policy.attemptBytes, 8 * 1024 * 1024) assert.equal(policy.admissionBytes, 32768) - assert.equal(policy.globalAttempts, 128); assert.equal(policy.ownerAttempts, 8) - assert.equal(policy.globalRows, 128 * 4019); assert.equal(policy.ownerRows, 8 * 4019) - assert.equal(policy.globalBytes, 128 * (8388608 + 32768)); assert.equal(policy.ownerBytes, 8 * (8388608 + 32768)) const input = { ...policy, retentionDays: 30 }, cloned = pollStoragePolicy(input) input.retentionDays = 1 assert.equal(cloned.retentionDays, 30); assert.equal(Object.isFrozen(cloned), true) - for (const patch of [{ globalAttempts: 129 }, { attemptRows: 4018 }, { ownerBytes: policy.ownerBytes + 1 }, { retentionDays: 0 }, + for (const patch of [{ attemptRows: 4018 }, { attemptBytes: policy.attemptBytes + 1 }, { retentionDays: 0 }, { retentionDays: 366 }, { safetyWindowMs: 59999 }, { safetyWindowMs: DAY + 1 }, { retentionDays: 1.5 }]) { assert.throws(() => pollStoragePolicy({ ...policy, ...patch }), PollStorageRefused) } @@ -47,34 +44,16 @@ test("scope validates original identity, clones and freezes, and never invents a assert.equal(pollStorageScope(scope, { now: 2000, allowExpired: true }).expiresAt, 2000) }) -test("quota checks exact capacity and cannot refund admission allowance to fit an extra attempt", () => { - assert.equal(pollStorageQuotaFit(usage(127), usage(7)), true) - assert.equal(pollStorageQuotaFit(usage(128), empty), false) - assert.equal(pollStorageQuotaFit(usage(8), usage(8)), false) - for (const dimension of ["bytes", "rows", "attempts"] as const) { - assert.equal(pollStorageQuotaFit({ ...usage(127), [dimension]: usage(127)[dimension] + 1 }, empty), false) - assert.equal(pollStorageQuotaFit(usage(127), { ...usage(7), [dimension]: usage(7)[dimension] + 1 }), false) - for (const bad of [-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, "0", undefined]) { - assert.equal(pollStorageQuotaFit({ ...empty, [dimension]: bad } as typeof empty, empty), false) +test("exact accounting accepts past quotas and rejects forged totals", () => { + for (const attempts of [0, 8, 20, 130, 1000]) { + const value = usage(attempts) + assert.equal(validatePollStorageUsage(value).attempts, attempts) + for (const dimension of ["bytes", "rows", "attempts"] as const) { + for (const invalid of [-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, "0", undefined, value[dimension] + 1]) + assert.throws(() => validatePollStorageUsage({ ...value, [dimension]: invalid }), PollStorageRefused) } } - assert.equal(pollStorageQuotaFit({ ...usage(127), bytes: policy.globalBytes - policy.attemptBytes }, empty), false) - assert.equal(pollStorageQuotaFit(empty, usage(1)), false) - assert.equal(pollStorageQuotaFit({ ...empty, bytes: Number.MAX_SAFE_INTEGER }, empty), false) -}) - -test("quota refuses partial, undercharged and mismatched reservation counters", () => { - const malformed = [{ attempts: 1 }, { bytes: policy.attemptBytes, rows: policy.attemptRows }, - { ...usage(1), bytes: policy.attemptBytes }, { ...usage(1), bytes: usage(1).bytes - 1 }, - { ...usage(1), rows: policy.attemptRows - 1 }, { ...usage(1), rows: policy.attemptRows + 1 }, - { ...usage(1), attempts: 2 }, { ...empty, bytes: 1 }, { ...empty, rows: 1 }, - { ...usage(1), bytes: usage(1).bytes + 1 }, { ...usage(1), extra: true }] - for (const value of malformed) { - assert.equal(pollStorageQuotaFit(value as typeof empty, empty), false) - assert.equal(pollStorageQuotaFit(usage(7), value as typeof empty), false) - } - assert.equal(pollStorageQuotaFit(usage(7), usage(7)), true) - assert.equal(pollStorageQuotaFit(empty, empty), true) + assert.throws(() => validatePollStorageUsage({ ...empty, extra: true } as typeof empty), PollStorageRefused) }) test("GC is strictly after expiry plus retention/safety and persisted gcNotBefore", () => { @@ -86,38 +65,17 @@ test("GC is strictly after expiry plus retention/safety and persisted gcNotBefor assert.equal(pollStorageGcEligible(candidate({ scope: { ...scope, kind: "mcp" }, mcpTerminal: true }), policy, boundary + 1), true) }) -test("336 paid hourly histories and one heavy poll fit unchanged owner bytes and rows",()=>{ - const retained=compactUsage(1,336) - assert(retained.bytes{ const good=compactUsage(0,1,40) - assert.equal(pollStorageQuotaFit(good,good),true) - assert.equal(pollStorageQuotaFit(compactUsage(0,1,131072),compactUsage(0,1,131072)),true) + assert.deepEqual(validatePollStorageUsage(good),good) + assert.deepEqual(validatePollStorageUsage(compactUsage(20,336,131072)),compactUsage(20,336,131072)) const {archiveBytes:_bytes,...missingArchive}=good,{compactedAttempts:_count,...missingCount}=good for(const value of [missingArchive,missingCount,{...good,archiveBytes:undefined},{...good,compactedAttempts:undefined}, compactUsage(0,1,39),compactUsage(0,1,131073),{...good,bytes:good.bytes-1},{...good,rows:good.rows+1}, {...good,compactedAttempts:-0},{...good,archiveBytes:NaN},{...good,opaque:true}, {...usage(0),compactedAttempts:0,archiveBytes:1},compactUsage(0,Number.MAX_SAFE_INTEGER,40)]){ - assert.equal(pollStorageQuotaFit(value as typeof good,value as typeof good),false) - assert.equal(pollStorageUsageRemaining(value as typeof good,"owner"),undefined) + assert.throws(() => validatePollStorageUsage(value as typeof good), PollStorageRefused) } - assert.equal(pollStorageQuotaFit({...empty,compactedAttempts:0,archiveBytes:0},empty),true) - assert.equal(pollStorageQuotaFit(compactUsage(0,1,41),compactUsage(0,1,40)),false,"No other compact admission can own the unexplained byte") -}) - -test("free heavy slots do not imply another full byte/row reservation fits",()=>{ - const owner=compactUsage(0,2000,40),global=compactUsage(0,32600,40) - assert(owner.bytes<=policy.ownerBytes);assert(global.bytes<=policy.globalBytes) - assert.equal(pollStorageUsageRemaining(owner,"owner"),0) - assert.equal(pollStorageUsageRemaining(global,"global"),0) - assert.equal(pollStorageQuotaFit(global,owner),false) - assert.equal(pollStorageUsageRemaining(compactUsage(0,2056,40),"owner"),undefined) }) test("retention increases, persisted retention/safety, recent stages and long original authority all delay GC", () => { diff --git a/backend/src/services/server-poll-storage-model.ts b/backend/src/services/server-poll-storage-model.ts index 9f676a8d..2fd6b789 100644 --- a/backend/src/services/server-poll-storage-model.ts +++ b/backend/src/services/server-poll-storage-model.ts @@ -11,20 +11,11 @@ export interface PollStoragePolicy { attemptBytes: number admissionBytes: number attemptRows: number - globalAttempts: number - ownerAttempts: number - globalBytes: number - ownerBytes: number - globalRows: number - ownerRows: number retentionDays: number safetyWindowMs: number } export const SERVER_POLL_STORAGE_POLICY: Readonly = Object.freeze({ attemptBytes: ATTEMPT_BYTES, admissionBytes: ADMISSION_BYTES, attemptRows: ATTEMPT_ROWS, - globalAttempts: 128, ownerAttempts: 8, - globalBytes: 128 * (ATTEMPT_BYTES + ADMISSION_BYTES), ownerBytes: 8 * (ATTEMPT_BYTES + ADMISSION_BYTES), - globalRows: 128 * ATTEMPT_ROWS, ownerRows: 8 * ATTEMPT_ROWS, retentionDays: 14, safetyWindowMs: 60000, }) @@ -40,7 +31,7 @@ const days = (value: unknown): value is number => integer(value) && value >= 1 & const uuid = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) const hash = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value) -/** Trusted composition only. Fixed reservations/caps cannot be weakened by a +/** Trusted composition only. Per-poll charges cannot be changed by a * caller; only retention and its safety window are configurable. */ export function pollStoragePolicy(raw: unknown = SERVER_POLL_STORAGE_POLICY): Readonly { if (!record(raw) || Object.keys(raw).some(key => !Object.hasOwn(SERVER_POLL_STORAGE_POLICY, key))) refuse() @@ -74,7 +65,7 @@ export function pollStorageScope(raw: unknown, options: { now: number; allowExpi } export interface PollStorageUsage { attempts: number; bytes: number; rows: number; compactedAttempts?: number; archiveBytes?: number } -function usage(raw: PollStorageUsage) { +export function validatePollStorageUsage(raw: PollStorageUsage) { if (!record(raw)) refuse() const compact = Object.hasOwn(raw,"compactedAttempts"), archive = Object.hasOwn(raw,"archiveBytes") const keys = Object.keys(raw).sort().join(",") @@ -87,33 +78,6 @@ function usage(raw: PollStorageUsage) { if (!integer(expectedRows) || !integer(expectedBytes) || raw.rows !== expectedRows || raw.bytes !== expectedBytes) refuse() return { ...raw, compactedAttempts:count, archiveBytes:encoded } } -/** Available NEW full reservations under every unchanged cap. SQL aggregate - * equality and all retained charge MACs must be checked by the admission owner; - * these arithmetic checks cannot authenticate compaction or free UNKNOWN. */ -export function pollStorageUsageRemaining(raw: PollStorageUsage, scope: "global"|"owner", rawPolicy:PollStoragePolicy=SERVER_POLL_STORAGE_POLICY):number|undefined { - try { - const policy=pollStoragePolicy(rawPolicy), value=usage(raw) - if(scope!=="global"&&scope!=="owner")refuse() - const attempts=scope==="global"?policy.globalAttempts:policy.ownerAttempts - const bytes=scope==="global"?policy.globalBytes:policy.ownerBytes, rows=scope==="global"?policy.globalRows:policy.ownerRows - if(value.attempts>attempts||value.bytes>bytes||value.rows>rows)refuse() - return Math.min(attempts-value.attempts,Math.floor((bytes-value.bytes)/(policy.attemptBytes+policy.admissionBytes)),Math.floor((rows-value.rows)/policy.attemptRows)) - }catch{return undefined} -} -/** Exact counters, including full reservations and paid retained archives. */ -export function pollStorageQuotaFit(globalUsage: PollStorageUsage, ownerUsage: PollStorageUsage, - rawPolicy: PollStoragePolicy = SERVER_POLL_STORAGE_POLICY): boolean { - try { - const policy = pollStoragePolicy(rawPolicy) - const global=usage(globalUsage),owner=usage(ownerUsage) - return (pollStorageUsageRemaining(global,"global",policy)??0)>0 && (pollStorageUsageRemaining(owner,"owner",policy)??0)>0 - && owner.attempts<=global.attempts && owner.bytes<=global.bytes && owner.rows<=global.rows - && owner.compactedAttempts<=global.compactedAttempts && owner.archiveBytes<=global.archiveBytes - && global.archiveBytes-owner.archiveBytes >= (global.compactedAttempts-owner.compactedAttempts)*40 - && global.archiveBytes-owner.archiveBytes <= (global.compactedAttempts-owner.compactedAttempts)*131072 - } catch { return false } -} - export interface PollStorageGcCandidate { scope: PollStorageScope lastActivityAt: number diff --git a/backend/src/services/server-poll-storage-restore.sql.test.ts b/backend/src/services/server-poll-storage-restore.sql.test.ts index c6665ca3..a4dd9029 100644 --- a/backend/src/services/server-poll-storage-restore.sql.test.ts +++ b/backend/src/services/server-poll-storage-restore.sql.test.ts @@ -15,10 +15,16 @@ try{ const actual=await pollStorageRestoreEvidence(pool) assert.deepEqual(actual,expected,"Every poll admission/token/ciphertext/stage/quarantine/counter must survive actual terminal restore byte-for-byte in canonical data form") const counts=(await pool.query("SELECT(SELECT count(*) FROM server_poll_storage_admissions)::int AS actual,admissions::int AS heavy,compacted_admissions::int AS compacted,(admissions+compacted_admissions)::int AS charged FROM server_poll_storage_usage WHERE scope='global'")).rows[0] - assert.equal(counts.actual,counts.charged);assert.equal(counts.heavy,128) + assert.equal(counts.actual,counts.charged);assert(counts.heavy>=130) assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage u WHERE u.scope<>'global' AND (u.admissions<>(SELECT count(*) FROM server_poll_storage_admissions a WHERE u.scope='owner:'||a.owner_id AND a.storage_state='full') OR u.compacted_admissions<>(SELECT count(*) FROM server_poll_storage_admissions a WHERE u.scope='owner:'||a.owner_id AND a.storage_state='compacted'))")).rows[0].n,0) const fresh={receiptId:randomUUID(),kind:"rest" as const,executionId:randomUUID(),ownerId:"owned-after-restore-"+randomUUID(),bindingProof:"a".repeat(64),contextProof:"b".repeat(64),issuedAt:Date.now()-1000,expiresAt:Date.now()+60000} - await assert.rejects(createServerPollStorage({scope:fresh,connectionId:null,maxStages:8,authorize:async()=>{}}).claim({deadlineAt:Date.now()+10000},async()=>assert.fail("Restored global quota must prevent any new anchor")),PollStorageRefused) - assert.deepEqual(await pollStorageRestoreEvidence(pool),expected,"Refused fresh admission must not alter restored counters or spend an extra token") - console.log("Owned poll storage AFTER terminal restore:",JSON.stringify({tablesCompared:Object.keys(POLL_STORAGE_TABLE_KEYS).length,exactClaimTokensAndCiphertextHashes:true,microsecondsPreserved:true,actualAdmissions:counts.actual,chargedAdmissions:counts.charged,heavyAdmissions:counts.heavy,compactedAdmissions:counts.compacted,allOwnerCountersReconciled:true,restoredGlobalQuotaStillEnforced:true,refusedAttemptChangesNoRows:true,newNativeDispatches:0,productionDatabaseTouched:false})) + const binding = {scope:fresh,connectionId:null,maxStages:8,authorize:async()=>{}} + await createServerPollStorage(binding).claim({deadlineAt:Date.now()+10000}, async sql => { + await sql.query("INSERT INTO server_poll_executions(receipt_id,identity_kind,execution_id,binding_proof,context_ciphertext,context_proof) VALUES($1,'rest',$2,$3,'SYNTHETIC',$4)", [fresh.receiptId,fresh.executionId,fresh.bindingProof,fresh.contextProof]) + }) + const afterAdmission = await pollStorageRestoreEvidence(pool) + assert.equal(afterAdmission.tables.server_poll_storage_admissions.rows, counts.actual + 1) + await assert.rejects(createServerPollStorage(binding).claim({deadlineAt:Date.now()+10000},async()=>assert.fail("Spent admission cannot create another anchor")),PollStorageRefused) + assert.deepEqual(await pollStorageRestoreEvidence(pool),afterAdmission,"Rejected replay cannot change restored counters") + console.log("Owned poll storage AFTER terminal restore:",JSON.stringify({tablesCompared:Object.keys(POLL_STORAGE_TABLE_KEYS).length,exactClaimTokensAndCiphertextHashes:true,microsecondsPreserved:true,actualAdmissions:counts.actual,chargedAdmissions:counts.charged,heavyAdmissions:counts.heavy,compactedAdmissions:counts.compacted,allOwnerCountersReconciled:true,freshAdmissionAfterRestore:true,refusedReplayChangesNoRows:true,newNativeDispatches:0,productionDatabaseTouched:false})) }finally{await closePool()} diff --git a/backend/src/services/server-poll-storage.sql.test.ts b/backend/src/services/server-poll-storage.sql.test.ts index 9403fab8..334c1cdf 100644 --- a/backend/src/services/server-poll-storage.sql.test.ts +++ b/backend/src/services/server-poll-storage.sql.test.ts @@ -106,10 +106,10 @@ try{ await assert.rejects(store.write(options(),sql=>sql.query("INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof) VALUES($1,'native.resource',$2,$2,$2)",[value.receiptId,proof])),PollStorageRefused) cases.push("two-phase claim, exact reservation, durable spent identity, normalized activity, plan stage cap and idempotent quarantine actual-row metering") - const owner="concurrent-"+randomUUID(),claims=await Promise.allSettled(Array.from({length:10},async()=>{const s=scope(owner);return createServerPollStorage(binding(s)).claim(options(),sql=>anchor(sql,s))})) - assert.equal(claims.filter(row=>row.status==="fulfilled").length,8) - assert.deepEqual(await usage(owner),{admissions:8,reserved_rows:8*4019,reserved_bytes:String(8*8421376)}) - cases.push("ten concurrent independent factories atomically admit eight owner attempts, refuse two, never partially charge counters") + const owner="concurrent-"+randomUUID(),claims=await Promise.allSettled(Array.from({length:20},async()=>{const s=scope(owner);return createServerPollStorage(binding(s)).claim(options(),sql=>anchor(sql,s))})) + assert.equal(claims.filter(row=>row.status==="fulfilled").length,20) + assert.deepEqual(await usage(owner),{admissions:20,reserved_rows:20*4019,reserved_bytes:String(20*8421376)}) + cases.push("twenty concurrent attempts for one owner retain exact charges") const uncertain=scope(),b=binding(uncertain);let loss=true,callbacks=0 const lost=createServerPollStorageForTests(b,{now:Date.now,async connect(opts){const c=await connectProbeStorage(opts);return {release:v=>c.release(v),async query(text,values,queryOptions){const result=await c.query(text,values,queryOptions);if(text==="COMMIT"&&loss){loss=false;throw Error("SYNTHETIC lost admission commit acknowledgement")};return result}}}}) @@ -181,41 +181,31 @@ try{ cases.push("actual existing worker tick collects an eligible original terminal poll admission and refunds quota while MCP is disabled") await (await import("./server-poll-storage-execution.sql-helper.js")).acceptServerPollStorageExecutionSql() cases.push("actual quota-bound full production poll: all four native GETs observe committed consumed admission, every maintenance publication/ACK metered, known replay no new native or quota") - const globalBefore=Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions) - const fill=await Promise.allSettled(Array.from({length:130-globalBefore},async()=>{const s=scope();return createServerPollStorage(binding(s)).claim({deadlineAt:Date.now()+60000},sql=>anchor(sql,s))})) - assert.equal(fill.filter(row=>row.status==="fulfilled").length,128-globalBefore) - assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions),128) - assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=0")).rows[0].n,0,"Refused owner reservations leave no zero counter rows") - cases.push("global 128-attempt cap holds across independent owners and concurrent actual commits; failed admissions leave no orphan counters") - { - const {readServerPollCapacity}=await import("./server-poll-capacity.js") - const fullOwner=(await pool.query("SELECT scope FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=8 LIMIT 1")).rows[0] - assert(fullOwner) - const ownerId=String(fullOwner.scope).slice("owner:".length) - const before=(await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows - const readOnly=await pool.connect() - try{ - await readOnly.query("BEGIN READ ONLY") - const capacity=await readServerPollCapacity(readOnly,ownerId,true) - assert.equal(capacity.status,"observed") - if(capacity.status!=="observed")assert.fail("Expected actual full retained capacity") - assert.deepEqual(capacity.owner,{used:8,limit:8,remaining:0}) - assert.deepEqual(capacity.global,{exhausted:true,usage:{used:128,limit:128,remaining:0}}) - const privateCapacity=await readServerPollCapacity(readOnly,ownerId,false) - assert.equal(privateCapacity.status,"observed") - if(privateCapacity.status!=="observed")assert.fail("Expected scoped private capacity") - assert.deepEqual(privateCapacity.global,{exhausted:true,usage:null}) - assert.equal(JSON.stringify(privateCapacity).includes(ownerId),false) - const emptyOwner=await readServerPollCapacity(readOnly,"unallocated-"+randomUUID(),false) - assert.equal(emptyOwner.status,"observed") - if(emptyOwner.status!=="observed")assert.fail("Expected unallocated owner capacity") - assert.deepEqual(emptyOwner.owner,{used:0,limit:8,remaining:8}) - assert.equal(emptyOwner.global.exhausted,true) - await readOnly.query("COMMIT") - }finally{readOnly.release()} - assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows,before) - cases.push("portal retained capacity uses real READ ONLY snapshot of owner8/global128, hides non-admin global numbers, never claims unallocated owner bypasses full global cap, and changes no quota row") + const globalBefore = Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions) + const ownerId = "scale-" + randomUUID() + for (let n = globalBefore; n < 130; n += 1) { + const attempt = scope(ownerId) + await createServerPollStorage(binding(attempt)).claim(options(), sql => anchor(sql, attempt)) } + const { readServerPollUsage } = await import("./server-poll-capacity.js") + const before = (await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows + const readOnly = await pool.connect() + try { + await readOnly.query("BEGIN READ ONLY") + const usage = await readServerPollUsage(readOnly, ownerId, true) + assert.equal(usage.status, "observed") + if (usage.status !== "observed") assert.fail("Expected observed journal usage") + assert.equal(usage.ownerFull, 130 - globalBefore) + assert.equal(usage.globalFull, 130) + const privateUsage = await readServerPollUsage(readOnly, ownerId, false) + assert.deepEqual(privateUsage, { ...usage, globalFull: null }) + assert.equal(JSON.stringify(privateUsage).includes(ownerId), false) + const emptyOwner = await readServerPollUsage(readOnly, "unallocated-" + randomUUID(), false) + assert.deepEqual(emptyOwner, { ...privateUsage, ownerFull: 0 }) + await readOnly.query("COMMIT") + } finally { readOnly.release() } + assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows, before) + cases.push("historical journals coexist with over 128 full admissions and read-only usage counts") const evidence=await(await import("./server-poll-storage-restore-evidence.sql-helper.js")).pollStorageRestoreEvidence(pool) await writeFile(resolve(process.env.MCP_STATE_DIR!,"poll-storage-owned-restore-evidence.json"),JSON.stringify(evidence),{flag:"wx",mode:0o600}) console.log("Owned poll storage SQL:",JSON.stringify({cases:cases.length,names:cases,historicalPrefix39:39,currentMigrations:MIGRATION_MANIFEST.length,actualMigrationFileStagedForOwnedHistoricalFixtures:true,allFileStatementsAndRealTerminalMarker:true,historicalRowsAndHashesPreserved:true,realPgTransactions:true,realQuotaTriggers:true,historicalFixtureBeforeGuards:true,providerOrClockOverrides:false,simulatedCommitAckLossAfterRealCommit:true,publicRoutesRegistered:false,journalAdapterIntegrated:true,productionDatabaseTouched:false,externalNetwork:false})) diff --git a/components/mcp/mcp-workspace.tsx b/components/mcp/mcp-workspace.tsx index 298bdc9c..79d9927d 100644 --- a/components/mcp/mcp-workspace.tsx +++ b/components/mcp/mcp-workspace.tsx @@ -16,7 +16,7 @@ import { PageHeader } from "@/components/page-header" import { DatabaseRestore } from "./database-restore" import { PlanReview } from "./plan-review" import { ArtifactDownloads } from "./artifact-downloads" -import { PollStorageCapacity } from "./poll-storage-capacity" +import { PollStorageUsage } from "./poll-storage-capacity" import { BridgeVlanWorkflow } from "./bridge-vlan-workflow" import { ObjectPermissionPreview, PolicyPreviewDecision } from "./object-permission-preview" import { Frame, FrameHeader, FrameTitle, FrameDescription, FramePanel } from "@/components/reui/frame" @@ -499,7 +499,7 @@ function RoutingProfiles({ api }: { api: McpApi }) { } function Overview({ api }: { api: McpApi }) { const query = useQuery(useCallback(signal => api.overview(signal), [api])) - return { if (window.confirm("Остановить новые обращения MCP и все профили Route AI? Начатые записи будут завершены или сверены.")) void api.stopAutomation().then(query.refresh, error => toast.error(errorText(error))) }}>Остановить автоматические изменения}>
{Object.entries({ connections: "Подключения", calls: "Вызовы за 24 часа", errors: "Ошибки и отказы", approvals: "Ожидают подтверждения", running: "Выполняются" }).map(([key, title]) =>

{title}

{query.data ? query.data[key as "calls"] : "—"}

)}
{query.data?.enabled ? "MCP включён" : "MCP выключен"}

Выключатель прекращает новые вызовы. Выключатель также останавливает новые решения Route AI. Отдельный профиль можно остановить на вкладке Route AI.

+ return { if (window.confirm("Остановить новые обращения MCP и все профили Route AI? Начатые записи будут завершены или сверены.")) void api.stopAutomation().then(query.refresh, error => toast.error(errorText(error))) }}>Остановить автоматические изменения}>
{Object.entries({ connections: "Подключения", calls: "Вызовы за 24 часа", errors: "Ошибки и отказы", approvals: "Ожидают подтверждения", running: "Выполняются" }).map(([key, title]) =>

{title}

{query.data ? query.data[key as "calls"] : "—"}

)}
{query.data?.enabled ? "MCP включён" : "MCP выключен"}

Выключатель прекращает новые вызовы. Выключатель также останавливает новые решения Route AI. Отдельный профиль можно остановить на вкладке Route AI.

} const recordQueryFilters = { requests: ["tool", "status", "connectionId", "serverId", "userId", "from", "to"], diff --git a/components/mcp/poll-storage-capacity.tsx b/components/mcp/poll-storage-capacity.tsx index 69ff011d..a3d23204 100644 --- a/components/mcp/poll-storage-capacity.tsx +++ b/components/mcp/poll-storage-capacity.tsx @@ -1,25 +1,20 @@ -import type {McpPollStorageCapacity} from "@mmapp/contracts/mcp" -import {Badge} from "@/components/reui/badge" -import {Button} from "@/components/ui/button" +import type { McpPollStorageUsage } from "@mmapp/contracts/mcp" +import { Button } from "@/components/ui/button" -export function PollStorageCapacity({capacity,loading,refresh}:{capacity?:McpPollStorageCapacity;loading:boolean;refresh:()=>void}){ - const observed=capacity?.status==="observed"?capacity:undefined - const ownerFull=observed?.owner.remaining===0,globalFull=observed?.global.exhausted===true - const full=ownerFull||globalFull +export function PollStorageUsage({ usage, loading, refresh }: { + usage?: McpPollStorageUsage; loading: boolean; refresh: () => void +}) { return

Журнал полных опросов

-
{loading?"Загрузка":!observed?"Нет данных":full?"Квота заполнена":"Квота не заполнена"}
+
- {observed?<> + {usage?.status === "observed" ? <>
-
Ваши полные журналы
{observed.owner.used} / {observed.owner.limit}Осталось: {observed.owner.remaining}
-
Полные журналы приложения
{observed.global.usage?<>{observed.global.usage.used} / {observed.global.usage.limit}Осталось: {observed.global.usage.remaining}:globalFull?"Заполнена":"Не заполнена"}
+
Ваши полные журналы
{usage.ownerFull}
+ {usage.globalFull !== null &&
Полные журналы приложения
{usage.globalFull}
}
- {full&&

{ownerFull&&globalFull?"Личная и общая квоты журнала заполнены.":ownerFull?"Личная квота журнала заполнена.":"Общая квота журнала заполнена."} Новый полный опрос не получит место. После безопасного архивирования или очистки по сроку хранения место может освободиться. Неизвестный результат сохраняет резерв; повторные попытки его не освобождают.

} -

Счётчик учитывает резерв под выполнение и журналы, ожидающие архивирования. Архив сохраняет все исходные записи и продолжает занимать место. Поэтому остаток зависит и от объёма сохранённой истории.

-

Срок хранения новых записей: {observed.retentionDays} дн. Существующие записи могут храниться дольше. Архивирование сохраняет исходный срок; очистка учитывает завершение операции, истечение допуска и защитный интервал.

-

Состояние показано на момент обновления. Окончательный допуск проверяется при запуске.

- :

{loading?"Проверяем заполнение журнала…":"Заполнение журнала сейчас недоступно. Свободное место не подтверждено; обновите статус позже."}

} +

Срок хранения новых записей: {usage.retentionDays} дн.

+ :

{loading ? "Загружаем данные журнала…" : "Данные журнала сейчас недоступны."}

}
} diff --git a/packages/contracts/src/mcp.ts b/packages/contracts/src/mcp.ts index 4e6f9cf1..7a7b6fdf 100644 --- a/packages/contracts/src/mcp.ts +++ b/packages/contracts/src/mcp.ts @@ -176,15 +176,9 @@ export const mcpPageQuerySchema = z.object({ export type McpConnection = z.infer export type McpConnectionCreate = z.infer -const pollOwnerCapacitySchema=z.object({used:z.number().int().min(0).max(8),limit:z.literal(8),remaining:z.number().int().min(0).max(8)}).strict().refine(value=>value.used+value.remaining<=value.limit) -const pollGlobalCapacitySchema=z.object({used:z.number().int().min(0).max(128),limit:z.literal(128),remaining:z.number().int().min(0).max(128)}).strict().refine(value=>value.used+value.remaining<=value.limit) -/** Heavy reservations. Retained archive bytes/rows can further reduce the - * remaining capacity; this observation never grants an execution admission. */ -export const mcpPollStorageCapacitySchema=z.discriminatedUnion("status",[ +export const mcpPollStorageUsageSchema=z.discriminatedUnion("status",[ z.object({status:z.literal("unavailable")}).strict(), - z.object({status:z.literal("observed"),owner:pollOwnerCapacitySchema, - global:z.object({exhausted:z.boolean(),usage:pollGlobalCapacitySchema.nullable()}).strict() - .refine(value=>value.usage===null||value.exhausted===(value.usage.remaining===0)), - retentionDays:z.number().int().min(1).max(365)}).strict(), + z.object({status:z.literal("observed"), ownerFull:z.number().int().nonnegative().safe(), + globalFull:z.number().int().nonnegative().safe().nullable(), retentionDays:z.number().int().min(1).max(365)}).strict(), ]) -export type McpPollStorageCapacity=z.infer +export type McpPollStorageUsage=z.infer diff --git a/shared/api/mcp-capacity.test.ts b/shared/api/mcp-capacity.test.ts index cda67d4a..2189bc25 100644 --- a/shared/api/mcp-capacity.test.ts +++ b/shared/api/mcp-capacity.test.ts @@ -1,17 +1,18 @@ import assert from "node:assert/strict" -import {test} from "node:test" -import {mcpPollStorageCapacitySchema} from "@mmapp/contracts/mcp" -import {mcpOverviewSchema} from "./mcp" +import { test } from "node:test" +import { mcpPollStorageUsageSchema } from "@mmapp/contracts/mcp" +import { mcpOverviewSchema } from "./mcp" -const capacity={status:"observed",owner:{used:8,limit:8,remaining:0},global:{exhausted:true,usage:{used:128,limit:128,remaining:0}},retentionDays:14} -test("poll retained capacity validates full counters and hides non-admin global usage",()=>{ - assert.deepEqual(mcpPollStorageCapacitySchema.parse(capacity),capacity) - const privateView={...capacity,global:{exhausted:true,usage:null}} - assert.deepEqual(mcpPollStorageCapacitySchema.parse(privateView),privateView) - for(const bad of [{...capacity,owner:{used:8,limit:8,remaining:1}},{...capacity,global:{exhausted:false,usage:capacity.global.usage}},{...capacity,retentionDays:0},{...capacity,owner:{used:9,limit:8,remaining:0}},{status:"unavailable",owner:{used:0,limit:8,remaining:8}}])assert.equal(mcpPollStorageCapacitySchema.safeParse(bad).success,false) +const usage = { status: "observed", ownerFull: 20, globalFull: 130, retentionDays: 30 } +test("poll journal usage is accepted above the former quotas and hides non-admin global counts", () => { + assert.deepEqual(mcpPollStorageUsageSchema.parse(usage), usage) + const privateView = { ...usage, globalFull: null } + assert.deepEqual(mcpPollStorageUsageSchema.parse(privateView), privateView) + for (const bad of [{ ...usage, ownerFull: -1 }, { ...usage, globalFull: 1.5 }, { ...usage, retentionDays: 0 }, { ...usage, remaining: 0 }]) + assert.equal(mcpPollStorageUsageSchema.safeParse(bad).success, false) }) -test("old overview responses report capacity unavailable instead of inventing free slots",()=>{ - const original={connections:1,calls:2,errors:0,approvals:0,running:0,enabled:true,observedAt:new Date().toISOString()} - assert.deepEqual(mcpOverviewSchema.parse(original).pollStorageCapacity,{status:"unavailable"}) - assert.deepEqual(mcpOverviewSchema.parse({...original,pollStorageCapacity:capacity}).pollStorageCapacity,capacity) +test("overview with an older backend reports usage unavailable without blocking other fields", () => { + const original = { connections: 1, calls: 2, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: new Date().toISOString() } + assert.deepEqual(mcpOverviewSchema.parse({ ...original, pollStorageCapacity: { status: "observed" } }).pollStorageUsage, { status: "unavailable" }) + assert.deepEqual(mcpOverviewSchema.parse({ ...original, pollStorageUsage: usage }).pollStorageUsage, usage) }) diff --git a/shared/api/mcp.ts b/shared/api/mcp.ts index e91ae347..26bd9669 100644 --- a/shared/api/mcp.ts +++ b/shared/api/mcp.ts @@ -1,11 +1,11 @@ import { z } from "zod" import { bridgeVlanStateSchema, type BridgeVlanDesired } from "@mmapp/contracts/bridge-vlan" -import { mcpCatalogResponseSchema, mcpConnectionsSchema, mcpSettingsSchema, mcpPolicyPreviewResponseSchema, mcpPollStorageCapacitySchema, type McpConnectionCreate } from "@mmapp/contracts/mcp" +import { mcpCatalogResponseSchema, mcpConnectionsSchema, mcpSettingsSchema, mcpPolicyPreviewResponseSchema, mcpPollStorageUsageSchema, type McpConnectionCreate } from "@mmapp/contracts/mcp" import { requestJson } from "./http-client" import { downloadHumanArtifact } from "./mcp-artifact" export const mcpRecordsSchema = z.object({ items: z.array(z.record(z.string(), z.unknown())), total: z.number().int(), nextCursor: z.string().nullable() }) -export const mcpOverviewSchema = z.object({ connections: z.number(), calls: z.number(), errors: z.number(), approvals: z.number(), running: z.number(), enabled: z.boolean(), observedAt: z.string(), pollStorageCapacity:mcpPollStorageCapacitySchema.default({status:"unavailable"}) }) +export const mcpOverviewSchema = z.object({ connections: z.number(), calls: z.number(), errors: z.number(), approvals: z.number(), running: z.number(), enabled: z.boolean(), observedAt: z.string(), pollStorageUsage:mcpPollStorageUsageSchema.default({status:"unavailable"}) }) export const maxMcpRestoreArchiveBytes = 64 * 1024 * 1024 const restoreArchiveSchema = z.object({ archiveRef: z.string().uuid(), sha256: z.string().regex(/^[a-f0-9]{64}$/), sizeBytes: z.number().int().positive().max(maxMcpRestoreArchiveBytes), expiresAt: z.string().datetime() }) const deviceCatalogSchema = z.object({ servers: z.array(z.object({ id: z.number(), name: z.string(), host: z.string(), enabled: z.boolean() })), resources: z.array(z.object({ id: z.string(), title: z.string(), read: z.boolean(), create: z.boolean(), update: z.boolean(), delete: z.boolean(), fields: z.array(z.object({ key: z.string(), type: z.enum(["string", "number", "boolean"]), options: z.array(z.string()).optional(), min: z.number().optional(), max: z.number().optional(), maxLength: z.number().optional(), requiredOnCreate: z.boolean() })) })) }) diff --git a/tests/e2e/mcp-context.spec.ts b/tests/e2e/mcp-context.spec.ts index c45a26ae..89b42c14 100644 --- a/tests/e2e/mcp-context.spec.ts +++ b/tests/e2e/mcp-context.spec.ts @@ -190,41 +190,39 @@ test("MCP: зависшее чтение показывает ошибку и п } }) -test("MCP журнал: заполненная квота объясняет удержание и показывает admin counters",async({page})=>{ +test("MCP журнал: число записей без старых потолков на узком экране", async ({ page }) => { await setup(page) - await page.route("**/api/mcp/overview",route=>route.fulfill({json:{connections:1,calls:7,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:8,limit:8,remaining:0},global:{exhausted:true,usage:{used:128,limit:128,remaining:0}},retentionDays:14}}})) + await page.setViewportSize({ width: 390, height: 844 }) + await page.route("**/api/mcp/overview", route => route.fulfill({ json: { + connections: 1, calls: 7, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: at, + pollStorageUsage: { status: "observed", ownerFull: 20, globalFull: 130, retentionDays: 30 }, + } })) await page.goto("/mcp") - const capacity=page.getByRole("region",{name:"Журнал полных опросов"}) - await expect(capacity.getByText("8 / 8",{exact:false})).toBeVisible() - await expect(capacity.getByText("128 / 128",{exact:false})).toBeVisible() - await expect(capacity.getByRole("alert")).toContainText("Личная и общая квоты журнала заполнены") - await expect(capacity).toContainText("Счётчик учитывает резерв под выполнение и журналы, ожидающие архивирования") - await expect(capacity).toContainText("Архив сохраняет все исходные записи и продолжает занимать место") - await expect(capacity).toContainText("14 дн.") - await capacity.screenshot({path:"test-results/mcp-poll-capacity-full.png"}) + const journal = page.getByRole("region", { name: "Журнал полных опросов" }) + await expect(journal.getByText("Ваши полные журналы")).toBeVisible() + await expect(journal.getByText("20", { exact: true })).toBeVisible() + await expect(journal.getByText("130", { exact: true })).toBeVisible() + await expect(journal).toContainText("30 дн.") + await expect(journal).not.toContainText(/Осталось|квота|\/\s*(8|128)\b/i) + expect(await journal.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) }) -test("MCP журнал: non-admin global usage скрыт, ошибка обновления не сохраняет зелёный статус",async({page})=>{ + +test("MCP журнал: личные данные отдельно, ошибка обновления показывает недоступность", async ({ page }) => { await setup(page) - let failed=false - await page.route("**/api/mcp/overview",route=>route.fulfill(failed?{status:503,json:{error:"Аудит временно недоступен"}}:{json:{connections:1,calls:0,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:1,limit:8,remaining:7},global:{exhausted:false,usage:null},retentionDays:14}}})) + let failed = false + await page.route("**/api/mcp/overview", route => route.fulfill(failed ? { status: 503, json: { error: "Аудит временно недоступен" } } : { json: { + connections: 1, calls: 0, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: at, + pollStorageUsage: { status: "observed", ownerFull: 8, globalFull: null, retentionDays: 30 }, + } })) await page.goto("/mcp") - const capacity=page.getByRole("region",{name:"Журнал полных опросов"}) - await expect(capacity).toContainText("Квота не заполнена") - await expect(capacity).not.toContainText("128") - failed=true;await capacity.getByRole("button",{name:"Обновить статус"}).click() - await expect(capacity.getByRole("status")).toContainText("Свободное место не подтверждено") - await expect(capacity).not.toContainText("Квота не заполнена") -}) -test("MCP журнал: на мобильном общая квота блокирует запуск при свободной личной",async({page})=>{ - await setup(page);await page.setViewportSize({width:390,height:844}) - await page.route("**/api/mcp/overview",route=>route.fulfill({json:{connections:1,calls:0,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:1,limit:8,remaining:7},global:{exhausted:true,usage:null},retentionDays:14}}})) - await page.goto("/mcp") - const capacity=page.getByRole("region",{name:"Журнал полных опросов"}) - await expect(capacity.getByRole("alert")).toContainText("Общая квота журнала заполнена") - await expect(capacity).toContainText("Осталось: 7") - expect(await capacity.evaluate(element=>element.scrollWidth<=element.clientWidth)).toBe(true) - await capacity.screenshot({path:"test-results/mcp-poll-capacity-mobile.png"}) + const journal = page.getByRole("region", { name: "Журнал полных опросов" }) + await expect(journal.getByText("8", { exact: true })).toBeVisible() + await expect(journal).not.toContainText("Полные журналы приложения") + failed = true + await journal.getByRole("button", { name: "Обновить статус" }).click() + await expect(journal.getByRole("status")).toContainText("Данные журнала сейчас недоступны") }) + const routePathCheckConfig = { name: "Проверка назначения", serverId: 1, community: "65000:10", family: "ipv4", table: "main", probeVrf: "main", candidates: [{ id: "probe", wanInterface: "wan", downstreamInterface: "down", jumpHostId: 2, exitNodeId: 3, gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r" }, controlProbe: { targetInterface: "exit", expectedHops: [{ serverId: 3, interface: "exit" }] } }],