Skip to content

API Reference parrot.knowledge.contracts.catalog_postgres

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.knowledge.contracts.catalog_postgres

View source

Postgres implementation of the contract catalog (FEAT-539 M2).

The single production :class:~parrot.knowledge.contracts.catalog. ContractCatalogStore backend. Postgres is authoritative for cards, obligations, verification, versions, aliases, judgements, answer audit and source cursors.

Tenancy is a separate configured schema per tenant: the schema name is configuration, validated as a plain SQL identifier before it can reach a statement, and every user- or model-supplied value is a bound parameter.

asyncpg is imported lazily so that importing the contracts package does not require the graphindex-postgres extra to be installed.

Attribute CONTRACTS_DDL

Type: tuple[str, ...]

Attribute LOW_CONFIDENCE_THRESHOLD

Attribute MAX_QUEUE_LIMIT

Attribute MAX_SEARCH_TOP_K

Class PostgresContractCatalog

Async Postgres catalog bound to one tenant schema.

Parameter Type Default Description
dsn Optional[str] None Explicit asyncpg DSN. Required unless pool is supplied — this feature deliberately does not fall back to a default DSN.
pool Optional['asyncpg.Pool'] None An externally owned pool to reuse. It is never closed by :meth:close.
tenant_id str Tenant this catalog is bound to.
schema str 'contracts' Per-tenant SQL schema; validated as a plain identifier.
principal Optional[str] None Service principal recorded for unattended writes.
now Callable[[], datetime] _utcnow Clock used for recorded timestamps.

Method PostgresContractCatalog.setup

Create this tenant's schema and tables idempotently.

setup() -> None

Method PostgresContractCatalog.close

Close the pool only when this instance created it.

close() -> None

Method PostgresContractCatalog.publication_guard

Avoid pool starvation even when different tenants share a small pool.

publication_guard(*, target: PublicationTarget) -> AsyncIterator[bool]

Parameter Type Default Description
target PublicationTarget

Returns: AsyncIterator[bool]

Method PostgresContractCatalog.upsert

Write card, obligations, history and outbox rows in one transaction.

upsert(card: ContractCard, *, expected_revision: Optional[int] = None, version: Optional[ContractVersion] = None, targets: tuple[PublicationTarget, ...] = ('ontology', 'temporal')) -> UpsertResult

Parameter Type Default Description
card ContractCard
expected_revision Optional[int] None
version Optional[ContractVersion] None
targets tuple[PublicationTarget, ...] ('ontology', 'temporal')

Returns: UpsertResult

Method PostgresContractCatalog.remove

Record a new retraction revision, retaining all historical evidence.

remove(contract_id: str) -> None

Parameter Type Default Description
contract_id str

Method PostgresContractCatalog.get

Return one card by id.

get(contract_id: str) -> Optional[ContractCard]

Parameter Type Default Description
contract_id str

Returns: Optional[ContractCard]

Method PostgresContractCatalog.find_by_sha

Return the card whose current source hashes to sha256.

find_by_sha(sha256: str) -> Optional[ContractCard]

Parameter Type Default Description
sha256 str

Returns: Optional[ContractCard]

Method PostgresContractCatalog.find_by_source_uri

Return the card whose canonical source URI is uri.

find_by_source_uri(uri: str) -> Optional[ContractCard]

Parameter Type Default Description
uri str

Returns: Optional[ContractCard]

Method PostgresContractCatalog.taken_slugs

Return every slug already used (SQL uniqueness is the real guard).

taken_slugs() -> set[str]

Returns: set[str]

Method PostgresContractCatalog.obligations_for

Return one contract's obligation set in stable id order.

obligations_for(contract_id: str) -> list[Obligation]

Parameter Type Default Description
contract_id str

Returns: list[Obligation]

Method PostgresContractCatalog.versions

Return the retained version/revision history, oldest first.

versions(contract_id: str) -> list[ContractVersion]

Parameter Type Default Description
contract_id str

Returns: list[ContractVersion]

Method PostgresContractCatalog.enqueue_publication

Queue one publication row idempotently on its durable key.

enqueue_publication(record: PublicationRecord) -> PublicationRecord

Parameter Type Default Description
record PublicationRecord

Returns: PublicationRecord

Method PostgresContractCatalog.list_cards

List cards filtered by status and verification state.

list_cards(*, status: Optional[ContractStatus] = None, verification: Optional[VerificationState] = None, active_only: bool = True) -> list[ContractCard]

Parameter Type Default Description
status Optional[ContractStatus] None Restrict to one contract status.
verification Optional[VerificationState] None Restrict to one verification state.
active_only bool True Exclude retracted cards.

Returns: list[ContractCard] — Cards ordered deterministically by contract_id.

Method PostgresContractCatalog.search

Rank cards with English plainto_tsquery / ts_rank.

The query is always a bound parameter — injection payloads are tokenised as ordinary search terms, never executed.

search(query: str, top_k: int = 8) -> list[SearchHit]

Parameter Type Default Description
query str Free-form user query; blank queries match nothing.
top_k int 8 Bounded number of hits (1..MAX_SEARCH_TOP_K).

Returns: list[SearchHit] — Hits ordered by descending rank, then contract_id.

Method PostgresContractCatalog.expiring

Return active cards inside an inclusive date window.

notice_deadline falls back to expiration_date for cards without a notice period; cards whose driving date is null are omitted entirely.

expiring(*, until: date, key: ExpiringKey = 'notice_deadline', since: Optional[date] = None) -> list[ContractCard]

Parameter Type Default Description
until date Inclusive end of the window.
key ExpiringKey 'notice_deadline' Which date drives the window.
since Optional[date] None Inclusive start, or None for everything up to until.

Returns: list[ContractCard]

Raises:

  • ValueError — When key is not a supported window key, or the window is inverted.

Method PostgresContractCatalog.verification_queue

Return unverified cards in deterministic priority order.

Missing evidence first, then unresolved low-confidence fields, then remaining stale cards; contract_id breaks every tie.

verification_queue(*, limit: int = 50) -> list[VerificationQueueEntry]

Parameter Type Default Description
limit int 50

Returns: list[VerificationQueueEntry]

Method PostgresContractCatalog.obligations_due

Return obligations inside a typed due-date window.

Fixed due dates are selected by an inclusive window. Recurrence is returned for review when include_recurring is set; it is never interpreted here.

obligations_due(window: ObligationWindow) -> list[Obligation]

Parameter Type Default Description
window ObligationWindow

Returns: list[Obligation]

Method PostgresContractCatalog.merge_parties

Merge two party identities inside one transaction.

Current cards, signatories, alias mappings and queued projections move together; historical snapshots keep the name they were signed under.

merge_parties(keep_party_id: str, merge_party_id: str, *, user: str) -> PartyMergeResult

Parameter Type Default Description
keep_party_id str
merge_party_id str
user str

Returns: PartyMergeResult

Raises:

  • ValueError — On an invalid self-merge.
  • UnknownPartyError — When either identity is unknown.

Method PostgresContractCatalog.party_aliases

Return every alias mapped onto one canonical party.

party_aliases(party_id: str) -> list[PartyAlias]

Parameter Type Default Description
party_id str

Returns: list[PartyAlias]

Method PostgresContractCatalog.all_party_aliases

Return catalog-wide aliases keyed by canonical party_id.

all_party_aliases() -> dict[str, list[str]]

Returns: dict[str, list[str]]

Method PostgresContractCatalog.add_party_alias

Map a normalized alias onto a canonical party.

add_party_alias(alias: str, party_id: str, *, user: str) -> PartyAlias

Parameter Type Default Description
alias str
party_id str
user str

Returns: PartyAlias

Raises:

  • AliasConflictError — When the alias already maps elsewhere; the conflict is surfaced for review instead of being silently remapped.

Method PostgresContractCatalog.resolve_party

Resolve a normalized alias to its canonical party_id.

resolve_party(alias: str) -> Optional[str]

Parameter Type Default Description
alias str

Returns: Optional[str]

Method PostgresContractCatalog.list_parties

Return every distinct party across active cards, id-ordered.

list_parties() -> list[Party]

Returns: list[Party]

Method PostgresContractCatalog.record_answer

Persist an audited answer before it is released.

record_answer(record: AnswerRecord) -> None

Parameter Type Default Description
record AnswerRecord

Method PostgresContractCatalog.get_answer

Return one audited answer, or None when unknown.

get_answer(answer_id: str) -> Optional[AnswerRecord]

Parameter Type Default Description
answer_id str

Returns: Optional[AnswerRecord]

Method PostgresContractCatalog.retire_answer

Retire an answer; its cited nodes are suppressed from then on.

retire_answer(answer_id: str, *, user: str, reason: str) -> AnswerRecord

Parameter Type Default Description
answer_id str
user str
reason str

Returns: AnswerRecord

Method PostgresContractCatalog.retired_citations

Return every suppressed (contract_id, node_id) pair.

Suppression is deliberately broad and version-independent: a refresh cannot evade it by renumbering an unchanged excerpt.

retired_citations() -> set[tuple[str, str]]

Returns: set[tuple[str, str]]

Method PostgresContractCatalog.get_delta_token

Return the committed opaque delta cursor for a source.

get_delta_token(source_uri: str) -> Optional[str]

Parameter Type Default Description
source_uri str

Returns: Optional[str]

Method PostgresContractCatalog.set_delta_token

Commit a delta cursor after the batch is durable.

set_delta_token(source_uri: str, token: str) -> None

Parameter Type Default Description
source_uri str
token str

Method PostgresContractCatalog.upsert_source_item

Record stable remote-item identity for renames and tombstones.

upsert_source_item(item: SourceItem) -> None

Parameter Type Default Description
item SourceItem

Method PostgresContractCatalog.get_source_item

Return one recorded source item by its stable identity.

get_source_item(drive_id: str, item_id: str) -> Optional[SourceItem]

Parameter Type Default Description
drive_id str
item_id str

Returns: Optional[SourceItem]

Method PostgresContractCatalog.list_source_items

Return recorded source items, for one source or for all of them.

list_source_items(source: Optional[str] = None) -> list[SourceItem]

Parameter Type Default Description
source Optional[str] None

Returns: list[SourceItem]

Method PostgresContractCatalog.record_judgement

Append a judgement row, including none outcomes.

record_judgement(judgement: RelationJudgement) -> None

Parameter Type Default Description
judgement RelationJudgement

Method PostgresContractCatalog.judgements_for

Return judgement history touching one contract, newest last.

judgements_for(contract_id: str) -> list[RelationJudgement]

Parameter Type Default Description
contract_id str

Returns: list[RelationJudgement]

Method PostgresContractCatalog.replace_relations

Replace the active relations owned by one source contract.

replace_relations(contract_id: str, relations: list[ContractRelation]) -> None

Parameter Type Default Description
contract_id str
relations list[ContractRelation]

Method PostgresContractCatalog.active_relations

Return active judged relations, optionally for one contract.

active_relations(contract_id: Optional[str] = None) -> list[ContractRelation]

Parameter Type Default Description
contract_id Optional[str] None

Returns: list[ContractRelation]

Method PostgresContractCatalog.invalidate_relations

Deactivate judgements and relations made against an old hash.

invalidate_relations(contract_id: str, *, source_sha256: str) -> int

Parameter Type Default Description
contract_id str
source_sha256 str

Returns: int

Method PostgresContractCatalog.pending_publications

Return queued/failed publication work, oldest first.

pending_publications(*, target: Optional[PublicationTarget] = None, limit: int = 50) -> list[PublicationRecord]

Parameter Type Default Description
target Optional[PublicationTarget] None
limit int 50

Returns: list[PublicationRecord]

Method PostgresContractCatalog.claim_publication

Claim publication work, marking it in flight and counting attempts.

Uses FOR UPDATE SKIP LOCKED so publication stays serialized per row: a crashed run's claim is recovered on the next pass instead of emitting a duplicate logical version.

claim_publication(*, target: PublicationTarget, limit: int = 1) -> list[PublicationRecord]

Parameter Type Default Description
target PublicationTarget
limit int 1

Returns: list[PublicationRecord]

Method PostgresContractCatalog.complete_publication

Record a verified receipt and mark the row published.

complete_publication(record: PublicationRecord, *, receipt: str) -> PublicationRecord

Parameter Type Default Description
record PublicationRecord
receipt str

Returns: PublicationRecord

Method PostgresContractCatalog.fail_publication

Record a retryable failure without losing the queued payload.

fail_publication(record: PublicationRecord, *, error: str) -> PublicationRecord

Parameter Type Default Description
record PublicationRecord
error str

Returns: PublicationRecord

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally