hyf

Context-aware query service for Radroots
git clone https://radroots.dev/git/hyf.git
Log | Files | Refs | README | LICENSE

operation_context.mojo (15600B)


      1 # D57 — hyf_ops_v3 context; v2 is retained as pre-activation characterization.
      2 #
      3 # This module owns the strict operation context selected by hyf_ops_v3 and
      4 # the historical v2 pre-activation compatibility controls. It does not implement
      5 # operation pipelines (C008/C009), typed semantic consistency (C023) or
      6 # activation (C042-C046). A recognized versioned request is parsed, then refused in
      7 # hyf_stdio.server; it must never reach the legacy shortcut handlers.
      8 
      9 from std.collections import Dict, List, Optional
     10 
     11 from json import Value
     12 from json.deserialize import get_bool, get_int, get_string
     13 
     14 
     15 comptime OPERATION_CONTRACT_SCHEMA_V2: String = "hyf_ops_v2"
     16 comptime OPERATION_CONTRACT_SCHEMA_V3: String = "hyf_ops_v3"
     17 comptime OPERATION_CONTEXT_DEFAULT_DEADLINE_MS: Int = 2500
     18 
     19 
     20 def corrected_operation_selector() -> String:
     21     return OPERATION_CONTRACT_SCHEMA_V3
     22 
     23 
     24 def is_corrected_operation(capability: String) -> Bool:
     25     return (
     26         capability == "farm_update.interpret"
     27         or capability == "buyer_request.interpret"
     28         or capability == "buyer_request.match"
     29     )
     30 
     31 
     32 def corrected_operation_requires_farm_id(capability: String) -> Bool:
     33     return capability == "farm_update.interpret"
     34 
     35 
     36 def corrected_operation_activation_enabled() -> Bool:
     37     """Activation boundary owned by C042-C046; C004 binds but never activates.
     38     """
     39     return False
     40 
     41 
     42 def _has_key(value: Value, key: String) -> Bool:
     43     for candidate in value.object_keys():
     44         if candidate == key:
     45             return True
     46     return False
     47 
     48 
     49 def _require_object(value: Value, context: String) raises:
     50     if not value.is_object():
     51         raise Error(context + " must be a JSON object")
     52 
     53 
     54 def _require_no_duplicate_keys(value: Value, context: String) raises:
     55     # ADR-0026 D46 CR04: bounded linear seen-key admission. The previous
     56     # all-pairs scan was quadratic in the decoded key count; this visits each
     57     # entry once and rejects the first repeated decoded key.
     58     var seen = Dict[String, Bool]()
     59     for item in value.object_items():
     60         var key = String(item[0])
     61         if key in seen:
     62             raise Error(context + " contains duplicate field '" + key + "'")
     63         seen[key] = True
     64 
     65 
     66 def _require_allowed_keys(
     67     value: Value, allowed_keys: List[String], context: String
     68 ) raises:
     69     for key in value.object_keys():
     70         var allowed = False
     71         for allowed_key in allowed_keys:
     72             if key == allowed_key:
     73                 allowed = True
     74                 break
     75         if not allowed:
     76             raise Error(context + " contains unexpected field '" + key + "'")
     77 
     78 
     79 def _has_nonblank(value: String) -> Bool:
     80     return String(value).strip().byte_length() > 0
     81 
     82 
     83 def _require_nonblank(value: String, context: String) raises:
     84     if not _has_nonblank(value):
     85         raise Error(context + " must not be blank")
     86 
     87 
     88 def _optional_string(
     89     value: Value, key: String, context: String
     90 ) raises -> Optional[String]:
     91     if not _has_key(value, key):
     92         return None
     93     var raw = get_string(value, key)
     94     _require_nonblank(raw, context)
     95     return String(raw)
     96 
     97 
     98 def _required_string(
     99     value: Value, key: String, context: String
    100 ) raises -> String:
    101     if not _has_key(value, key):
    102         raise Error(context + " is required")
    103     var raw = get_string(value, key)
    104     _require_nonblank(raw, context)
    105     return String(raw)
    106 
    107 
    108 @fieldwise_init
    109 struct OperationVersions(Copyable, Movable):
    110     var schema: String
    111     var taxonomy: String
    112     var normalization: String
    113     var review_policy: String
    114     var ranking_policy: String
    115     var question_bundle: String
    116     var model: String
    117 
    118 
    119 def _parse_operation_versions(
    120     json: Value, context: String
    121 ) raises -> OperationVersions:
    122     _require_object(json, context)
    123     _require_no_duplicate_keys(json, context)
    124 
    125     var allowed_keys = List[String]()
    126     for key in [
    127         "schema",
    128         "taxonomy",
    129         "normalization",
    130         "review_policy",
    131         "ranking_policy",
    132         "question_bundle",
    133         "model",
    134     ]:
    135         allowed_keys.append(key)
    136     _require_allowed_keys(json, allowed_keys, context)
    137 
    138     var schema = _required_string(json, "schema", context + " schema")
    139     if (
    140         schema != OPERATION_CONTRACT_SCHEMA_V2
    141         and schema != OPERATION_CONTRACT_SCHEMA_V3
    142     ):
    143         raise Error(
    144             context
    145             + " selects unsupported operation contract schema '"
    146             + schema
    147             + "'"
    148         )
    149 
    150     var model = _required_string(json, "model", context + " model")
    151     if schema == OPERATION_CONTRACT_SCHEMA_V3 and model != "jev-1.14.0":
    152         raise Error(context + " requires exact Jev model jev-1.14.0")
    153 
    154     return OperationVersions(
    155         schema=schema,
    156         taxonomy=_required_string(json, "taxonomy", context + " taxonomy"),
    157         normalization=_required_string(
    158             json, "normalization", context + " normalization"
    159         ),
    160         review_policy=_required_string(
    161             json, "review_policy", context + " review_policy"
    162         ),
    163         ranking_policy=_required_string(
    164             json, "ranking_policy", context + " ranking_policy"
    165         ),
    166         question_bundle=_required_string(
    167             json, "question_bundle", context + " question_bundle"
    168         ),
    169         model=model,
    170     )
    171 
    172 
    173 @fieldwise_init
    174 struct OperationActor(Copyable, Movable):
    175     # This is an untrusted public ActorRef descriptor, never an authenticated
    176     # CommandContext. The host retains and revalidates its SDK context.
    177     var participant: String
    178     var role: String
    179     var organization: Optional[String]
    180     var grant_id: Optional[String]
    181 
    182 
    183 def _canonical_identity(value: String, context: String) raises -> String:
    184     if value.byte_length() != 64:
    185         raise Error(context + " must be a 64-character lowercase hex identity")
    186     for i in range(value.byte_length()):
    187         var byte = value.unsafe_ptr()[i]
    188         if not ((byte >= 48 and byte <= 57) or (byte >= 97 and byte <= 102)):
    189             raise Error(context + " must use lowercase ASCII hex")
    190     return value
    191 
    192 
    193 def _nullable_identity(
    194     value: Value, key: String, context: String
    195 ) raises -> Optional[String]:
    196     if not _has_key(value, key):
    197         raise Error(context + " is required (explicit null is permitted)")
    198     var raw = value[key]
    199     if raw.is_null():
    200         return None
    201     return _canonical_identity(get_string(value, key), context)
    202 
    203 
    204 def _parse_operation_actor(value: Value) raises -> OperationActor:
    205     _require_object(value, "operation context actor")
    206     _require_no_duplicate_keys(value, "operation context actor")
    207     var keys = List[String]()
    208     for key in ["participant", "role", "organization", "grant_id"]:
    209         keys.append(key)
    210     _require_allowed_keys(value, keys, "operation context actor")
    211     var participant = _canonical_identity(
    212         _required_string(value, "participant", "actor participant"),
    213         "actor participant",
    214     )
    215     var role = _required_string(value, "role", "actor role")
    216     if role != "seller" and role != "buyer" and role != "coordinator":
    217         raise Error("actor role must be seller, buyer or coordinator")
    218     return OperationActor(
    219         participant=participant,
    220         role=role,
    221         organization=_nullable_identity(
    222             value, "organization", "actor organization"
    223         ),
    224         grant_id=_nullable_identity(value, "grant_id", "actor grant_id"),
    225     )
    226 
    227 
    228 def _canonical_unix_seconds(value: String) raises:
    229     # Representation parity with public radroots_domain::UnixSeconds. Time
    230     # interpretation and source eligibility remain with the shared SDK owner.
    231     var size = value.byte_length()
    232     if size == 0 or size > 12:
    233         raise Error("evaluation_time must be canonical bounded UnixSeconds")
    234     if size > 1 and value.unsafe_ptr()[0] == 48:
    235         raise Error("evaluation_time must not have leading zeros")
    236     var seconds = 0
    237     for i in range(size):
    238         var byte = value.unsafe_ptr()[i]
    239         if byte < 48 or byte > 57:
    240             raise Error("evaluation_time must use unsigned ASCII seconds")
    241         seconds = seconds * 10 + Int(byte) - 48
    242     if seconds > 253402300799:
    243         raise Error("evaluation_time exceeds the shared UnixSeconds bound")
    244 
    245 
    246 @fieldwise_init
    247 struct OperationContext(Copyable, Movable):
    248     var consumer: String
    249     var execution_mode_preference: String
    250     var deadline_ms: Int
    251     var evaluation_time: String
    252     var timezone: Optional[String]
    253     var locale: Optional[String]
    254     var versions: OperationVersions
    255     var return_provenance: Bool
    256     var actor_id: String
    257     var farm_id: Optional[String]
    258     var actor: Optional[OperationActor]
    259     var workspace_id: Optional[String]
    260 
    261 
    262 def default_operation_context() -> OperationContext:
    263     return OperationContext(
    264         consumer="unknown",
    265         execution_mode_preference="deterministic",
    266         deadline_ms=OPERATION_CONTEXT_DEFAULT_DEADLINE_MS,
    267         evaluation_time="",
    268         timezone=None,
    269         locale=None,
    270         versions=OperationVersions(
    271             schema="",
    272             taxonomy="",
    273             normalization="",
    274             review_policy="",
    275             ranking_policy="",
    276             question_bundle="",
    277             model="",
    278         ),
    279         return_provenance=False,
    280         actor_id="",
    281         farm_id=None,
    282         actor=None,
    283         workspace_id=None,
    284     )
    285 
    286 
    287 def operation_context_selects_v3(context_json: Value) raises -> Bool:
    288     if not context_json.is_object() or not _has_key(context_json, "versions"):
    289         return False
    290     var versions = context_json["versions"]
    291     if not versions.is_object() or not _has_key(versions, "schema"):
    292         return False
    293     var schema = versions["schema"]
    294     return (
    295         schema.is_string()
    296         and String(schema.string_value()) == OPERATION_CONTRACT_SCHEMA_V3
    297     )
    298 
    299 
    300 def operation_context_selects_v2(context_json: Value) raises -> Bool:
    301     """True only for a well-typed ``context.versions.schema == hyf_ops_v2``.
    302 
    303     Missing, null, wrong-type and unknown selectors are not recognized here;
    304     they fall through to the unchanged legacy parser, which rejects
    305     ``versions`` for unrelated capabilities and returns invalid_request.
    306 
    307     ADR-0026 D46 CR04: this first-wins lookup is only used after the envelope
    308     root duplicate gate has rejected any ambiguous v2-targeting envelope; use
    309     ``context_selects_versioned_any`` for duplicate-aware inspection.
    310     """
    311     if not context_json.is_object():
    312         return False
    313     if not _has_key(context_json, "versions"):
    314         return False
    315     var versions = context_json["versions"]
    316     if not versions.is_object():
    317         return False
    318     if not _has_key(versions, "schema"):
    319         return False
    320     var schema = versions["schema"]
    321     if not schema.is_string():
    322         return False
    323     return String(schema.string_value()) == OPERATION_CONTRACT_SCHEMA_V2
    324 
    325 
    326 def context_selects_versioned_any(context_json: Value) raises -> Bool:
    327     """Duplicate-aware v2/v3 inspection for the envelope admission gate.
    328 
    329     Scans every decoded ``versions`` member and every decoded ``schema`` entry
    330     instead of the first match, so a duplicate key cannot hide a v2 selector
    331     behind an earlier legacy value. Not a substitute for unambiguous parsing:
    332     the caller rejects the whole envelope when duplicate root keys are found.
    333     """
    334     if not context_json.is_object():
    335         return False
    336     for item in context_json.object_items():
    337         if item[0] != "versions":
    338             continue
    339         var versions = item[1].copy()
    340         if not versions.is_object():
    341             continue
    342         for member in versions.object_items():
    343             if member[0] == "schema" and member[1].is_string():
    344                 if (
    345                     String(member[1].string_value())
    346                     == OPERATION_CONTRACT_SCHEMA_V2
    347                     or String(member[1].string_value())
    348                     == OPERATION_CONTRACT_SCHEMA_V3
    349                 ):
    350                     return True
    351     return False
    352 
    353 
    354 def parse_operation_context(
    355     json: Value, capability: String
    356 ) raises -> OperationContext:
    357     if not is_corrected_operation(capability):
    358         raise Error(
    359             "operation context is only defined for corrected operations, not '"
    360             + capability
    361             + "'"
    362         )
    363 
    364     _require_object(json, "operation context")
    365     _require_no_duplicate_keys(json, "operation context")
    366 
    367     var is_v3 = operation_context_selects_v3(json)
    368     var requires_farm = not is_v3 and corrected_operation_requires_farm_id(
    369         capability
    370     )
    371     var allowed_keys = List[String]()
    372     for key in [
    373         "consumer",
    374         "execution_mode_preference",
    375         "deadline_ms",
    376         "evaluation_time",
    377         "timezone",
    378         "locale",
    379         "versions",
    380         "return_provenance",
    381     ]:
    382         allowed_keys.append(key)
    383     if is_v3:
    384         allowed_keys.append("actor")
    385         allowed_keys.append("workspace_id")
    386     else:
    387         allowed_keys.append("actor_id")
    388     if requires_farm:
    389         allowed_keys.append("farm_id")
    390     _require_allowed_keys(json, allowed_keys, "operation context")
    391 
    392     var context = default_operation_context()
    393 
    394     var consumer = _optional_string(
    395         json, "consumer", "operation context consumer"
    396     )
    397     if consumer:
    398         context.consumer = consumer.value()
    399 
    400     if _has_key(json, "execution_mode_preference"):
    401         var preference = get_string(json, "execution_mode_preference")
    402         if preference != "deterministic" and preference != "assisted":
    403             raise Error(
    404                 "operation context execution_mode_preference must be"
    405                 " 'deterministic' or 'assisted'"
    406             )
    407         context.execution_mode_preference = String(preference)
    408 
    409     if _has_key(json, "deadline_ms"):
    410         context.deadline_ms = get_int(json, "deadline_ms")
    411         if context.deadline_ms <= 0 or (
    412             is_v3 and context.deadline_ms > 2147483647
    413         ):
    414             raise Error(
    415                 "operation context deadline_ms must be greater than zero"
    416             )
    417 
    418     context.evaluation_time = _required_string(
    419         json, "evaluation_time", "operation context evaluation_time"
    420     )
    421     if is_v3:
    422         _canonical_unix_seconds(context.evaluation_time)
    423 
    424     context.timezone = _optional_string(
    425         json, "timezone", "operation context timezone"
    426     )
    427     context.locale = _optional_string(
    428         json, "locale", "operation context locale"
    429     )
    430 
    431     if not _has_key(json, "versions"):
    432         raise Error("operation context versions is required")
    433     context.versions = _parse_operation_versions(
    434         json["versions"].clone(), "operation context versions"
    435     )
    436 
    437     if _has_key(json, "return_provenance"):
    438         context.return_provenance = get_bool(json, "return_provenance")
    439 
    440     if is_v3:
    441         if not _has_key(json, "actor"):
    442             raise Error("operation context actor is required")
    443         context.actor = _parse_operation_actor(json["actor"].clone())
    444         context.workspace_id = _canonical_identity(
    445             _required_string(
    446                 json, "workspace_id", "operation context workspace_id"
    447             ),
    448             "operation context workspace_id",
    449         )
    450         # Never turn this descriptor into an authorization token or a business
    451         # write. It remains behind the pre-activation guard until later owners.
    452     else:
    453         context.actor_id = _required_string(
    454             json, "actor_id", "operation context actor_id"
    455         )
    456 
    457     if requires_farm:
    458         context.farm_id = _required_string(
    459             json, "farm_id", "operation context farm_id"
    460         )
    461 
    462     return context^