Skip to content

crp.headers

Auto-generated reference for the crp.headers subpackage.

headers

crp.headers

CRP protocol header surface (CRP-SPEC-002).

The HTTP-header layer that turns the CRP engine's internal analysis into the wire protocol: canonical header-name constants, response emission, inbound request parsing, Axiom-4 stripping, and response middleware.

CacheDirectives dataclass

Parsed CRP-Context-Cache directive set (SPEC-002 §4.10).

ConditionalResult dataclass

Outcome of a conditional-dispatch evaluation.

not_modified property

Return whether the not modified condition holds.

failed_dependency property

Return whether the failed dependency condition holds.

headers property

Return the headers.

HaltReason

Bases: str, Enum

Canonical crp_halt_reason values (SPEC-002 §13.2).

HaltResponse dataclass

A fully-formed HTTP 451 safety halt (body + headers).

CRPHeaderMiddleware

Placeholder raised if used without Starlette installed.

RequestDirectives dataclass

Structured view of inbound CRP request preferences.

has_policy property

Return whether this object has policy.

emit_headers(*, provenance=None, quality=None, compliance=None, session_id=None, window=None, strategy=None, protocol_version=None, etag=None, cache_status=None, window_hmac=None, chain_integrity=None, report_uri=None, audit_trail_id=None, audit_trail_uri=None, data_residency=None, safety_budget=None, oversight_mode=None, rqa=None, policy_applied=None, mode=None, mode_transition=None, coverage=None, continuation_id=None, dag_root=None, window_lineage=None, set_session=None, activation_status=None, activation_features=None, onboarding=None, extra=None)

compute_etag(facts)

Compute the CKF fact-set ETag (SPEC-002 §4.8).

The ETag is "sha256:" + SHA-256(sorted "fact_id:content_hash" lines). Sorting makes the hash order-independent, so two gateways with the same fact-set produce the same ETag regardless of insertion order.

Parameters:

Name Type Description Default
facts Iterable[tuple[str, str]]

iterable of (fact_id, content_hash) pairs.

required

Returns:

Type Description
str

"sha256:<hex>" - or the canonical empty-set ETag when facts is

str

empty.

evaluate_conditional(*, if_match, current_etag, cache=None, ckf_has_relevant_facts=True)

Decide the conditional-dispatch outcome for one call (SPEC-002 §4.9-4.11).

Parameters:

Name Type Description Default
if_match str | None

client's CRP-Context-If-Match (an ETag or "*"), or None.

required
current_etag str

the gateway's freshly computed CKF ETag.

required
cache CacheDirectives | Sequence[str] | None

parsed :class:CacheDirectives or a raw token list.

None
ckf_has_relevant_facts bool

whether the CKF holds facts relevant to the query.

True

Returns:

Type Description
ConditionalResult

class:ConditionalResult.

parse_cache_directives(directives)

Parse a list of raw cache-directive tokens into :class:CacheDirectives.

build_halt_response(*, reason, session_id, audit_trail_uri, oversight_required=False, retry_condition=None, hallucination_risk=None, retry_after=None)

Build the HTTP 451 safety-halt response (SPEC-002 §13.2).

Parameters:

Name Type Description Default
reason HaltReason | str

a :class:HaltReason (or its string value).

required
session_id str

the halted session id.

required
audit_trail_uri str

dereferenceable URI to the audit trail for this halt.

required
oversight_required bool

whether human oversight must approve a retry.

False
retry_condition str | None

"oversight-required" or an ISO-8601 timestamp. If omitted it defaults to "oversight-required" when oversight_required is set, else None.

None
hallucination_risk str | None

optional risk tier for the CRP-Safety-Hallucination-Risk header (e.g. "CRITICAL").

None
retry_after int | str | None

optional CRP-Safety-Retry-After value (seconds or token).

None

Returns:

Type Description
HaltResponse

class:HaltResponse with http_status=451.

inject_into_raw(raw_headers, crp_headers)

Append crp_headers to an ASGI raw-header list (no framework needed).

merge_headers(response_headers, crp_headers)

Merge crp_headers into a plain header dict (CRP values win).

assert_no_crp_headers(headers)

Raise AssertionError if any name in headers is a CRP header.

Intended for conformance tests (TV-002) that verify Axiom-4 compliance on the outbound provider request.

parse_request_headers(headers)

Parse a mapping of inbound HTTP headers into :class:RequestDirectives.

strip_crp_headers(headers)

Return headers with every CRP-* header removed.

Axiom 4 (CRP-SPEC-001/015): no CRP governance header may reach the LLM provider. This filter is prefix-based so it is robust to future header additions - anything starting with CRP- is dropped.

strip_inbound_forbidden_headers(headers)

Strip client-spoofed response-namespace headers from an inbound request.

SPEC-002 §14.1: CRP-Safety-*/CRP-Provenance-*/CRP-Compliance-*/ CRP-Quality-* are gateway-authoritative response headers. A client MUST NOT set them; the gateway MUST strip any it receives.

Returns (cleaned_headers, stripped_names).

headers.conditional

crp.headers.conditional

Conditional dispatch - ETag computation + HTTP 304/424 evaluation (SPEC-002 §4.8-4.11).

This is the library-side decision logic for conditional context dispatch. A gateway computes the current CKF fact-set :func:compute_etag, compares it to the client's CRP-Context-If-Match value, evaluates CRP-Context-Cache directives, and uses :func:evaluate_conditional to decide whether to:

  • serve a fresh envelope (HTTP 200, Cache-Status: MISS),
  • skip reconstruction and return HTTP 304 (Cache-Status: HIT), or
  • refuse with HTTP 424 when only-if-ckf is set but the CKF has no facts.

The actual HTTP response object is the gateway's concern; this module returns a structured :class:ConditionalResult so any transport can act on it.

CacheDirectives dataclass

Parsed CRP-Context-Cache directive set (SPEC-002 §4.10).

ConditionalResult dataclass

Outcome of a conditional-dispatch evaluation.

not_modified property

Return whether the not modified condition holds.

failed_dependency property

Return whether the failed dependency condition holds.

headers property

Return the headers.

compute_etag(facts)

Compute the CKF fact-set ETag (SPEC-002 §4.8).

The ETag is "sha256:" + SHA-256(sorted "fact_id:content_hash" lines). Sorting makes the hash order-independent, so two gateways with the same fact-set produce the same ETag regardless of insertion order.

Parameters:

Name Type Description Default
facts Iterable[tuple[str, str]]

iterable of (fact_id, content_hash) pairs.

required

Returns:

Type Description
str

"sha256:<hex>" - or the canonical empty-set ETag when facts is

str

empty.

parse_cache_directives(directives)

Parse a list of raw cache-directive tokens into :class:CacheDirectives.

evaluate_conditional(*, if_match, current_etag, cache=None, ckf_has_relevant_facts=True)

Decide the conditional-dispatch outcome for one call (SPEC-002 §4.9-4.11).

Parameters:

Name Type Description Default
if_match str | None

client's CRP-Context-If-Match (an ETag or "*"), or None.

required
current_etag str

the gateway's freshly computed CKF ETag.

required
cache CacheDirectives | Sequence[str] | None

parsed :class:CacheDirectives or a raw token list.

None
ckf_has_relevant_facts bool

whether the CKF holds facts relevant to the query.

True

Returns:

Type Description
ConditionalResult

class:ConditionalResult.

headers.emit

crp.headers.emit

Header emission (CRP-SPEC-002).

:func:emit_headers maps the engine's existing analysis outputs - the DPE ProvenanceReport, the QualityReport, the compliance RiskAssessment, session/window state - onto the canonical CRP-* response header surface.

The emitter is intentionally duck-typed and defensive: every input is optional and accessed via :func:getattr, so it never hard-couples to a specific engine version and never raises on a missing field. Callers wire in whatever they have; the emitter emits whatever it can.

emit_headers(*, provenance=None, quality=None, compliance=None, session_id=None, window=None, strategy=None, protocol_version=None, etag=None, cache_status=None, window_hmac=None, chain_integrity=None, report_uri=None, audit_trail_id=None, audit_trail_uri=None, data_residency=None, safety_budget=None, oversight_mode=None, rqa=None, policy_applied=None, mode=None, mode_transition=None, coverage=None, continuation_id=None, dag_root=None, window_lineage=None, set_session=None, activation_status=None, activation_features=None, onboarding=None, extra=None)

headers.halt

crp.headers.halt

HTTP 451 safety-halt response builder (SPEC-002 §13.2).

When the gateway refuses to relay a generation for legal/safety reasons it returns HTTP 451 Unavailable For Legal Reasons with a structured JSON body and a fixed set of CRP response headers. :func:build_halt_response produces both so any transport can serialise them.

HaltReason

Bases: str, Enum

Canonical crp_halt_reason values (SPEC-002 §13.2).

HaltResponse dataclass

A fully-formed HTTP 451 safety halt (body + headers).

build_halt_response(*, reason, session_id, audit_trail_uri, oversight_required=False, retry_condition=None, hallucination_risk=None, retry_after=None)

Build the HTTP 451 safety-halt response (SPEC-002 §13.2).

Parameters:

Name Type Description Default
reason HaltReason | str

a :class:HaltReason (or its string value).

required
session_id str

the halted session id.

required
audit_trail_uri str

dereferenceable URI to the audit trail for this halt.

required
oversight_required bool

whether human oversight must approve a retry.

False
retry_condition str | None

"oversight-required" or an ISO-8601 timestamp. If omitted it defaults to "oversight-required" when oversight_required is set, else None.

None
hallucination_risk str | None

optional risk tier for the CRP-Safety-Hallucination-Risk header (e.g. "CRITICAL").

None
retry_after int | str | None

optional CRP-Safety-Retry-After value (seconds or token).

None

Returns:

Type Description
HaltResponse

class:HaltResponse with http_status=451.

headers.middleware

crp.headers.middleware

Response-header injection middleware (CRP-SPEC-002).

Provides a Starlette/FastAPI :class:CRPHeaderMiddleware (import-guarded so the core library never hard-depends on Starlette) and framework-agnostic helpers.

Usage pattern (FastAPI)::

from crp.headers.middleware import CRPHeaderMiddleware
app.add_middleware(CRPHeaderMiddleware)

@app.post("/crp/v3/dispatch")
async def dispatch(request: Request):
    ...
    request.state.crp_headers = emit_headers(provenance=report, quality=q)
    return JSONResponse({"output": result.output})

The route computes the CRP headers (via :func:crp.headers.emit.emit_headers) and stashes them on request.state.crp_headers; the middleware merges them onto the outgoing response.

CRPHeaderMiddleware

Placeholder raised if used without Starlette installed.

merge_headers(response_headers, crp_headers)

Merge crp_headers into a plain header dict (CRP values win).

inject_into_raw(raw_headers, crp_headers)

Append crp_headers to an ASGI raw-header list (no framework needed).

headers.names

crp.headers.names

CRP HTTP header-name constants (CRP-SPEC-002).

Single source of truth for every CRP-* header name emitted or parsed by the protocol surface. Grouped by namespace. The ten provisional IANA registrations are flagged in :data:IANA_PRIORITY.

All names are canonical (Title-Case, hyphenated) per RFC 9110 §5.1. HTTP header names are case-insensitive, but emitting canonical casing keeps the wire format tidy and audit-friendly.

is_crp_header(name)

Return True if name is a CRP protocol header (case-insensitive).

headers.parse

crp.headers.parse

Inbound CRP request-header parsing + Axiom-4 stripping (CRP-SPEC-002/015).

Two responsibilities:

  1. :func:parse_request_headers - read the client's CRP request preferences (safety policy, accepted quality/strategy/risk, conditional-dispatch ETag, cache directives, grounding mode, session token, data residency, reproducibility seed) into a structured :class:RequestDirectives.

  2. :func:strip_crp_headers - Axiom 4: the gateway MUST NOT forward any CRP-* header to the LLM provider. An allowlist-free, prefix-based filter guarantees no governance header leaks downstream.

RequestDirectives dataclass

Structured view of inbound CRP request preferences.

has_policy property

Return whether this object has policy.

parse_request_headers(headers)

Parse a mapping of inbound HTTP headers into :class:RequestDirectives.

strip_crp_headers(headers)

Return headers with every CRP-* header removed.

Axiom 4 (CRP-SPEC-001/015): no CRP governance header may reach the LLM provider. This filter is prefix-based so it is robust to future header additions - anything starting with CRP- is dropped.

assert_no_crp_headers(headers)

Raise AssertionError if any name in headers is a CRP header.

Intended for conformance tests (TV-002) that verify Axiom-4 compliance on the outbound provider request.

is_forbidden_request_header(name)

Return True if name is a response-namespace header forbidden on requests per SPEC-002 §14.1 (and not on the request allowlist).

strip_inbound_forbidden_headers(headers)

Strip client-spoofed response-namespace headers from an inbound request.

SPEC-002 §14.1: CRP-Safety-*/CRP-Provenance-*/CRP-Compliance-*/ CRP-Quality-* are gateway-authoritative response headers. A client MUST NOT set them; the gateway MUST strip any it receives.

Returns (cleaned_headers, stripped_names).