mostlyright-data 0.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mostlyright/data_harness/__init__.py +158 -0
- mostlyright/data_harness/acquisition/__init__.py +55 -0
- mostlyright/data_harness/acquisition/http.py +2773 -0
- mostlyright/data_harness/acquisition/parsing.py +809 -0
- mostlyright/data_harness/acquisition/ranges.py +495 -0
- mostlyright/data_harness/acquisition/result_download.py +360 -0
- mostlyright/data_harness/acquisition/retention_admission.py +248 -0
- mostlyright/data_harness/acquisition/sandbox.py +4888 -0
- mostlyright/data_harness/acquisition/url_policy.py +530 -0
- mostlyright/data_harness/agent_runtime.py +2743 -0
- mostlyright/data_harness/assets/logo-ink.svg +31 -0
- mostlyright/data_harness/backends/__init__.py +28 -0
- mostlyright/data_harness/backends/pandas_backend.py +350 -0
- mostlyright/data_harness/backends/polars_backend.py +366 -0
- mostlyright/data_harness/backends/protocol.py +124 -0
- mostlyright/data_harness/backends/reference.py +83 -0
- mostlyright/data_harness/backends/registry.py +55 -0
- mostlyright/data_harness/backends/restrictions.py +126 -0
- mostlyright/data_harness/canonical.py +333 -0
- mostlyright/data_harness/catalog_job.py +625 -0
- mostlyright/data_harness/cli.py +5398 -0
- mostlyright/data_harness/contracts.py +53 -0
- mostlyright/data_harness/coordinator.py +1307 -0
- mostlyright/data_harness/deploy.py +924 -0
- mostlyright/data_harness/deploy_target.py +312 -0
- mostlyright/data_harness/deployment_evidence.py +1067 -0
- mostlyright/data_harness/event_presentation.py +576 -0
- mostlyright/data_harness/events.py +2152 -0
- mostlyright/data_harness/fast_delimited.py +239 -0
- mostlyright/data_harness/fleet.py +237 -0
- mostlyright/data_harness/formats.py +236 -0
- mostlyright/data_harness/governors.py +1163 -0
- mostlyright/data_harness/hosted_bootstrap.py +972 -0
- mostlyright/data_harness/hosted_crawler.py +1115 -0
- mostlyright/data_harness/hosted_crawler_container_smoke.py +351 -0
- mostlyright/data_harness/hosted_crawler_fetch.py +423 -0
- mostlyright/data_harness/hosted_crawler_job.py +1277 -0
- mostlyright/data_harness/hosted_crawler_protocol.py +676 -0
- mostlyright/data_harness/hosted_dataset.py +1500 -0
- mostlyright/data_harness/hosted_deploy.py +3037 -0
- mostlyright/data_harness/hosted_handoff.py +62 -0
- mostlyright/data_harness/hosted_ingestion_contract.py +504 -0
- mostlyright/data_harness/hosted_ingestion_job.py +356 -0
- mostlyright/data_harness/hosted_ingestion_job_smoke.py +40 -0
- mostlyright/data_harness/hosted_session_container_smoke.py +194 -0
- mostlyright/data_harness/hosted_session_worker.py +3554 -0
- mostlyright/data_harness/hosted_session_worker_job_smoke.py +46 -0
- mostlyright/data_harness/hosted_worker.py +6784 -0
- mostlyright/data_harness/ingestion/__init__.py +56 -0
- mostlyright/data_harness/ingestion/contracts.py +461 -0
- mostlyright/data_harness/ingestion/faults.py +42 -0
- mostlyright/data_harness/ingestion/gcs_store.py +1162 -0
- mostlyright/data_harness/ingestion/spool.py +130 -0
- mostlyright/data_harness/ingestion/store.py +885 -0
- mostlyright/data_harness/key_seam.py +434 -0
- mostlyright/data_harness/linux_process_boundary.py +262 -0
- mostlyright/data_harness/local_contracts.py +2880 -0
- mostlyright/data_harness/local_search/__init__.py +5 -0
- mostlyright/data_harness/local_search/build_index.py +1087 -0
- mostlyright/data_harness/local_search/contracts.py +920 -0
- mostlyright/data_harness/local_search/query_trace.py +266 -0
- mostlyright/data_harness/local_search/retrieval.py +700 -0
- mostlyright/data_harness/local_search/sealed.py +474 -0
- mostlyright/data_harness/local_search/service.py +784 -0
- mostlyright/data_harness/nbrender/CONTRACT.md +212 -0
- mostlyright/data_harness/nbrender/__init__.py +12 -0
- mostlyright/data_harness/nbrender/chrome.py +359 -0
- mostlyright/data_harness/nbrender/code_body.py +266 -0
- mostlyright/data_harness/nbrender/document.py +407 -0
- mostlyright/data_harness/nbrender/frame.py +275 -0
- mostlyright/data_harness/nbrender/interactive.py +337 -0
- mostlyright/data_harness/nbrender/markdown_body.py +477 -0
- mostlyright/data_harness/nbrender/mr_components.py +134 -0
- mostlyright/data_harness/nbrender/outputs_data.py +595 -0
- mostlyright/data_harness/nbrender/outputs_rich.py +906 -0
- mostlyright/data_harness/nbrender/outputs_source.py +260 -0
- mostlyright/data_harness/nbrender/outputs_stage.py +176 -0
- mostlyright/data_harness/nbrender/outputs_text.py +400 -0
- mostlyright/data_harness/nbrender/parse.py +394 -0
- mostlyright/data_harness/nbrender/status.py +40 -0
- mostlyright/data_harness/nbrender/tokens.py +1295 -0
- mostlyright/data_harness/notebook.py +1710 -0
- mostlyright/data_harness/offline.py +2049 -0
- mostlyright/data_harness/operation_registry.py +1007 -0
- mostlyright/data_harness/operator_setup.py +239 -0
- mostlyright/data_harness/pipeline.py +6428 -0
- mostlyright/data_harness/plan_graph.py +2026 -0
- mostlyright/data_harness/preparation/__init__.py +104 -0
- mostlyright/data_harness/preparation/contracts.py +1017 -0
- mostlyright/data_harness/preparation/engine.py +221 -0
- mostlyright/data_harness/preparation/errors.py +14 -0
- mostlyright/data_harness/preparation/gates.py +751 -0
- mostlyright/data_harness/preparation/joins.py +574 -0
- mostlyright/data_harness/preparation/profile.py +384 -0
- mostlyright/data_harness/preparation/table.py +217 -0
- mostlyright/data_harness/preparation/transforms.py +568 -0
- mostlyright/data_harness/progress_events.py +534 -0
- mostlyright/data_harness/readers/__init__.py +46 -0
- mostlyright/data_harness/readers/containers.py +963 -0
- mostlyright/data_harness/readers/contracts.py +542 -0
- mostlyright/data_harness/readers/delimited.py +257 -0
- mostlyright/data_harness/readers/grib2/__init__.py +33 -0
- mostlyright/data_harness/readers/grib2/admission.py +722 -0
- mostlyright/data_harness/readers/grib2/decode.py +1009 -0
- mostlyright/data_harness/readers/grib2/geometry.py +1133 -0
- mostlyright/data_harness/readers/grib2/portable_math.py +501 -0
- mostlyright/data_harness/readers/json_tabular.py +485 -0
- mostlyright/data_harness/readers/registry.py +514 -0
- mostlyright/data_harness/readers/samples/README.md +110 -0
- mostlyright/data_harness/readers/samples/archive.gzip/1.0.0/cities_one_stream/cities.csv.gz +0 -0
- mostlyright/data_harness/readers/samples/archive.gzip/1.0.0/cities_one_stream/expected.json +24 -0
- mostlyright/data_harness/readers/samples/archive.gzip/1.1.0/cities_one_stream/cities.csv.gz +0 -0
- mostlyright/data_harness/readers/samples/archive.gzip/1.1.0/cities_one_stream/expected.json +24 -0
- mostlyright/data_harness/readers/samples/archive.tar/1.0.0/cities_beside_a_directory_entry/cities.tar +0 -0
- mostlyright/data_harness/readers/samples/archive.tar/1.0.0/cities_beside_a_directory_entry/expected.json +24 -0
- mostlyright/data_harness/readers/samples/archive.tar/1.1.0/cities_beside_a_directory_entry/cities.tar +0 -0
- mostlyright/data_harness/readers/samples/archive.tar/1.1.0/cities_beside_a_directory_entry/expected.json +24 -0
- mostlyright/data_harness/readers/samples/archive.zip/1.0.0/cities_beside_a_second_member/cities.zip +0 -0
- mostlyright/data_harness/readers/samples/archive.zip/1.0.0/cities_beside_a_second_member/expected.json +25 -0
- mostlyright/data_harness/readers/samples/archive.zip/1.1.0/dwd_semicolon_station_member/dwd-station.zip +0 -0
- mostlyright/data_harness/readers/samples/archive.zip/1.1.0/dwd_semicolon_station_member/expected.json +25 -0
- mostlyright/data_harness/readers/samples/archive.zip/1.2.0/dwd_semicolon_station_member/dwd-station.zip +0 -0
- mostlyright/data_harness/readers/samples/archive.zip/1.2.0/dwd_semicolon_station_member/expected.json +25 -0
- mostlyright/data_harness/readers/samples/delimited_text/1.0.0/an_ordinary_comma_separated_table/cities.csv +3 -0
- mostlyright/data_harness/readers/samples/delimited_text/1.0.0/an_ordinary_comma_separated_table/expected.json +23 -0
- mostlyright/data_harness/readers/samples/delimited_text/1.0.0/quoted_fields_holding_the_delimiter/cities.tsv +5 -0
- mostlyright/data_harness/readers/samples/delimited_text/1.0.0/quoted_fields_holding_the_delimiter/expected.json +25 -0
- mostlyright/data_harness/readers/samples/delimited_text/1.1.0/an_hourly_observation_table_served_as_plain_text/expected.json +30 -0
- mostlyright/data_harness/readers/samples/delimited_text/1.1.0/an_hourly_observation_table_served_as_plain_text/observations.csv +5 -0
- mostlyright/data_harness/readers/samples/json.tabular/1.0.0/nested_hourly_observations/expected.json +44 -0
- mostlyright/data_harness/readers/samples/json.tabular/1.0.0/nested_hourly_observations/stations.json +1 -0
- mostlyright/data_harness/readers/samples/json.tabular/1.1.0/an_observation_stream_served_as_plain_text/expected.json +48 -0
- mostlyright/data_harness/readers/samples/json.tabular/1.1.0/an_observation_stream_served_as_plain_text/observations.ndjson +4 -0
- mostlyright/data_harness/readers/samples/spreadsheet.xlsx/1.0.0/an_ordinary_table_beside_a_second_sheet/cities.xlsx +0 -0
- mostlyright/data_harness/readers/samples/spreadsheet.xlsx/1.0.0/an_ordinary_table_beside_a_second_sheet/expected.json +24 -0
- mostlyright/data_harness/readers/samples/spreadsheet.xlsx/1.0.0/shares_the_workbook_had_already_computed/expected.json +27 -0
- mostlyright/data_harness/readers/samples/spreadsheet.xlsx/1.0.0/shares_the_workbook_had_already_computed/shares.xlsx +0 -0
- mostlyright/data_harness/readers/samples/spreadsheet.xlsx/1.1.0/shares_the_workbook_had_already_computed/expected.json +27 -0
- mostlyright/data_harness/readers/samples/spreadsheet.xlsx/1.1.0/shares_the_workbook_had_already_computed/shares.xlsx +0 -0
- mostlyright/data_harness/readers/samples/weather.grib2/1.0.0/README.md +20 -0
- mostlyright/data_harness/readers/samples/weather.grib2/1.0.0/gfs_2m_temperature/expected.json +55 -0
- mostlyright/data_harness/readers/samples/weather.grib2/1.0.0/gfs_2m_temperature/gfs-2m-temperature.grib2 +0 -0
- mostlyright/data_harness/readers/samples/weather.grib2/1.0.0/hrrr_2m_temperature/expected.json +54 -0
- mostlyright/data_harness/readers/samples/weather.grib2/1.0.0/hrrr_2m_temperature/hrrr-2m-temperature.grib2 +0 -0
- mostlyright/data_harness/readers/samples/weather.grib2/1.0.0/hrrr_categorical_rain/expected.json +54 -0
- mostlyright/data_harness/readers/samples/weather.grib2/1.0.0/hrrr_categorical_rain/hrrr-categorical-rain.grib2 +0 -0
- mostlyright/data_harness/readers/samples/weather.grib2/2.0.0/hrrr_2m_temperature/expected.json +54 -0
- mostlyright/data_harness/readers/samples/weather.grib2/2.0.0/hrrr_2m_temperature/hrrr-2m-temperature.grib2 +0 -0
- mostlyright/data_harness/readers/samples.py +582 -0
- mostlyright/data_harness/readers/spreadsheet.py +803 -0
- mostlyright/data_harness/readers/tabular.py +510 -0
- mostlyright/data_harness/recipe.py +5321 -0
- mostlyright/data_harness/repair/__init__.py +78 -0
- mostlyright/data_harness/repair/adapters.py +274 -0
- mostlyright/data_harness/repair/contracts.py +872 -0
- mostlyright/data_harness/repair/coordinator.py +1099 -0
- mostlyright/data_harness/repair/errors.py +16 -0
- mostlyright/data_harness/review.py +2533 -0
- mostlyright/data_harness/rowset.py +283 -0
- mostlyright/data_harness/serving.py +1975 -0
- mostlyright/data_harness/serving_edge.py +590 -0
- mostlyright/data_harness/serving_http.py +1031 -0
- mostlyright/data_harness/session_probes.py +759 -0
- mostlyright/data_harness/signing.py +101 -0
- mostlyright/data_harness/source_discovery.py +898 -0
- mostlyright/data_harness/sources/__init__.py +209 -0
- mostlyright/data_harness/sources/_adapter_steps.py +213 -0
- mostlyright/data_harness/sources/adapters.py +1214 -0
- mostlyright/data_harness/sources/cadence.py +1428 -0
- mostlyright/data_harness/sources/cadence_emission.py +453 -0
- mostlyright/data_harness/sources/cadence_history.py +546 -0
- mostlyright/data_harness/sources/catalog/__init__.py +17 -0
- mostlyright/data_harness/sources/catalog/admission.py +477 -0
- mostlyright/data_harness/sources/catalog/authoring.py +1701 -0
- mostlyright/data_harness/sources/catalog/authoring_policy.py +701 -0
- mostlyright/data_harness/sources/catalog/authoring_shards.py +1217 -0
- mostlyright/data_harness/sources/catalog/bounded_io.py +231 -0
- mostlyright/data_harness/sources/catalog/channel.py +523 -0
- mostlyright/data_harness/sources/catalog/channel_client.py +296 -0
- mostlyright/data_harness/sources/catalog/contracts.py +825 -0
- mostlyright/data_harness/sources/catalog/coverage.py +137 -0
- mostlyright/data_harness/sources/catalog/delta.py +1340 -0
- mostlyright/data_harness/sources/catalog/embedding.py +532 -0
- mostlyright/data_harness/sources/catalog/entry_v2.py +1182 -0
- mostlyright/data_harness/sources/catalog/fill.py +3889 -0
- mostlyright/data_harness/sources/catalog/fill_partitions.py +459 -0
- mostlyright/data_harness/sources/catalog/fill_staging.py +1105 -0
- mostlyright/data_harness/sources/catalog/gating.py +374 -0
- mostlyright/data_harness/sources/catalog/generation_receipt.py +1607 -0
- mostlyright/data_harness/sources/catalog/harvest/__init__.py +7 -0
- mostlyright/data_harness/sources/catalog/harvest/ckan.py +384 -0
- mostlyright/data_harness/sources/catalog/harvest/datagov_v4.py +798 -0
- mostlyright/data_harness/sources/catalog/harvest/protocol.py +964 -0
- mostlyright/data_harness/sources/catalog/harvest/sdmx.py +445 -0
- mostlyright/data_harness/sources/catalog/harvest/stac.py +384 -0
- mostlyright/data_harness/sources/catalog/health.py +447 -0
- mostlyright/data_harness/sources/catalog/hosted_catalog.py +105 -0
- mostlyright/data_harness/sources/catalog/identity_history.py +1549 -0
- mostlyright/data_harness/sources/catalog/neural.py +1618 -0
- mostlyright/data_harness/sources/catalog/packed_catalog.py +2345 -0
- mostlyright/data_harness/sources/catalog/packed_retrieval.py +1517 -0
- mostlyright/data_harness/sources/catalog/packed_writer.py +2802 -0
- mostlyright/data_harness/sources/catalog/query_trace.py +1037 -0
- mostlyright/data_harness/sources/catalog/recommend.py +171 -0
- mostlyright/data_harness/sources/catalog/retrieval.py +230 -0
- mostlyright/data_harness/sources/catalog/retrieval_manifest.py +995 -0
- mostlyright/data_harness/sources/catalog/rights_decisions.py +254 -0
- mostlyright/data_harness/sources/catalog/sealed.py +560 -0
- mostlyright/data_harness/sources/catalog/search.py +230 -0
- mostlyright/data_harness/sources/catalog/streaming_delta.py +1097 -0
- mostlyright/data_harness/sources/catalog/update.py +891 -0
- mostlyright/data_harness/sources/collections.py +815 -0
- mostlyright/data_harness/sources/contracts.py +2223 -0
- mostlyright/data_harness/sources/deletion.py +761 -0
- mostlyright/data_harness/sources/fitness.py +162 -0
- mostlyright/data_harness/sources/governance.py +163 -0
- mostlyright/data_harness/sources/hosted.py +173 -0
- mostlyright/data_harness/sources/integration.py +218 -0
- mostlyright/data_harness/sources/range_reader.py +418 -0
- mostlyright/data_harness/sources/registry.py +514 -0
- mostlyright/data_harness/sources/rights_rule.py +59 -0
- mostlyright/data_harness/sources/source_cadence_vectors.v1.json +1 -0
- mostlyright/data_harness/sources/sports.py +521 -0
- mostlyright/data_harness/sources/stream.py +524 -0
- mostlyright/data_harness/sources/stream_connector.py +418 -0
- mostlyright/data_harness/sources/stream_recorder.py +1404 -0
- mostlyright/data_harness/studio_boundary.py +2019 -0
- mostlyright/data_harness/thin/__init__.py +37 -0
- mostlyright/data_harness/thin/acquire.py +1137 -0
- mostlyright/data_harness/thin/acquire_cancel.py +579 -0
- mostlyright/data_harness/thin/approvals.py +617 -0
- mostlyright/data_harness/thin/commands.py +406 -0
- mostlyright/data_harness/thin/download.py +194 -0
- mostlyright/data_harness/thin/narrative.py +589 -0
- mostlyright/data_harness/thin/parity.py +1070 -0
- mostlyright/data_harness/thin/propose.py +2759 -0
- mostlyright/data_harness/thin/research.py +1663 -0
- mostlyright/data_harness/thin/router.py +924 -0
- mostlyright/data_harness/thin/runs.py +519 -0
- mostlyright/data_harness/thin/session.py +281 -0
- mostlyright/data_harness/thin/stream.py +501 -0
- mostlyright/data_harness/thin/transport.py +187 -0
- mostlyright/data_harness/thin/vocabulary.py +368 -0
- mostlyright/data_harness/thin/workers.py +164 -0
- mostlyright/data_harness/ucum/TABLE-PIN.json +40 -0
- mostlyright/data_harness/ucum/ucum-subset.v1.json +632 -0
- mostlyright/data_harness/unit_flow.py +927 -0
- mostlyright/data_harness/units.py +572 -0
- mostlyright/data_harness/ux/__init__.py +9 -0
- mostlyright/data_harness/ux/approve.py +485 -0
- mostlyright/data_harness/ux/author_yaml.py +597 -0
- mostlyright/data_harness/ux/cloud_auth.py +447 -0
- mostlyright/data_harness/ux/commands/__init__.py +260 -0
- mostlyright/data_harness/ux/commands/approve.py +136 -0
- mostlyright/data_harness/ux/commands/auth.py +744 -0
- mostlyright/data_harness/ux/commands/author.py +79 -0
- mostlyright/data_harness/ux/commands/catalog_author.py +403 -0
- mostlyright/data_harness/ux/commands/catalog_fill.py +523 -0
- mostlyright/data_harness/ux/commands/catalog_harvest.py +545 -0
- mostlyright/data_harness/ux/commands/catalog_publish.py +1838 -0
- mostlyright/data_harness/ux/commands/catalog_search.py +71 -0
- mostlyright/data_harness/ux/commands/catalog_update.py +437 -0
- mostlyright/data_harness/ux/commands/deploy.py +134 -0
- mostlyright/data_harness/ux/commands/deploy_dataset.py +98 -0
- mostlyright/data_harness/ux/commands/deploy_plan.py +105 -0
- mostlyright/data_harness/ux/commands/deploy_status.py +104 -0
- mostlyright/data_harness/ux/commands/diff.py +74 -0
- mostlyright/data_harness/ux/commands/index.py +84 -0
- mostlyright/data_harness/ux/commands/inventory.py +47 -0
- mostlyright/data_harness/ux/commands/list_builds.py +143 -0
- mostlyright/data_harness/ux/commands/login.py +63 -0
- mostlyright/data_harness/ux/commands/peek.py +236 -0
- mostlyright/data_harness/ux/commands/plan_check.py +90 -0
- mostlyright/data_harness/ux/commands/preflight.py +97 -0
- mostlyright/data_harness/ux/commands/record.py +107 -0
- mostlyright/data_harness/ux/commands/review_setup.py +47 -0
- mostlyright/data_harness/ux/commands/search.py +440 -0
- mostlyright/data_harness/ux/commands/show.py +61 -0
- mostlyright/data_harness/ux/commands/whoami.py +37 -0
- mostlyright/data_harness/ux/credential_native.py +551 -0
- mostlyright/data_harness/ux/credential_store.py +1055 -0
- mostlyright/data_harness/ux/credentials.py +631 -0
- mostlyright/data_harness/ux/diffing.py +444 -0
- mostlyright/data_harness/ux/headline.py +671 -0
- mostlyright/data_harness/ux/hosted_acquisition.py +974 -0
- mostlyright/data_harness/ux/hosted_run_status.py +619 -0
- mostlyright/data_harness/ux/inventory.py +427 -0
- mostlyright/data_harness/ux/local_review.py +375 -0
- mostlyright/data_harness/ux/login.py +691 -0
- mostlyright/data_harness/ux/path_kind.py +147 -0
- mostlyright/data_harness/ux/peek.py +1000 -0
- mostlyright/data_harness/ux/plain_file.py +178 -0
- mostlyright/data_harness/ux/plan_check.py +311 -0
- mostlyright/data_harness/ux/preflight.py +918 -0
- mostlyright/data_harness/ux/readers.py +1124 -0
- mostlyright/data_harness/ux/remediation.py +2195 -0
- mostlyright/data_harness/ux/render.py +657 -0
- mostlyright/data_harness/ux/workload.py +1077 -0
- mostlyright/data_harness/viewer.py +3713 -0
- mostlyright/data_harness/visual_run/__init__.py +83 -0
- mostlyright/data_harness/visual_run/authoring.py +235 -0
- mostlyright/data_harness/visual_run/contracts.py +673 -0
- mostlyright/data_harness/visual_run/materialize.py +486 -0
- mostlyright/data_harness/visual_run/observations.py +874 -0
- mostlyright/data_harness/visual_run/query.py +259 -0
- mostlyright/data_harness/visual_run/reducer.py +280 -0
- mostlyright/data_harness/visual_run/sdk.py +892 -0
- mostlyright/data_harness/visual_run/store.py +584 -0
- mostlyright/data_harness/visual_run/transport.py +239 -0
- mostlyright/data_harness/watch.py +2999 -0
- mostlyright_data-0.9.0.dist-info/METADATA +607 -0
- mostlyright_data-0.9.0.dist-info/RECORD +314 -0
- mostlyright_data-0.9.0.dist-info/WHEEL +4 -0
- mostlyright_data-0.9.0.dist-info/entry_points.txt +12 -0
|
@@ -0,0 +1,1618 @@
|
|
|
1
|
+
"""Governed, offline encoding from one explicit local neural-model sidecar.
|
|
2
|
+
|
|
3
|
+
This module is reachable only through ``embedding.resolve_local_neural_backend``. It has no model
|
|
4
|
+
root default and no download, cache, hub, plugin, socket, or arbitrary command-execution path.
|
|
5
|
+
Resolution captures regular files through one no-follow directory descriptor, verifies the exact
|
|
6
|
+
PIN and every member, then closes the descriptor. Resolution prepares one authenticated private
|
|
7
|
+
runtime worker so the per-item encode budget covers only inference.
|
|
8
|
+
|
|
9
|
+
Provider-scale callers use ``encode_many``, which is the shared bounded seam and not a second
|
|
10
|
+
encoder: it evaluates at most 1000 items serially through the ``encode`` below. Every nonempty
|
|
11
|
+
item returns the model-produced vector the three installed-wheel receipts authenticated for
|
|
12
|
+
that exact tuple; an empty item returns the descriptor-sized deterministic no-signal value
|
|
13
|
+
without inference. Every declared tuple runs this one adapter. The PIN's ``max_batch`` budget
|
|
14
|
+
is recorded and unrouted.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import base64
|
|
20
|
+
import binascii
|
|
21
|
+
import csv
|
|
22
|
+
import hashlib
|
|
23
|
+
import io
|
|
24
|
+
import multiprocessing
|
|
25
|
+
import os
|
|
26
|
+
import platform
|
|
27
|
+
import resource
|
|
28
|
+
import shutil
|
|
29
|
+
import stat
|
|
30
|
+
import sys
|
|
31
|
+
import sysconfig
|
|
32
|
+
import tempfile
|
|
33
|
+
from collections import deque
|
|
34
|
+
from importlib import metadata
|
|
35
|
+
from importlib.machinery import BuiltinImporter, FrozenImporter, PathFinder
|
|
36
|
+
from importlib.util import module_from_spec
|
|
37
|
+
from pathlib import Path, PurePosixPath
|
|
38
|
+
from typing import Any
|
|
39
|
+
|
|
40
|
+
from packaging.requirements import Requirement
|
|
41
|
+
from packaging.utils import canonicalize_name
|
|
42
|
+
|
|
43
|
+
from mostlyright.data_harness.canonical import canonical_json_bytes, parse_json
|
|
44
|
+
from mostlyright.data_harness.sources.catalog.embedding import (
|
|
45
|
+
BOUNDED_SCALAR_ADAPTER,
|
|
46
|
+
BatchEncodeResult,
|
|
47
|
+
PinnedLocalBackendDescriptor,
|
|
48
|
+
encode_many_bounded,
|
|
49
|
+
)
|
|
50
|
+
from mostlyright.data_harness.sources.contracts import SourceContractError
|
|
51
|
+
|
|
52
|
+
PIN_NAME = "PIN.json"
|
|
53
|
+
PIN_SHA256 = "42b5a7c9ff04b1ff306e35a711e4b937d50d286a3e62285a09a8e72bd479522a"
|
|
54
|
+
COORDINATE_SHA256 = "efb1bb9a47444ce60e0758041c027e51e419c01dd03797643b773d3f18e88510"
|
|
55
|
+
PIN_SCHEMA_VERSION = "local-search-neural-pin.v2"
|
|
56
|
+
BACKEND_ID = "minilm_l6_v2_local"
|
|
57
|
+
BACKEND_VERSION = "1.0.0"
|
|
58
|
+
DIMENSIONS = 384
|
|
59
|
+
QUANTIZATION = "int32_fixed_point_10000"
|
|
60
|
+
RUNTIME_VERSIONS = {"onnxruntime": "1.28.0", "tokenizers": "0.23.1"}
|
|
61
|
+
SUPPORTED_TUPLES = frozenset(
|
|
62
|
+
{
|
|
63
|
+
"macos-14-arm64-cpython-3.13.12",
|
|
64
|
+
"macos-15-arm64-cpython-3.13.12",
|
|
65
|
+
"ubuntu-24.04-x86_64-cpython-3.13.14",
|
|
66
|
+
}
|
|
67
|
+
)
|
|
68
|
+
MAX_PIN_BYTES = 512 * 1024
|
|
69
|
+
MAX_MODEL_BYTES = 128 * 1024 * 1024
|
|
70
|
+
MAX_TEXT_CHARS = 4_096
|
|
71
|
+
MAX_LENGTH = 256
|
|
72
|
+
VECTOR_SCALE = 10_000
|
|
73
|
+
MAX_ENCODE_LATENCY_NS = 2_000_000_000
|
|
74
|
+
MAX_PEAK_RSS_BYTES = 768 * 1024 * 1024
|
|
75
|
+
MAX_RUNTIME_INITIALIZATION_SECONDS = 15.0
|
|
76
|
+
|
|
77
|
+
#: The mode every declared tuple runs in, and the only one this module has evidence for.
|
|
78
|
+
BATCH_ADAPTER_MODE = BOUNDED_SCALAR_ADAPTER
|
|
79
|
+
|
|
80
|
+
#: The native batch width authenticated by the exact PIN (``budgets.max_batch``). It is recorded
|
|
81
|
+
#: and never read. Routing it would mean padding a group of texts to a common shape and running one
|
|
82
|
+
#: fused inference, and the vectors that came back would be a different computation from the
|
|
83
|
+
#: ones the installed-wheel receipts authenticated -- a claim the recorded measurements do not
|
|
84
|
+
#: support.
|
|
85
|
+
#: This constant records an unexercised budget and is not routed by the production adapter.
|
|
86
|
+
NATIVE_MAX_BATCH = 32
|
|
87
|
+
_INT32_MIN = -(1 << 31)
|
|
88
|
+
_INT32_MAX = (1 << 31) - 1
|
|
89
|
+
_WORKER_JOIN_SECONDS = 0.1
|
|
90
|
+
_RUNTIME_ROOT_DISTRIBUTIONS = (
|
|
91
|
+
"onnxruntime",
|
|
92
|
+
"tokenizers",
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# Capture interpreter-owned roots before an authenticated runtime finder is installed. Calling
|
|
96
|
+
# ``sysconfig`` from inside the finder would itself perform imports on a cold interpreter and hand
|
|
97
|
+
# those imports to the very meta-path hooks the finder is designed not to trust.
|
|
98
|
+
_STDLIB_ROOTS = frozenset(
|
|
99
|
+
Path(value).resolve(strict=True)
|
|
100
|
+
for key in ("stdlib", "platstdlib")
|
|
101
|
+
if isinstance((value := sysconfig.get_path(key)), str)
|
|
102
|
+
)
|
|
103
|
+
_THIRD_PARTY_ROOTS = frozenset(
|
|
104
|
+
Path(value).resolve(strict=True)
|
|
105
|
+
for key in ("purelib", "platlib")
|
|
106
|
+
if isinstance((value := sysconfig.get_path(key)), str)
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class LocalNeuralEmbeddingBackend:
|
|
111
|
+
"""A private-session embedding backend bound to captured, verified sidecar bytes."""
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
descriptor: PinnedLocalBackendDescriptor,
|
|
116
|
+
*,
|
|
117
|
+
model_bytes: bytes,
|
|
118
|
+
tokenizer_bytes: bytes,
|
|
119
|
+
runtime_closure_sha256: str,
|
|
120
|
+
) -> None:
|
|
121
|
+
self._descriptor = descriptor
|
|
122
|
+
self._model_bytes = model_bytes
|
|
123
|
+
self._tokenizer_bytes = tokenizer_bytes
|
|
124
|
+
self._runtime_closure_sha256 = runtime_closure_sha256
|
|
125
|
+
self._worker: tuple[Any, ...] | None = None
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def descriptor(self) -> PinnedLocalBackendDescriptor:
|
|
129
|
+
return self._descriptor
|
|
130
|
+
|
|
131
|
+
def encode(self, text: str) -> tuple[int, ...]:
|
|
132
|
+
if not isinstance(text, str) or len(text) > MAX_TEXT_CHARS:
|
|
133
|
+
raise SourceContractError(
|
|
134
|
+
"NEURAL_INPUT_LIMIT",
|
|
135
|
+
"embedding.text",
|
|
136
|
+
f"must be a string containing 0 to {MAX_TEXT_CHARS} characters",
|
|
137
|
+
)
|
|
138
|
+
if not text:
|
|
139
|
+
# A valid catalog entry may have no published column or vocabulary facts. The lexical
|
|
140
|
+
# backend represents that absence as a zero vector; preserve the same no-signal
|
|
141
|
+
# meaning here without starting the model worker merely to encode no text.
|
|
142
|
+
return (0,) * self._descriptor.dimensions
|
|
143
|
+
|
|
144
|
+
connection, process = self._ensure_worker()[:2]
|
|
145
|
+
try:
|
|
146
|
+
connection.send(("encode", text))
|
|
147
|
+
except (BrokenPipeError, EOFError, OSError):
|
|
148
|
+
self._stop_worker()
|
|
149
|
+
raise SourceContractError(
|
|
150
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
151
|
+
"embedding.runtime",
|
|
152
|
+
"the bounded neural worker became unavailable",
|
|
153
|
+
) from None
|
|
154
|
+
try:
|
|
155
|
+
response = _receive_worker_result(
|
|
156
|
+
connection,
|
|
157
|
+
process,
|
|
158
|
+
timeout_seconds=MAX_ENCODE_LATENCY_NS / 1_000_000_000,
|
|
159
|
+
snapshot_root=self._worker[2] if len(self._worker) > 2 else None,
|
|
160
|
+
)
|
|
161
|
+
except SourceContractError:
|
|
162
|
+
self._worker = None
|
|
163
|
+
raise
|
|
164
|
+
if response.get("status") == "error":
|
|
165
|
+
self._stop_worker()
|
|
166
|
+
raise SourceContractError(
|
|
167
|
+
response.get("code", "NEURAL_SESSION_UNAVAILABLE"),
|
|
168
|
+
response.get("path", "embedding.runtime"),
|
|
169
|
+
response.get("detail", "the bounded neural worker failed"),
|
|
170
|
+
)
|
|
171
|
+
if set(response) != {"status", "vector", "peak_rss_bytes"} or response["status"] != "ok":
|
|
172
|
+
self._stop_worker()
|
|
173
|
+
raise SourceContractError(
|
|
174
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
175
|
+
"embedding.runtime",
|
|
176
|
+
"the bounded neural worker returned an invalid response",
|
|
177
|
+
)
|
|
178
|
+
result = tuple(response["vector"])
|
|
179
|
+
if len(result) != DIMENSIONS or any(
|
|
180
|
+
type(value) is not int or not _INT32_MIN <= value <= _INT32_MAX for value in result
|
|
181
|
+
):
|
|
182
|
+
self._stop_worker()
|
|
183
|
+
raise SourceContractError(
|
|
184
|
+
"NEURAL_VECTOR_DIMENSIONS",
|
|
185
|
+
"embedding.vector",
|
|
186
|
+
f"quantized output must contain exactly {DIMENSIONS} signed int32 integers",
|
|
187
|
+
)
|
|
188
|
+
if type(response["peak_rss_bytes"]) is not int or response["peak_rss_bytes"] > (
|
|
189
|
+
MAX_PEAK_RSS_BYTES
|
|
190
|
+
):
|
|
191
|
+
self._stop_worker()
|
|
192
|
+
raise SourceContractError(
|
|
193
|
+
"NEURAL_MEMORY_LIMIT",
|
|
194
|
+
"embedding.runtime",
|
|
195
|
+
"encoding exceeded the pinned peak-memory limit",
|
|
196
|
+
)
|
|
197
|
+
return result
|
|
198
|
+
|
|
199
|
+
def encode_many(self, texts: tuple[str, ...] | list[str]) -> BatchEncodeResult:
|
|
200
|
+
"""Encode a bounded sequence serially through this backend's exact scalar operation.
|
|
201
|
+
|
|
202
|
+
There is no second batch code path here on purpose. Each item goes through ``encode``
|
|
203
|
+
above. Nonempty items use the same bounded request to the same private worker, the same PIN
|
|
204
|
+
and installed-closure checks, the same 256-token truncation, mean pooling, normalization
|
|
205
|
+
and integer quantization, the same deadline, and the same terminate/kill on a worker that
|
|
206
|
+
does not answer. Empty items return the deterministic descriptor-sized zero defined by the
|
|
207
|
+
scalar operation and start no inference. Thus each batch vector is exactly its scalar
|
|
208
|
+
vector on every declared tuple.
|
|
209
|
+
|
|
210
|
+
Provider-scale publication has a measured 34--44 CPU-hour projection. The seam makes
|
|
211
|
+
capability claims only for the tuples authenticated by installed-wheel receipts.
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
return encode_many_bounded(self, texts)
|
|
215
|
+
|
|
216
|
+
def _ensure_worker(self) -> tuple[Any, ...]:
|
|
217
|
+
if self._worker is None:
|
|
218
|
+
self._worker = _start_worker(
|
|
219
|
+
self._model_bytes,
|
|
220
|
+
self._tokenizer_bytes,
|
|
221
|
+
self._runtime_closure_sha256,
|
|
222
|
+
)
|
|
223
|
+
return self._worker
|
|
224
|
+
|
|
225
|
+
def _stop_worker(self) -> None:
|
|
226
|
+
if self._worker is None:
|
|
227
|
+
return
|
|
228
|
+
worker = self._worker
|
|
229
|
+
self._worker = None
|
|
230
|
+
_terminate_worker(*worker)
|
|
231
|
+
|
|
232
|
+
def close(self) -> None:
|
|
233
|
+
"""Stop the private bounded inference worker, if it was started."""
|
|
234
|
+
|
|
235
|
+
self._stop_worker()
|
|
236
|
+
|
|
237
|
+
def __del__(self) -> None:
|
|
238
|
+
try:
|
|
239
|
+
self._stop_worker()
|
|
240
|
+
except Exception:
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def resolve_local_neural_backend(
|
|
245
|
+
model_root: str | os.PathLike[str] | None,
|
|
246
|
+
) -> LocalNeuralEmbeddingBackend:
|
|
247
|
+
"""Capture one explicit sidecar and prepare its authenticated local runtime."""
|
|
248
|
+
|
|
249
|
+
path = _explicit_absolute_root(model_root)
|
|
250
|
+
pin, members = _capture_sidecar(path)
|
|
251
|
+
tuple_id = _runtime_tuple()
|
|
252
|
+
supported = pin.get("supported_tuples")
|
|
253
|
+
if (
|
|
254
|
+
tuple_id not in SUPPORTED_TUPLES
|
|
255
|
+
or supported != sorted(SUPPORTED_TUPLES)
|
|
256
|
+
or tuple_id not in supported
|
|
257
|
+
):
|
|
258
|
+
raise SourceContractError(
|
|
259
|
+
"NEURAL_TUPLE_UNAVAILABLE",
|
|
260
|
+
"embedding.runtime_tuple",
|
|
261
|
+
f"runtime tuple {tuple_id!r} is not supported by the exact PIN",
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
runtime_closures = pin.get("runtime_closures")
|
|
265
|
+
if not isinstance(runtime_closures, dict) or set(runtime_closures) != set(supported):
|
|
266
|
+
raise SourceContractError(
|
|
267
|
+
"NEURAL_RUNTIME_CLOSURE_MISMATCH",
|
|
268
|
+
"embedding.runtime",
|
|
269
|
+
"the supported tuple registry has no exact installed-runtime closure",
|
|
270
|
+
)
|
|
271
|
+
runtime_closure_sha256 = runtime_closures.get(tuple_id)
|
|
272
|
+
if not _is_sha256(runtime_closure_sha256):
|
|
273
|
+
raise SourceContractError(
|
|
274
|
+
"NEURAL_RUNTIME_CLOSURE_MISMATCH",
|
|
275
|
+
"embedding.runtime",
|
|
276
|
+
"the runtime closure coordinate for this tuple is invalid",
|
|
277
|
+
)
|
|
278
|
+
artifacts = tuple(sorted((item["path"], item["sha256"]) for item in pin["artifacts"]))
|
|
279
|
+
descriptor = PinnedLocalBackendDescriptor(
|
|
280
|
+
backend_id=BACKEND_ID,
|
|
281
|
+
backend_version=BACKEND_VERSION,
|
|
282
|
+
dimensions=DIMENSIONS,
|
|
283
|
+
quantization=QUANTIZATION,
|
|
284
|
+
query_safe=False,
|
|
285
|
+
model_root=str(path),
|
|
286
|
+
pin_sha256=PIN_SHA256,
|
|
287
|
+
coordinate_sha256=COORDINATE_SHA256,
|
|
288
|
+
runtime_tuple=tuple_id,
|
|
289
|
+
runtime_closure_sha256=runtime_closure_sha256,
|
|
290
|
+
artifact_sha256s=artifacts,
|
|
291
|
+
)
|
|
292
|
+
backend = LocalNeuralEmbeddingBackend(
|
|
293
|
+
descriptor,
|
|
294
|
+
model_bytes=members["model.int8.onnx"],
|
|
295
|
+
tokenizer_bytes=members["tokenizer.json"],
|
|
296
|
+
runtime_closure_sha256=runtime_closure_sha256,
|
|
297
|
+
)
|
|
298
|
+
backend._ensure_worker()
|
|
299
|
+
return backend
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _explicit_absolute_root(model_root: str | os.PathLike[str] | None) -> Path:
|
|
303
|
+
if model_root is None or isinstance(model_root, bytes):
|
|
304
|
+
raise SourceContractError(
|
|
305
|
+
"NEURAL_MODEL_ROOT_REQUIRED",
|
|
306
|
+
"embedding.model_root",
|
|
307
|
+
"the caller must supply one explicit sidecar root",
|
|
308
|
+
)
|
|
309
|
+
try:
|
|
310
|
+
path = Path(os.fspath(model_root))
|
|
311
|
+
except TypeError:
|
|
312
|
+
raise SourceContractError(
|
|
313
|
+
"NEURAL_MODEL_ROOT_REQUIRED",
|
|
314
|
+
"embedding.model_root",
|
|
315
|
+
"the caller must supply one explicit sidecar root",
|
|
316
|
+
) from None
|
|
317
|
+
if not path.is_absolute():
|
|
318
|
+
raise SourceContractError(
|
|
319
|
+
"NEURAL_MODEL_ROOT_ABSOLUTE",
|
|
320
|
+
"embedding.model_root",
|
|
321
|
+
"the caller-supplied sidecar root must be absolute",
|
|
322
|
+
)
|
|
323
|
+
return path
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _capture_sidecar(root: Path) -> tuple[dict[str, Any], dict[str, bytes]]:
|
|
327
|
+
try:
|
|
328
|
+
initial = os.lstat(root)
|
|
329
|
+
except OSError:
|
|
330
|
+
raise SourceContractError(
|
|
331
|
+
"NEURAL_MODEL_ROOT_UNAVAILABLE",
|
|
332
|
+
"embedding.model_root",
|
|
333
|
+
"the explicit sidecar root is unavailable",
|
|
334
|
+
) from None
|
|
335
|
+
if stat.S_ISLNK(initial.st_mode):
|
|
336
|
+
raise SourceContractError(
|
|
337
|
+
"NEURAL_MODEL_ROOT_LINK",
|
|
338
|
+
"embedding.model_root",
|
|
339
|
+
"the explicit sidecar root may not be a symbolic link",
|
|
340
|
+
)
|
|
341
|
+
if not stat.S_ISDIR(initial.st_mode):
|
|
342
|
+
raise SourceContractError(
|
|
343
|
+
"NEURAL_MODEL_ROOT_UNAVAILABLE",
|
|
344
|
+
"embedding.model_root",
|
|
345
|
+
"the explicit sidecar root must be a directory",
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
|
|
349
|
+
try:
|
|
350
|
+
root_fd = os.open(root, flags)
|
|
351
|
+
except OSError:
|
|
352
|
+
raise SourceContractError(
|
|
353
|
+
"NEURAL_MODEL_ROOT_UNAVAILABLE",
|
|
354
|
+
"embedding.model_root",
|
|
355
|
+
"the explicit sidecar root could not be descriptor-captured",
|
|
356
|
+
) from None
|
|
357
|
+
try:
|
|
358
|
+
captured = os.fstat(root_fd)
|
|
359
|
+
if _identity(initial) != _identity(captured):
|
|
360
|
+
_root_race()
|
|
361
|
+
pin_bytes = _read_member(root_fd, PIN_NAME, MAX_PIN_BYTES)
|
|
362
|
+
if hashlib.sha256(pin_bytes).hexdigest() != PIN_SHA256:
|
|
363
|
+
raise SourceContractError(
|
|
364
|
+
"NEURAL_PIN_MISMATCH",
|
|
365
|
+
"embedding.model_root/PIN.json",
|
|
366
|
+
"PIN.json bytes differ from the selected coordinate",
|
|
367
|
+
)
|
|
368
|
+
pin = _parse_exact_pin(pin_bytes)
|
|
369
|
+
expected = {item["path"]: item["sha256"] for item in pin["artifacts"]}
|
|
370
|
+
if set(os.listdir(root_fd)) != {PIN_NAME, *expected}:
|
|
371
|
+
raise SourceContractError(
|
|
372
|
+
"NEURAL_MODEL_CLOSURE",
|
|
373
|
+
"embedding.model_root",
|
|
374
|
+
"the sidecar contains an absent or unpinned member",
|
|
375
|
+
)
|
|
376
|
+
members: dict[str, bytes] = {}
|
|
377
|
+
total = 0
|
|
378
|
+
for name in sorted(expected):
|
|
379
|
+
value = _read_member(root_fd, name, MAX_MODEL_BYTES)
|
|
380
|
+
total += len(value)
|
|
381
|
+
if total > MAX_MODEL_BYTES:
|
|
382
|
+
raise SourceContractError(
|
|
383
|
+
"NEURAL_MODEL_BYTES",
|
|
384
|
+
"embedding.model_root",
|
|
385
|
+
"the sidecar exceeds its pinned byte limit",
|
|
386
|
+
)
|
|
387
|
+
if hashlib.sha256(value).hexdigest() != expected[name]:
|
|
388
|
+
raise SourceContractError(
|
|
389
|
+
"NEURAL_ARTIFACT_MISMATCH",
|
|
390
|
+
f"embedding.model_root/{name}",
|
|
391
|
+
"artifact bytes differ from PIN.json",
|
|
392
|
+
)
|
|
393
|
+
members[name] = value
|
|
394
|
+
final_captured = os.fstat(root_fd)
|
|
395
|
+
try:
|
|
396
|
+
final = os.lstat(root)
|
|
397
|
+
except OSError:
|
|
398
|
+
_root_race()
|
|
399
|
+
if (
|
|
400
|
+
_identity(initial) != _identity(final)
|
|
401
|
+
or _identity(captured) != _identity(final_captured)
|
|
402
|
+
or _identity(captured) != _identity(final)
|
|
403
|
+
or captured.st_mtime_ns != final_captured.st_mtime_ns
|
|
404
|
+
or captured.st_ctime_ns != final_captured.st_ctime_ns
|
|
405
|
+
or set(os.listdir(root_fd)) != {PIN_NAME, *expected}
|
|
406
|
+
):
|
|
407
|
+
_root_race()
|
|
408
|
+
return pin, members
|
|
409
|
+
finally:
|
|
410
|
+
os.close(root_fd)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _parse_exact_pin(value: bytes) -> dict[str, Any]:
|
|
414
|
+
try:
|
|
415
|
+
pin = parse_json(value)
|
|
416
|
+
except ValueError:
|
|
417
|
+
raise SourceContractError(
|
|
418
|
+
"NEURAL_PIN_MISMATCH",
|
|
419
|
+
"embedding.model_root/PIN.json",
|
|
420
|
+
"PIN.json is not strict JSON",
|
|
421
|
+
) from None
|
|
422
|
+
if not isinstance(pin, dict) or pin.get("schema_version") != PIN_SCHEMA_VERSION:
|
|
423
|
+
raise SourceContractError(
|
|
424
|
+
"NEURAL_PIN_MISMATCH",
|
|
425
|
+
"embedding.model_root/PIN.json",
|
|
426
|
+
"PIN.json schema differs from the selected coordinate",
|
|
427
|
+
)
|
|
428
|
+
if pin.get("runtime") != RUNTIME_VERSIONS:
|
|
429
|
+
raise SourceContractError(
|
|
430
|
+
"NEURAL_PIN_MISMATCH",
|
|
431
|
+
"embedding.model_root/PIN.json",
|
|
432
|
+
"runtime pins differ from the selected coordinate",
|
|
433
|
+
)
|
|
434
|
+
if pin.get("tuple_candidates") != sorted(SUPPORTED_TUPLES):
|
|
435
|
+
raise SourceContractError(
|
|
436
|
+
"NEURAL_PIN_MISMATCH",
|
|
437
|
+
"embedding.model_root/PIN.json",
|
|
438
|
+
"runtime tuple candidates differ from the exact coordinate",
|
|
439
|
+
)
|
|
440
|
+
supported = pin.get("supported_tuples")
|
|
441
|
+
runtime_closures = pin.get("runtime_closures")
|
|
442
|
+
if (
|
|
443
|
+
not isinstance(supported, list)
|
|
444
|
+
or supported != sorted(supported)
|
|
445
|
+
or not set(supported).issubset(SUPPORTED_TUPLES)
|
|
446
|
+
or not isinstance(runtime_closures, dict)
|
|
447
|
+
or set(runtime_closures) != set(supported)
|
|
448
|
+
or any(not _is_sha256(digest) for digest in runtime_closures.values())
|
|
449
|
+
):
|
|
450
|
+
raise SourceContractError(
|
|
451
|
+
"NEURAL_PIN_MISMATCH",
|
|
452
|
+
"embedding.model_root/PIN.json",
|
|
453
|
+
"supported tuples and installed-runtime closures are not an exact registry",
|
|
454
|
+
)
|
|
455
|
+
coordinate = pin.get("coordinate")
|
|
456
|
+
if not isinstance(coordinate, dict) or (
|
|
457
|
+
hashlib.sha256(canonical_json_bytes(coordinate)).hexdigest() != COORDINATE_SHA256
|
|
458
|
+
):
|
|
459
|
+
raise SourceContractError(
|
|
460
|
+
"NEURAL_PIN_MISMATCH",
|
|
461
|
+
"embedding.model_root/PIN.json",
|
|
462
|
+
"model coordinate differs from the selected coordinate",
|
|
463
|
+
)
|
|
464
|
+
if coordinate.get("backend_id") != BACKEND_ID or coordinate.get("backend_version") != (
|
|
465
|
+
BACKEND_VERSION
|
|
466
|
+
):
|
|
467
|
+
raise SourceContractError(
|
|
468
|
+
"NEURAL_PIN_MISMATCH",
|
|
469
|
+
"embedding.model_root/PIN.json",
|
|
470
|
+
"backend identity differs from the selected coordinate",
|
|
471
|
+
)
|
|
472
|
+
if coordinate.get("dimensions") != DIMENSIONS:
|
|
473
|
+
raise SourceContractError(
|
|
474
|
+
"NEURAL_PIN_MISMATCH",
|
|
475
|
+
"embedding.model_root/PIN.json",
|
|
476
|
+
"embedding dimensions differ from the selected coordinate",
|
|
477
|
+
)
|
|
478
|
+
artifacts = pin.get("artifacts")
|
|
479
|
+
if not isinstance(artifacts, list) or not artifacts:
|
|
480
|
+
raise SourceContractError(
|
|
481
|
+
"NEURAL_PIN_MISMATCH",
|
|
482
|
+
"embedding.model_root/PIN.json",
|
|
483
|
+
"the exact artifact coordinate is absent",
|
|
484
|
+
)
|
|
485
|
+
return pin
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _read_member(root_fd: int, name: str, maximum: int) -> bytes:
|
|
489
|
+
if not name or "/" in name or "\\" in name or name in {".", ".."}:
|
|
490
|
+
raise SourceContractError(
|
|
491
|
+
"NEURAL_ARTIFACT_UNSAFE",
|
|
492
|
+
f"embedding.model_root/{name}",
|
|
493
|
+
"artifact name is unsafe",
|
|
494
|
+
)
|
|
495
|
+
try:
|
|
496
|
+
before = os.stat(name, dir_fd=root_fd, follow_symlinks=False)
|
|
497
|
+
except OSError:
|
|
498
|
+
raise SourceContractError(
|
|
499
|
+
"NEURAL_ARTIFACT_UNSAFE",
|
|
500
|
+
f"embedding.model_root/{name}",
|
|
501
|
+
"artifact is absent or unreadable",
|
|
502
|
+
) from None
|
|
503
|
+
if not stat.S_ISREG(before.st_mode) or not 0 < before.st_size <= maximum:
|
|
504
|
+
raise SourceContractError(
|
|
505
|
+
"NEURAL_ARTIFACT_UNSAFE",
|
|
506
|
+
f"embedding.model_root/{name}",
|
|
507
|
+
"artifact must be a bounded regular file",
|
|
508
|
+
)
|
|
509
|
+
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
|
|
510
|
+
try:
|
|
511
|
+
descriptor = os.open(name, flags, dir_fd=root_fd)
|
|
512
|
+
except OSError:
|
|
513
|
+
raise SourceContractError(
|
|
514
|
+
"NEURAL_ARTIFACT_UNSAFE",
|
|
515
|
+
f"embedding.model_root/{name}",
|
|
516
|
+
"artifact could not be descriptor-captured without following links",
|
|
517
|
+
) from None
|
|
518
|
+
try:
|
|
519
|
+
captured = os.fstat(descriptor)
|
|
520
|
+
if _identity(before) != _identity(captured) or before.st_size != captured.st_size:
|
|
521
|
+
raise SourceContractError(
|
|
522
|
+
"NEURAL_ARTIFACT_RACE",
|
|
523
|
+
f"embedding.model_root/{name}",
|
|
524
|
+
"artifact changed during descriptor capture",
|
|
525
|
+
)
|
|
526
|
+
chunks: list[bytes] = []
|
|
527
|
+
remaining = maximum + 1
|
|
528
|
+
while remaining:
|
|
529
|
+
chunk = os.read(descriptor, min(1024 * 1024, remaining))
|
|
530
|
+
if not chunk:
|
|
531
|
+
break
|
|
532
|
+
chunks.append(chunk)
|
|
533
|
+
remaining -= len(chunk)
|
|
534
|
+
value = b"".join(chunks)
|
|
535
|
+
after = os.fstat(descriptor)
|
|
536
|
+
if (
|
|
537
|
+
_identity(captured) != _identity(after)
|
|
538
|
+
or captured.st_size != after.st_size
|
|
539
|
+
or len(value) != captured.st_size
|
|
540
|
+
or len(value) > maximum
|
|
541
|
+
):
|
|
542
|
+
raise SourceContractError(
|
|
543
|
+
"NEURAL_ARTIFACT_RACE",
|
|
544
|
+
f"embedding.model_root/{name}",
|
|
545
|
+
"artifact changed while it was read",
|
|
546
|
+
)
|
|
547
|
+
return value
|
|
548
|
+
finally:
|
|
549
|
+
os.close(descriptor)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _identity(value: os.stat_result) -> tuple[int, int]:
|
|
553
|
+
return value.st_dev, value.st_ino
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _root_race() -> None:
|
|
557
|
+
raise SourceContractError(
|
|
558
|
+
"NEURAL_MODEL_ROOT_RACE",
|
|
559
|
+
"embedding.model_root",
|
|
560
|
+
"the caller-supplied sidecar root changed during descriptor capture",
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _runtime_tuple() -> str:
|
|
565
|
+
machine = {"aarch64": "arm64", "amd64": "x86_64"}.get(
|
|
566
|
+
platform.machine().lower(), platform.machine().lower()
|
|
567
|
+
)
|
|
568
|
+
implementation = platform.python_implementation().lower()
|
|
569
|
+
version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
|
|
570
|
+
if sys.platform == "darwin":
|
|
571
|
+
macos_release = platform.mac_ver()[0].split(".", 1)[0] or "unknown"
|
|
572
|
+
os_coordinate = f"macos-{macos_release}"
|
|
573
|
+
elif sys.platform == "linux":
|
|
574
|
+
try:
|
|
575
|
+
release = platform.freedesktop_os_release()
|
|
576
|
+
except OSError:
|
|
577
|
+
release = {}
|
|
578
|
+
distribution = release.get("ID", "linux").lower()
|
|
579
|
+
os_version = release.get("VERSION_ID", "unknown").lower()
|
|
580
|
+
os_coordinate = f"{distribution}-{os_version}"
|
|
581
|
+
else:
|
|
582
|
+
os_coordinate = sys.platform.lower()
|
|
583
|
+
return f"{os_coordinate}-{machine}-{implementation}-{version}"
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _is_sha256(value: object) -> bool:
|
|
587
|
+
if not isinstance(value, str) or len(value) != 64:
|
|
588
|
+
return False
|
|
589
|
+
try:
|
|
590
|
+
int(value, 16)
|
|
591
|
+
except ValueError:
|
|
592
|
+
return False
|
|
593
|
+
return value == value.lower()
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _installed_runtime_closure_with_distributions() -> tuple[dict[str, Any], dict[str, Any]]:
|
|
597
|
+
distributions: dict[str, list[Any]] = {}
|
|
598
|
+
for distribution in metadata.distributions():
|
|
599
|
+
name = distribution.metadata.get("Name")
|
|
600
|
+
if isinstance(name, str):
|
|
601
|
+
distributions.setdefault(canonicalize_name(name), []).append(distribution)
|
|
602
|
+
|
|
603
|
+
pending: deque[tuple[str, str]] = deque(
|
|
604
|
+
(canonicalize_name(name), "") for name in _RUNTIME_ROOT_DISTRIBUTIONS
|
|
605
|
+
)
|
|
606
|
+
seen: set[str] = set()
|
|
607
|
+
selected: dict[str, Any] = {}
|
|
608
|
+
records: list[dict[str, str]] = []
|
|
609
|
+
while pending:
|
|
610
|
+
name, selected_extra = pending.popleft()
|
|
611
|
+
if name in seen:
|
|
612
|
+
continue
|
|
613
|
+
candidates = distributions.get(name, [])
|
|
614
|
+
if not candidates:
|
|
615
|
+
raise SourceContractError(
|
|
616
|
+
"NEURAL_RUNTIME_UNAVAILABLE",
|
|
617
|
+
"embedding.runtime",
|
|
618
|
+
f"required runtime distribution {name} is not installed",
|
|
619
|
+
)
|
|
620
|
+
if len(candidates) != 1:
|
|
621
|
+
raise _runtime_closure_refused(
|
|
622
|
+
f"required runtime distribution {name} is installed more than once"
|
|
623
|
+
)
|
|
624
|
+
distribution = candidates[0]
|
|
625
|
+
selected[name] = distribution
|
|
626
|
+
record = distribution.read_text("RECORD")
|
|
627
|
+
if record is None:
|
|
628
|
+
raise SourceContractError(
|
|
629
|
+
"NEURAL_RUNTIME_CLOSURE_MISMATCH",
|
|
630
|
+
"embedding.runtime",
|
|
631
|
+
f"required runtime distribution {name} has no installed RECORD",
|
|
632
|
+
)
|
|
633
|
+
records.append(
|
|
634
|
+
{
|
|
635
|
+
"name": name,
|
|
636
|
+
"record_sha256": _portable_record_sha256(distribution, record),
|
|
637
|
+
"version": distribution.version,
|
|
638
|
+
}
|
|
639
|
+
)
|
|
640
|
+
seen.add(name)
|
|
641
|
+
for raw_requirement in distribution.requires or ():
|
|
642
|
+
requirement = Requirement(raw_requirement)
|
|
643
|
+
if requirement.marker is not None and not requirement.marker.evaluate(
|
|
644
|
+
{"extra": selected_extra}
|
|
645
|
+
):
|
|
646
|
+
continue
|
|
647
|
+
pending.append((canonicalize_name(requirement.name), ""))
|
|
648
|
+
return (
|
|
649
|
+
{
|
|
650
|
+
"distributions": sorted(records, key=lambda item: item["name"]),
|
|
651
|
+
"roots": list(_RUNTIME_ROOT_DISTRIBUTIONS),
|
|
652
|
+
"schema_version": "local-search-neural-installed-closure.v2",
|
|
653
|
+
},
|
|
654
|
+
selected,
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _installed_runtime_closure() -> dict[str, Any]:
|
|
659
|
+
closure, _distributions = _installed_runtime_closure_with_distributions()
|
|
660
|
+
return closure
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
_INSTALLER_OWNED_RECORD_MEMBERS = frozenset({"INSTALLER", "REQUESTED", "direct_url.json", "RECORD"})
|
|
664
|
+
_MAX_RUNTIME_MEMBER_BYTES = 512 * 1024 * 1024
|
|
665
|
+
_MAX_RUNTIME_CLOSURE_BYTES = 2 * 1024 * 1024 * 1024
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
class _SnapshotDistribution:
|
|
669
|
+
def __init__(self, source: Any, root: Path, record: str) -> None:
|
|
670
|
+
self.metadata = source.metadata
|
|
671
|
+
self.version = source.version
|
|
672
|
+
self.requires = source.requires
|
|
673
|
+
self.files = source.files
|
|
674
|
+
self._root = root
|
|
675
|
+
self._record = record
|
|
676
|
+
|
|
677
|
+
def locate_file(self, _path: str) -> Path:
|
|
678
|
+
return self._root
|
|
679
|
+
|
|
680
|
+
def read_text(self, name: str) -> str | None:
|
|
681
|
+
return self._record if name == "RECORD" else None
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def _runtime_closure_refused(detail: str) -> SourceContractError:
|
|
685
|
+
return SourceContractError("NEURAL_RUNTIME_CLOSURE_MISMATCH", "embedding.runtime", detail)
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _record_digest(value: str) -> bytes:
|
|
689
|
+
if not value.startswith("sha256="):
|
|
690
|
+
raise ValueError
|
|
691
|
+
encoded = value.removeprefix("sha256=")
|
|
692
|
+
if len(encoded) != 43 or any(
|
|
693
|
+
character not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
|
694
|
+
for character in encoded
|
|
695
|
+
):
|
|
696
|
+
raise ValueError
|
|
697
|
+
try:
|
|
698
|
+
decoded = base64.b64decode(encoded + "=", altchars=b"-_", validate=True)
|
|
699
|
+
except (binascii.Error, ValueError):
|
|
700
|
+
raise ValueError from None
|
|
701
|
+
if len(decoded) != hashlib.sha256().digest_size:
|
|
702
|
+
raise ValueError
|
|
703
|
+
return decoded
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _read_runtime_member(
|
|
707
|
+
root_fd: int, parts: tuple[str, ...], expected_size: int, *, capture: bool = False
|
|
708
|
+
) -> tuple[bytes, tuple[int, int, int, int], bytes | None]:
|
|
709
|
+
if expected_size > _MAX_RUNTIME_MEMBER_BYTES:
|
|
710
|
+
raise _runtime_closure_refused("a runtime member exceeds the closure byte limit")
|
|
711
|
+
directory_fd = os.dup(root_fd)
|
|
712
|
+
member_fd: int | None = None
|
|
713
|
+
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
|
|
714
|
+
try:
|
|
715
|
+
for part in parts[:-1]:
|
|
716
|
+
next_fd = os.open(part, flags | getattr(os, "O_DIRECTORY", 0), dir_fd=directory_fd)
|
|
717
|
+
os.close(directory_fd)
|
|
718
|
+
directory_fd = next_fd
|
|
719
|
+
member_fd = os.open(parts[-1], flags, dir_fd=directory_fd)
|
|
720
|
+
opened = os.fstat(member_fd)
|
|
721
|
+
if not stat.S_ISREG(opened.st_mode) or opened.st_size != expected_size:
|
|
722
|
+
raise _runtime_closure_refused("a runtime member differs from its installed RECORD")
|
|
723
|
+
digest = hashlib.sha256()
|
|
724
|
+
captured: list[bytes] = []
|
|
725
|
+
total = 0
|
|
726
|
+
while True:
|
|
727
|
+
chunk = os.read(member_fd, min(1024 * 1024, expected_size - total + 1))
|
|
728
|
+
if not chunk:
|
|
729
|
+
break
|
|
730
|
+
total += len(chunk)
|
|
731
|
+
if total > expected_size:
|
|
732
|
+
raise _runtime_closure_refused("a runtime member differs from its installed RECORD")
|
|
733
|
+
digest.update(chunk)
|
|
734
|
+
if capture:
|
|
735
|
+
captured.append(chunk)
|
|
736
|
+
closed = os.fstat(member_fd)
|
|
737
|
+
if total != expected_size or (
|
|
738
|
+
opened.st_dev,
|
|
739
|
+
opened.st_ino,
|
|
740
|
+
opened.st_size,
|
|
741
|
+
opened.st_mtime_ns,
|
|
742
|
+
) != (closed.st_dev, closed.st_ino, closed.st_size, closed.st_mtime_ns):
|
|
743
|
+
raise _runtime_closure_refused("a runtime member changed while it was authenticated")
|
|
744
|
+
fingerprint = (
|
|
745
|
+
closed.st_dev,
|
|
746
|
+
closed.st_ino,
|
|
747
|
+
closed.st_size,
|
|
748
|
+
closed.st_mtime_ns,
|
|
749
|
+
)
|
|
750
|
+
return digest.digest(), fingerprint, b"".join(captured) if capture else None
|
|
751
|
+
except OSError:
|
|
752
|
+
raise _runtime_closure_refused(
|
|
753
|
+
"a runtime member could not be opened without links"
|
|
754
|
+
) from None
|
|
755
|
+
finally:
|
|
756
|
+
if member_fd is not None:
|
|
757
|
+
os.close(member_fd)
|
|
758
|
+
os.close(directory_fd)
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _portable_record_binding(
|
|
762
|
+
distribution: Any, record: str
|
|
763
|
+
) -> tuple[str, tuple[tuple[str, int, int, int, int], ...]]:
|
|
764
|
+
"""Bind installed wheel payloads without binding the virtual-environment path.
|
|
765
|
+
|
|
766
|
+
Installers rewrite console-script shebangs with the destination interpreter and add a small
|
|
767
|
+
set of installer-owned metadata files. Neither can affect neural inference, while hashing them
|
|
768
|
+
makes the same wheel closure differ solely because it was installed at another absolute path.
|
|
769
|
+
All wheel-owned package and metadata rows remain bound exactly as installed.
|
|
770
|
+
"""
|
|
771
|
+
|
|
772
|
+
parsed_rows: list[tuple[str, str, str]] = []
|
|
773
|
+
try:
|
|
774
|
+
parsed = csv.reader(io.StringIO(record, newline=""))
|
|
775
|
+
for row in parsed:
|
|
776
|
+
if len(row) != 3:
|
|
777
|
+
raise ValueError
|
|
778
|
+
parsed_rows.append((row[0], row[1], row[2]))
|
|
779
|
+
except (csv.Error, ValueError):
|
|
780
|
+
raise _runtime_closure_refused(
|
|
781
|
+
"a required runtime distribution has an invalid RECORD"
|
|
782
|
+
) from None
|
|
783
|
+
|
|
784
|
+
record_rows = [
|
|
785
|
+
path
|
|
786
|
+
for path, digest, size in parsed_rows
|
|
787
|
+
if path.endswith(".dist-info/RECORD") and digest == size == ""
|
|
788
|
+
]
|
|
789
|
+
if len(record_rows) != 1:
|
|
790
|
+
raise _runtime_closure_refused("a required runtime distribution has an invalid RECORD row")
|
|
791
|
+
dist_info = record_rows[0].rsplit("/", 1)[0]
|
|
792
|
+
rows: list[dict[str, str]] = []
|
|
793
|
+
fingerprints: list[tuple[str, int, int, int, int]] = []
|
|
794
|
+
seen_paths: set[str] = set()
|
|
795
|
+
total_bytes = 0
|
|
796
|
+
root = Path(distribution.locate_file(""))
|
|
797
|
+
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
|
|
798
|
+
try:
|
|
799
|
+
root_fd = os.open(root, flags)
|
|
800
|
+
except OSError:
|
|
801
|
+
raise _runtime_closure_refused(
|
|
802
|
+
"the runtime installation root could not be opened"
|
|
803
|
+
) from None
|
|
804
|
+
try:
|
|
805
|
+
for path, digest, size in parsed_rows:
|
|
806
|
+
if not path or path in seen_paths or "\\" in path or "\x00" in path:
|
|
807
|
+
raise _runtime_closure_refused("a required runtime RECORD path is invalid")
|
|
808
|
+
seen_paths.add(path)
|
|
809
|
+
pure = PurePosixPath(path)
|
|
810
|
+
parts = pure.parts
|
|
811
|
+
is_script = (
|
|
812
|
+
len(parts) == 5
|
|
813
|
+
and parts[:4] == ("..", "..", "..", "bin")
|
|
814
|
+
and parts[4] not in {"", ".", ".."}
|
|
815
|
+
and "/" not in parts[4]
|
|
816
|
+
)
|
|
817
|
+
if is_script:
|
|
818
|
+
try:
|
|
819
|
+
_record_digest(digest)
|
|
820
|
+
if not size.isdecimal():
|
|
821
|
+
raise ValueError
|
|
822
|
+
except ValueError:
|
|
823
|
+
raise _runtime_closure_refused(
|
|
824
|
+
"a generated runtime script row is invalid"
|
|
825
|
+
) from None
|
|
826
|
+
continue
|
|
827
|
+
if pure.is_absolute() or any(part in {"", ".", ".."} for part in parts):
|
|
828
|
+
raise _runtime_closure_refused("a required runtime RECORD path is unsafe")
|
|
829
|
+
installer_owned = (
|
|
830
|
+
len(parts) >= 2
|
|
831
|
+
and str(pure.parent) == dist_info
|
|
832
|
+
and pure.name in _INSTALLER_OWNED_RECORD_MEMBERS
|
|
833
|
+
)
|
|
834
|
+
if pure.name == "RECORD" and str(pure.parent) == dist_info:
|
|
835
|
+
if digest or size:
|
|
836
|
+
raise _runtime_closure_refused("the installed RECORD self-row is invalid")
|
|
837
|
+
continue
|
|
838
|
+
try:
|
|
839
|
+
expected_digest = _record_digest(digest)
|
|
840
|
+
if not size.isdecimal():
|
|
841
|
+
raise ValueError
|
|
842
|
+
expected_size = int(size)
|
|
843
|
+
except ValueError:
|
|
844
|
+
raise _runtime_closure_refused(
|
|
845
|
+
"a required runtime RECORD digest or size is invalid"
|
|
846
|
+
) from None
|
|
847
|
+
if installer_owned:
|
|
848
|
+
continue
|
|
849
|
+
total_bytes += expected_size
|
|
850
|
+
if total_bytes > _MAX_RUNTIME_CLOSURE_BYTES:
|
|
851
|
+
raise _runtime_closure_refused("the runtime closure exceeds its byte limit")
|
|
852
|
+
observed_digest, fingerprint, _captured = _read_runtime_member(
|
|
853
|
+
root_fd, tuple(parts), expected_size
|
|
854
|
+
)
|
|
855
|
+
if observed_digest != expected_digest:
|
|
856
|
+
raise _runtime_closure_refused("a runtime member differs from its installed RECORD")
|
|
857
|
+
rows.append({"path": path, "sha256": digest, "size": size})
|
|
858
|
+
fingerprints.append((path, *fingerprint))
|
|
859
|
+
finally:
|
|
860
|
+
os.close(root_fd)
|
|
861
|
+
if not rows:
|
|
862
|
+
raise _runtime_closure_refused("a required runtime distribution has no wheel-owned members")
|
|
863
|
+
rows.sort(key=lambda item: item["path"])
|
|
864
|
+
fingerprints.sort(key=lambda item: item[0])
|
|
865
|
+
return hashlib.sha256(canonical_json_bytes(rows)).hexdigest(), tuple(fingerprints)
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
def _portable_record_sha256(distribution: Any, record: str) -> str:
|
|
869
|
+
digest, _fingerprints = _portable_record_binding(distribution, record)
|
|
870
|
+
return digest
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def _snapshot_runtime(
|
|
874
|
+
distributions: dict[str, Any],
|
|
875
|
+
root: Path | None = None,
|
|
876
|
+
) -> tuple[Path, dict[str, _SnapshotDistribution]]:
|
|
877
|
+
"""Copy authenticated runtime members into one private import root."""
|
|
878
|
+
|
|
879
|
+
root = Path(tempfile.mkdtemp(prefix="mostlyright-neural-runtime-")) if root is None else root
|
|
880
|
+
snapshots: dict[str, _SnapshotDistribution] = {}
|
|
881
|
+
try:
|
|
882
|
+
for name, distribution in distributions.items():
|
|
883
|
+
record = distribution.read_text("RECORD")
|
|
884
|
+
if record is None:
|
|
885
|
+
raise _runtime_closure_refused(f"required runtime distribution {name} lost RECORD")
|
|
886
|
+
_portable_record_binding(distribution, record)
|
|
887
|
+
source_root = Path(distribution.locate_file(""))
|
|
888
|
+
source_fd = os.open(
|
|
889
|
+
source_root,
|
|
890
|
+
os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0),
|
|
891
|
+
)
|
|
892
|
+
try:
|
|
893
|
+
for path, digest, size in csv.reader(io.StringIO(record, newline="")):
|
|
894
|
+
pure = PurePosixPath(path)
|
|
895
|
+
parts = pure.parts
|
|
896
|
+
if (
|
|
897
|
+
not path
|
|
898
|
+
or pure.is_absolute()
|
|
899
|
+
or any(part in {"", ".", ".."} for part in parts)
|
|
900
|
+
):
|
|
901
|
+
continue
|
|
902
|
+
if ".dist-info/" in path and pure.name in _INSTALLER_OWNED_RECORD_MEMBERS:
|
|
903
|
+
continue
|
|
904
|
+
if not digest or not size:
|
|
905
|
+
continue
|
|
906
|
+
expected_size = int(size)
|
|
907
|
+
expected_digest = _record_digest(digest)
|
|
908
|
+
observed, _state, payload = _read_runtime_member(
|
|
909
|
+
source_fd, tuple(parts), expected_size, capture=True
|
|
910
|
+
)
|
|
911
|
+
if observed != expected_digest or payload is None:
|
|
912
|
+
raise _runtime_closure_refused(
|
|
913
|
+
"a runtime member changed while its private snapshot was created"
|
|
914
|
+
)
|
|
915
|
+
destination = root.joinpath(*parts)
|
|
916
|
+
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
917
|
+
descriptor = os.open(
|
|
918
|
+
destination,
|
|
919
|
+
os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0),
|
|
920
|
+
0o500 if destination.suffix in {".so", ".dylib", ".dll", ".pyd"} else 0o400,
|
|
921
|
+
)
|
|
922
|
+
try:
|
|
923
|
+
view = memoryview(payload)
|
|
924
|
+
while view:
|
|
925
|
+
written = os.write(descriptor, view)
|
|
926
|
+
view = view[written:]
|
|
927
|
+
finally:
|
|
928
|
+
os.close(descriptor)
|
|
929
|
+
finally:
|
|
930
|
+
os.close(source_fd)
|
|
931
|
+
snapshots[name] = _SnapshotDistribution(distribution, root, record)
|
|
932
|
+
return root, snapshots
|
|
933
|
+
except BaseException:
|
|
934
|
+
shutil.rmtree(root, ignore_errors=True)
|
|
935
|
+
raise
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def _installed_runtime_closure_sha256() -> str:
|
|
939
|
+
return hashlib.sha256(canonical_json_bytes(_installed_runtime_closure())).hexdigest()
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
def _runtime_installation_state(
|
|
943
|
+
distributions: dict[str, Any],
|
|
944
|
+
) -> tuple[tuple[str, str, tuple[tuple[str, int, int, int, int], ...]], ...]:
|
|
945
|
+
state = []
|
|
946
|
+
for name, distribution in sorted(distributions.items()):
|
|
947
|
+
record = distribution.read_text("RECORD")
|
|
948
|
+
if record is None:
|
|
949
|
+
raise _runtime_closure_refused(
|
|
950
|
+
f"required runtime distribution {name} has no installed RECORD"
|
|
951
|
+
)
|
|
952
|
+
digest, fingerprints = _portable_record_binding(distribution, record)
|
|
953
|
+
state.append((name, digest, fingerprints))
|
|
954
|
+
return tuple(state)
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
def _require_runtime_closure(expected_sha256: str) -> dict[str, Any]:
|
|
958
|
+
closure, distributions = _installed_runtime_closure_with_distributions()
|
|
959
|
+
observed_sha256 = hashlib.sha256(canonical_json_bytes(closure)).hexdigest()
|
|
960
|
+
if not _is_sha256(expected_sha256) or observed_sha256 != expected_sha256:
|
|
961
|
+
raise SourceContractError(
|
|
962
|
+
"NEURAL_RUNTIME_CLOSURE_MISMATCH",
|
|
963
|
+
"embedding.runtime",
|
|
964
|
+
"the installed neural dependency closure differs from the tuple PIN",
|
|
965
|
+
)
|
|
966
|
+
return distributions
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def _within(path: Path, root: Path) -> bool:
|
|
970
|
+
try:
|
|
971
|
+
path.relative_to(root)
|
|
972
|
+
except ValueError:
|
|
973
|
+
return False
|
|
974
|
+
return True
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
_STDLIB_SEARCH = tuple(
|
|
978
|
+
value
|
|
979
|
+
for value in sys.path
|
|
980
|
+
if isinstance(value, str)
|
|
981
|
+
and value
|
|
982
|
+
and any(_within(Path(value).resolve(), root) for root in _STDLIB_ROOTS)
|
|
983
|
+
and not any(_within(Path(value).resolve(), root) for root in _THIRD_PARTY_ROOTS)
|
|
984
|
+
)
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
class _AuthenticatedRuntimeLoader:
|
|
988
|
+
def __init__(self, delegate: Any, verify: Any, origin: str) -> None:
|
|
989
|
+
self._delegate = delegate
|
|
990
|
+
self._verify = verify
|
|
991
|
+
self._origin = origin
|
|
992
|
+
|
|
993
|
+
def create_module(self, spec: Any) -> Any:
|
|
994
|
+
self._verify()
|
|
995
|
+
create = getattr(self._delegate, "create_module", None)
|
|
996
|
+
return None if create is None else create(spec)
|
|
997
|
+
|
|
998
|
+
def exec_module(self, module: Any) -> None:
|
|
999
|
+
payload = self._verify()
|
|
1000
|
+
if self._origin.endswith(".py"):
|
|
1001
|
+
if not isinstance(payload, bytes):
|
|
1002
|
+
raise ImportError("authenticated runtime source bytes are unavailable")
|
|
1003
|
+
code = compile(payload, self._origin, "exec", dont_inherit=True)
|
|
1004
|
+
exec(code, module.__dict__)
|
|
1005
|
+
else:
|
|
1006
|
+
self._delegate.exec_module(module)
|
|
1007
|
+
self._verify()
|
|
1008
|
+
|
|
1009
|
+
def __getattr__(self, name: str) -> Any:
|
|
1010
|
+
return getattr(self._delegate, name)
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
class _AuthenticatedRuntimeFinder:
|
|
1014
|
+
"""Resolve runtime packages and standard-library imports from closed roots."""
|
|
1015
|
+
|
|
1016
|
+
def __init__(self, distributions: dict[str, Any]) -> None:
|
|
1017
|
+
self._owners: dict[str, tuple[Path, frozenset[str], dict[str, tuple[bytes, int]], Any]] = {}
|
|
1018
|
+
for _distribution_name, distribution in distributions.items():
|
|
1019
|
+
root = Path(distribution.locate_file("")).resolve(strict=True)
|
|
1020
|
+
record = distribution.read_text("RECORD")
|
|
1021
|
+
if record is None:
|
|
1022
|
+
raise _runtime_closure_refused("an authenticated runtime distribution lost RECORD")
|
|
1023
|
+
members = frozenset(
|
|
1024
|
+
PurePosixPath(str(item)).as_posix()
|
|
1025
|
+
for item in distribution.files or ()
|
|
1026
|
+
if not str(item).startswith("../")
|
|
1027
|
+
)
|
|
1028
|
+
expected: dict[str, tuple[bytes, int]] = {}
|
|
1029
|
+
try:
|
|
1030
|
+
for path, digest, size in csv.reader(io.StringIO(record, newline="")):
|
|
1031
|
+
if path in members and digest and size:
|
|
1032
|
+
expected[path] = (_record_digest(digest), int(size))
|
|
1033
|
+
except (ValueError, csv.Error):
|
|
1034
|
+
raise _runtime_closure_refused(
|
|
1035
|
+
"an authenticated runtime distribution has an invalid RECORD"
|
|
1036
|
+
) from None
|
|
1037
|
+
for member in members:
|
|
1038
|
+
first = PurePosixPath(member).parts[0]
|
|
1039
|
+
if ".dist-info" in first or ".data" in first:
|
|
1040
|
+
continue
|
|
1041
|
+
top_level = first.split(".", 1)[0]
|
|
1042
|
+
if not top_level.isidentifier():
|
|
1043
|
+
continue
|
|
1044
|
+
existing = self._owners.get(top_level)
|
|
1045
|
+
if existing is not None and existing[3] is not distribution:
|
|
1046
|
+
raise _runtime_closure_refused(
|
|
1047
|
+
f"runtime package {top_level} is owned by more than one distribution"
|
|
1048
|
+
)
|
|
1049
|
+
self._owners[top_level] = (root, members, expected, distribution)
|
|
1050
|
+
self._stdlib_roots = _STDLIB_ROOTS
|
|
1051
|
+
self._third_party_roots = _THIRD_PARTY_ROOTS
|
|
1052
|
+
self._stdlib_search = _STDLIB_SEARCH
|
|
1053
|
+
|
|
1054
|
+
def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> Any:
|
|
1055
|
+
del target
|
|
1056
|
+
top_level = fullname.partition(".")[0]
|
|
1057
|
+
owner = self._owners.get(top_level)
|
|
1058
|
+
if owner is not None:
|
|
1059
|
+
root, members, expected, _distribution = owner
|
|
1060
|
+
spec = PathFinder.find_spec(fullname, [str(root)] if path is None else path)
|
|
1061
|
+
self._validate_runtime_spec(fullname, spec, root, members)
|
|
1062
|
+
if spec.loader is not None:
|
|
1063
|
+
spec.loader = _AuthenticatedRuntimeLoader(
|
|
1064
|
+
spec.loader,
|
|
1065
|
+
lambda: self._verify_runtime_origin(fullname, spec, root, expected),
|
|
1066
|
+
spec.origin,
|
|
1067
|
+
)
|
|
1068
|
+
return spec
|
|
1069
|
+
search = self._stdlib_search if path is None else path
|
|
1070
|
+
spec = PathFinder.find_spec(fullname, search)
|
|
1071
|
+
self._validate_stdlib_spec(fullname, spec)
|
|
1072
|
+
return spec
|
|
1073
|
+
|
|
1074
|
+
def _validate_runtime_spec(
|
|
1075
|
+
self, fullname: str, spec: Any, root: Path, members: frozenset[str]
|
|
1076
|
+
) -> None:
|
|
1077
|
+
if spec is None or (spec.loader is None and spec.submodule_search_locations is None):
|
|
1078
|
+
raise ImportError(f"authenticated runtime module {fullname} is unavailable")
|
|
1079
|
+
if isinstance(spec.origin, str):
|
|
1080
|
+
try:
|
|
1081
|
+
relative = Path(spec.origin).resolve(strict=True).relative_to(root).as_posix()
|
|
1082
|
+
except (OSError, RuntimeError, ValueError):
|
|
1083
|
+
raise ImportError(
|
|
1084
|
+
f"runtime module {fullname} is outside its authenticated root"
|
|
1085
|
+
) from None
|
|
1086
|
+
if relative not in members:
|
|
1087
|
+
raise ImportError(f"runtime module {fullname} is absent from its wheel RECORD")
|
|
1088
|
+
return
|
|
1089
|
+
locations = spec.submodule_search_locations
|
|
1090
|
+
if locations is None:
|
|
1091
|
+
raise ImportError(f"runtime namespace {fullname} has no authenticated location")
|
|
1092
|
+
prefix = fullname.replace(".", "/") + "/"
|
|
1093
|
+
if not any(member.startswith(prefix) for member in members):
|
|
1094
|
+
raise ImportError(f"runtime namespace {fullname} is absent from its wheel RECORD")
|
|
1095
|
+
if any(not _within(Path(location).resolve(strict=True), root) for location in locations):
|
|
1096
|
+
raise ImportError(f"runtime namespace {fullname} is outside its authenticated root")
|
|
1097
|
+
|
|
1098
|
+
def _verify_runtime_origin(
|
|
1099
|
+
self,
|
|
1100
|
+
fullname: str,
|
|
1101
|
+
spec: Any,
|
|
1102
|
+
root: Path,
|
|
1103
|
+
expected: dict[str, tuple[bytes, int]],
|
|
1104
|
+
) -> bytes | None:
|
|
1105
|
+
if not isinstance(spec.origin, str):
|
|
1106
|
+
return None
|
|
1107
|
+
try:
|
|
1108
|
+
relative = Path(spec.origin).resolve(strict=True).relative_to(root).as_posix()
|
|
1109
|
+
digest, size = expected[relative]
|
|
1110
|
+
root_fd = os.open(
|
|
1111
|
+
root,
|
|
1112
|
+
os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0),
|
|
1113
|
+
)
|
|
1114
|
+
try:
|
|
1115
|
+
observed, _fingerprint, payload = _read_runtime_member(
|
|
1116
|
+
root_fd,
|
|
1117
|
+
tuple(PurePosixPath(relative).parts),
|
|
1118
|
+
size,
|
|
1119
|
+
capture=spec.origin.endswith(".py"),
|
|
1120
|
+
)
|
|
1121
|
+
finally:
|
|
1122
|
+
os.close(root_fd)
|
|
1123
|
+
except (KeyError, OSError, RuntimeError, SourceContractError, ValueError):
|
|
1124
|
+
raise ImportError(f"runtime module {fullname} changed before execution") from None
|
|
1125
|
+
if observed != digest:
|
|
1126
|
+
raise ImportError(f"runtime module {fullname} changed before execution")
|
|
1127
|
+
return payload
|
|
1128
|
+
|
|
1129
|
+
def _validate_stdlib_spec(self, fullname: str, spec: Any) -> None:
|
|
1130
|
+
if spec is None:
|
|
1131
|
+
raise ImportError(f"undeclared runtime dependency {fullname} is unavailable")
|
|
1132
|
+
if spec.origin in {"built-in", "frozen"}:
|
|
1133
|
+
return
|
|
1134
|
+
if isinstance(spec.origin, str):
|
|
1135
|
+
try:
|
|
1136
|
+
origin = Path(spec.origin).resolve(strict=True)
|
|
1137
|
+
except (OSError, RuntimeError):
|
|
1138
|
+
raise ImportError(
|
|
1139
|
+
f"standard-library module {fullname} has an invalid origin"
|
|
1140
|
+
) from None
|
|
1141
|
+
if any(_within(origin, root) for root in self._third_party_roots):
|
|
1142
|
+
raise ImportError(f"undeclared runtime dependency {fullname} is not authenticated")
|
|
1143
|
+
if any(_within(origin, root) for root in self._stdlib_roots):
|
|
1144
|
+
return
|
|
1145
|
+
raise ImportError(f"undeclared runtime dependency {fullname} is outside closed roots")
|
|
1146
|
+
|
|
1147
|
+
|
|
1148
|
+
class _RuntimeImportGuard:
|
|
1149
|
+
def __init__(self, distributions: dict[str, Any]) -> None:
|
|
1150
|
+
self.finder = _AuthenticatedRuntimeFinder(distributions)
|
|
1151
|
+
self._meta_path: list[Any] = []
|
|
1152
|
+
self._removed: dict[str, Any] = {}
|
|
1153
|
+
|
|
1154
|
+
def __enter__(self) -> None:
|
|
1155
|
+
self._meta_path = list(sys.meta_path)
|
|
1156
|
+
for name, module in tuple(sys.modules.items()):
|
|
1157
|
+
if module is None:
|
|
1158
|
+
continue
|
|
1159
|
+
spec = getattr(module, "__spec__", None)
|
|
1160
|
+
origin = getattr(spec, "origin", None)
|
|
1161
|
+
if origin in {"built-in", "frozen"}:
|
|
1162
|
+
continue
|
|
1163
|
+
if isinstance(origin, str):
|
|
1164
|
+
try:
|
|
1165
|
+
resolved = Path(origin).resolve(strict=True)
|
|
1166
|
+
except (OSError, RuntimeError):
|
|
1167
|
+
resolved = None
|
|
1168
|
+
if (
|
|
1169
|
+
resolved is not None
|
|
1170
|
+
and any(_within(resolved, root) for root in self.finder._stdlib_roots)
|
|
1171
|
+
and not any(_within(resolved, root) for root in self.finder._third_party_roots)
|
|
1172
|
+
):
|
|
1173
|
+
continue
|
|
1174
|
+
removed = sys.modules.pop(name, None)
|
|
1175
|
+
if removed is not None:
|
|
1176
|
+
self._removed[name] = removed
|
|
1177
|
+
sys.meta_path[:] = [BuiltinImporter, FrozenImporter, self.finder]
|
|
1178
|
+
|
|
1179
|
+
def __exit__(self, _type: Any, _value: Any, _traceback: Any) -> None:
|
|
1180
|
+
sys.meta_path[:] = self._meta_path
|
|
1181
|
+
owned = set(self.finder._owners)
|
|
1182
|
+
for name in tuple(sys.modules):
|
|
1183
|
+
if name.partition(".")[0] in owned:
|
|
1184
|
+
sys.modules.pop(name, None)
|
|
1185
|
+
for name, module in self._removed.items():
|
|
1186
|
+
sys.modules.setdefault(name, module)
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
def _runtime_module_spec(distribution: Any, module_name: str) -> Any:
|
|
1190
|
+
"""Resolve a top-level package only beneath the distribution whose bytes were authenticated."""
|
|
1191
|
+
|
|
1192
|
+
try:
|
|
1193
|
+
root = Path(distribution.locate_file("")).resolve(strict=True)
|
|
1194
|
+
expected_relative = f"{module_name}/__init__.py"
|
|
1195
|
+
members = distribution.files
|
|
1196
|
+
if members is None or expected_relative not in {
|
|
1197
|
+
PurePosixPath(str(item)).as_posix() for item in members
|
|
1198
|
+
}:
|
|
1199
|
+
raise ValueError
|
|
1200
|
+
unresolved = root / expected_relative
|
|
1201
|
+
opened = os.lstat(unresolved)
|
|
1202
|
+
if not stat.S_ISREG(opened.st_mode):
|
|
1203
|
+
raise ValueError
|
|
1204
|
+
expected = unresolved.resolve(strict=True)
|
|
1205
|
+
expected.relative_to(root)
|
|
1206
|
+
spec = PathFinder.find_spec(module_name, [str(root)])
|
|
1207
|
+
if spec is None or spec.loader is None or not isinstance(spec.origin, str):
|
|
1208
|
+
raise ValueError
|
|
1209
|
+
if Path(spec.origin).resolve(strict=True) != expected:
|
|
1210
|
+
raise ValueError
|
|
1211
|
+
return spec
|
|
1212
|
+
except (OSError, RuntimeError, ValueError):
|
|
1213
|
+
raise SourceContractError(
|
|
1214
|
+
"NEURAL_RUNTIME_CLOSURE_MISMATCH",
|
|
1215
|
+
"embedding.runtime",
|
|
1216
|
+
f"the authenticated {module_name} module could not be resolved",
|
|
1217
|
+
) from None
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
def _require_runtime_module_origin(module: Any, distribution: Any, module_name: str) -> None:
|
|
1221
|
+
"""Require an imported runtime package to come from its authenticated distribution."""
|
|
1222
|
+
|
|
1223
|
+
try:
|
|
1224
|
+
root = Path(distribution.locate_file("")).resolve(strict=True)
|
|
1225
|
+
raw_origin = getattr(module, "__file__", None)
|
|
1226
|
+
if not isinstance(raw_origin, str) or not raw_origin:
|
|
1227
|
+
raise ValueError
|
|
1228
|
+
origin = Path(raw_origin)
|
|
1229
|
+
opened = os.lstat(origin)
|
|
1230
|
+
if not stat.S_ISREG(opened.st_mode):
|
|
1231
|
+
raise ValueError
|
|
1232
|
+
resolved = origin.resolve(strict=True)
|
|
1233
|
+
relative = resolved.relative_to(root).as_posix()
|
|
1234
|
+
members = distribution.files
|
|
1235
|
+
if members is None or relative not in {
|
|
1236
|
+
PurePosixPath(str(item)).as_posix() for item in members
|
|
1237
|
+
}:
|
|
1238
|
+
raise ValueError
|
|
1239
|
+
except (metadata.PackageNotFoundError, OSError, RuntimeError, ValueError):
|
|
1240
|
+
raise SourceContractError(
|
|
1241
|
+
"NEURAL_RUNTIME_CLOSURE_MISMATCH",
|
|
1242
|
+
"embedding.runtime",
|
|
1243
|
+
f"the imported {module_name} module is outside its authenticated distribution",
|
|
1244
|
+
) from None
|
|
1245
|
+
|
|
1246
|
+
|
|
1247
|
+
def _load_authenticated_runtime_module(
|
|
1248
|
+
distribution: Any, module_name: str, finder: _AuthenticatedRuntimeFinder | None = None
|
|
1249
|
+
) -> Any:
|
|
1250
|
+
"""Load a runtime package from its authenticated origin without consulting import hooks."""
|
|
1251
|
+
|
|
1252
|
+
spec = (
|
|
1253
|
+
_runtime_module_spec(distribution, module_name)
|
|
1254
|
+
if finder is None
|
|
1255
|
+
else finder.find_spec(module_name)
|
|
1256
|
+
)
|
|
1257
|
+
existing = sys.modules.get(module_name)
|
|
1258
|
+
if existing is not None:
|
|
1259
|
+
_require_runtime_module_origin(existing, distribution, module_name)
|
|
1260
|
+
return existing
|
|
1261
|
+
module = module_from_spec(spec)
|
|
1262
|
+
sys.modules[module_name] = module
|
|
1263
|
+
try:
|
|
1264
|
+
spec.loader.exec_module(module)
|
|
1265
|
+
except (ImportError, ModuleNotFoundError):
|
|
1266
|
+
sys.modules.pop(module_name, None)
|
|
1267
|
+
raise SourceContractError(
|
|
1268
|
+
"NEURAL_RUNTIME_UNAVAILABLE",
|
|
1269
|
+
"embedding.runtime",
|
|
1270
|
+
"the exact optional neural runtime could not be imported",
|
|
1271
|
+
) from None
|
|
1272
|
+
except BaseException:
|
|
1273
|
+
sys.modules.pop(module_name, None)
|
|
1274
|
+
raise
|
|
1275
|
+
_require_runtime_module_origin(module, distribution, module_name)
|
|
1276
|
+
return module
|
|
1277
|
+
|
|
1278
|
+
|
|
1279
|
+
def _load_runtime(
|
|
1280
|
+
model_bytes: bytes,
|
|
1281
|
+
tokenizer_bytes: bytes,
|
|
1282
|
+
expected_closure_sha256: str,
|
|
1283
|
+
snapshot_root: Path | None = None,
|
|
1284
|
+
) -> tuple[Any, Any, Any, _RuntimeImportGuard, Path]:
|
|
1285
|
+
installed = _require_runtime_closure(expected_closure_sha256)
|
|
1286
|
+
snapshot_root, distributions = _snapshot_runtime(installed, snapshot_root)
|
|
1287
|
+
snapshot_closure = {
|
|
1288
|
+
"distributions": sorted(
|
|
1289
|
+
(
|
|
1290
|
+
{
|
|
1291
|
+
"name": name,
|
|
1292
|
+
"record_sha256": _portable_record_sha256(
|
|
1293
|
+
distribution, distribution.read_text("RECORD") or ""
|
|
1294
|
+
),
|
|
1295
|
+
"version": distribution.version,
|
|
1296
|
+
}
|
|
1297
|
+
for name, distribution in distributions.items()
|
|
1298
|
+
),
|
|
1299
|
+
key=lambda item: item["name"],
|
|
1300
|
+
),
|
|
1301
|
+
"roots": list(_RUNTIME_ROOT_DISTRIBUTIONS),
|
|
1302
|
+
"schema_version": "local-search-neural-installed-closure.v2",
|
|
1303
|
+
}
|
|
1304
|
+
if hashlib.sha256(canonical_json_bytes(snapshot_closure)).hexdigest() != (
|
|
1305
|
+
expected_closure_sha256
|
|
1306
|
+
):
|
|
1307
|
+
shutil.rmtree(snapshot_root, ignore_errors=True)
|
|
1308
|
+
raise _runtime_closure_refused("the private runtime snapshot differs from the tuple PIN")
|
|
1309
|
+
before = _runtime_installation_state(distributions)
|
|
1310
|
+
for distribution_name, expected in RUNTIME_VERSIONS.items():
|
|
1311
|
+
distribution = distributions[canonicalize_name(distribution_name)]
|
|
1312
|
+
observed = distribution.version
|
|
1313
|
+
if observed != expected:
|
|
1314
|
+
raise SourceContractError(
|
|
1315
|
+
"NEURAL_RUNTIME_MISMATCH",
|
|
1316
|
+
"embedding.runtime",
|
|
1317
|
+
f"{distribution_name} must be exactly {expected}, observed {observed}",
|
|
1318
|
+
)
|
|
1319
|
+
guard = _RuntimeImportGuard(distributions)
|
|
1320
|
+
try:
|
|
1321
|
+
guard.__enter__()
|
|
1322
|
+
np = _load_authenticated_runtime_module(distributions["numpy"], "numpy", guard.finder)
|
|
1323
|
+
ort = _load_authenticated_runtime_module(
|
|
1324
|
+
distributions["onnxruntime"], "onnxruntime", guard.finder
|
|
1325
|
+
)
|
|
1326
|
+
tokenizers = _load_authenticated_runtime_module(
|
|
1327
|
+
distributions["tokenizers"], "tokenizers", guard.finder
|
|
1328
|
+
)
|
|
1329
|
+
|
|
1330
|
+
options = ort.SessionOptions()
|
|
1331
|
+
options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
|
1332
|
+
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
|
|
1333
|
+
options.inter_op_num_threads = 1
|
|
1334
|
+
options.intra_op_num_threads = 1
|
|
1335
|
+
options.enable_mem_pattern = False
|
|
1336
|
+
options.enable_cpu_mem_arena = False
|
|
1337
|
+
options.use_deterministic_compute = True
|
|
1338
|
+
options.add_session_config_entry("session.inter_op.allow_spinning", "0")
|
|
1339
|
+
options.add_session_config_entry("session.intra_op.allow_spinning", "0")
|
|
1340
|
+
try:
|
|
1341
|
+
session = ort.InferenceSession(
|
|
1342
|
+
model_bytes,
|
|
1343
|
+
sess_options=options,
|
|
1344
|
+
providers=["CPUExecutionProvider"],
|
|
1345
|
+
)
|
|
1346
|
+
session.disable_fallback()
|
|
1347
|
+
if session.get_providers() != ["CPUExecutionProvider"]:
|
|
1348
|
+
raise SourceContractError(
|
|
1349
|
+
"NEURAL_PROVIDER",
|
|
1350
|
+
"embedding.runtime",
|
|
1351
|
+
"the runtime enabled an undeclared execution provider",
|
|
1352
|
+
)
|
|
1353
|
+
tokenizer = tokenizers.Tokenizer.from_str(tokenizer_bytes.decode("utf-8"))
|
|
1354
|
+
except SourceContractError:
|
|
1355
|
+
raise
|
|
1356
|
+
except Exception:
|
|
1357
|
+
raise SourceContractError(
|
|
1358
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
1359
|
+
"embedding.runtime",
|
|
1360
|
+
"the verified sidecar could not create the pinned local session",
|
|
1361
|
+
) from None
|
|
1362
|
+
tokenizer.enable_truncation(MAX_LENGTH, direction="right", strategy="longest_first")
|
|
1363
|
+
pad_id = tokenizer.token_to_id("[PAD]")
|
|
1364
|
+
if pad_id is None:
|
|
1365
|
+
raise SourceContractError(
|
|
1366
|
+
"NEURAL_TOKENIZER",
|
|
1367
|
+
"embedding.runtime",
|
|
1368
|
+
"the pinned tokenizer has no padding token",
|
|
1369
|
+
)
|
|
1370
|
+
tokenizer.enable_padding(
|
|
1371
|
+
direction="right", pad_id=pad_id, pad_token="[PAD]", length=MAX_LENGTH
|
|
1372
|
+
)
|
|
1373
|
+
after = _runtime_installation_state(distributions)
|
|
1374
|
+
except BaseException:
|
|
1375
|
+
guard.__exit__(*sys.exc_info())
|
|
1376
|
+
shutil.rmtree(snapshot_root, ignore_errors=True)
|
|
1377
|
+
raise
|
|
1378
|
+
before_roots = {
|
|
1379
|
+
name: Path(distribution.locate_file("")).resolve(strict=True)
|
|
1380
|
+
for name, distribution in distributions.items()
|
|
1381
|
+
}
|
|
1382
|
+
after_roots = {
|
|
1383
|
+
name: Path(distribution.locate_file("")).resolve(strict=True)
|
|
1384
|
+
for name, distribution in distributions.items()
|
|
1385
|
+
}
|
|
1386
|
+
if before != after or before_roots != after_roots:
|
|
1387
|
+
guard.__exit__(None, None, None)
|
|
1388
|
+
shutil.rmtree(snapshot_root, ignore_errors=True)
|
|
1389
|
+
raise _runtime_closure_refused("the runtime installation changed while it was loaded")
|
|
1390
|
+
return np, session, tokenizer, guard, snapshot_root
|
|
1391
|
+
|
|
1392
|
+
|
|
1393
|
+
def _encode_with_runtime(runtime: tuple[Any, ...], text: str) -> tuple[int, ...]:
|
|
1394
|
+
np, session, tokenizer = runtime[:3]
|
|
1395
|
+
encoded = tokenizer.encode(text, add_special_tokens=True)
|
|
1396
|
+
input_names = {item.name for item in session.get_inputs()}
|
|
1397
|
+
arrays = {
|
|
1398
|
+
"input_ids": np.asarray([encoded.ids], dtype=np.int64),
|
|
1399
|
+
"attention_mask": np.asarray([encoded.attention_mask], dtype=np.int64),
|
|
1400
|
+
"token_type_ids": np.asarray([encoded.type_ids], dtype=np.int64),
|
|
1401
|
+
}
|
|
1402
|
+
feed = {name: arrays[name] for name in input_names if name in arrays}
|
|
1403
|
+
if set(feed) != input_names:
|
|
1404
|
+
raise SourceContractError(
|
|
1405
|
+
"NEURAL_MODEL_INPUT",
|
|
1406
|
+
"embedding.model",
|
|
1407
|
+
"the pinned model declares an unsupported input set",
|
|
1408
|
+
)
|
|
1409
|
+
outputs = session.run(None, feed)
|
|
1410
|
+
if len(outputs) != 1 or outputs[0].ndim != 3:
|
|
1411
|
+
raise SourceContractError(
|
|
1412
|
+
"NEURAL_MODEL_OUTPUT",
|
|
1413
|
+
"embedding.model",
|
|
1414
|
+
"the pinned model did not emit one token-embedding tensor",
|
|
1415
|
+
)
|
|
1416
|
+
hidden = outputs[0].astype(np.float32, copy=False)
|
|
1417
|
+
if hidden.shape[0] != 1 or hidden.shape[2] != DIMENSIONS:
|
|
1418
|
+
raise SourceContractError(
|
|
1419
|
+
"NEURAL_MODEL_OUTPUT",
|
|
1420
|
+
"embedding.model",
|
|
1421
|
+
"the pinned model emitted the wrong batch or embedding dimension",
|
|
1422
|
+
)
|
|
1423
|
+
mask = arrays["attention_mask"].astype(np.float32)[..., None]
|
|
1424
|
+
pooled = (hidden * mask).sum(axis=1, dtype=np.float32) / mask.sum(axis=1, dtype=np.float32)
|
|
1425
|
+
norm = np.sqrt((pooled * pooled).sum(axis=1, dtype=np.float32), dtype=np.float32)[..., None]
|
|
1426
|
+
if bool(np.any(norm == 0)):
|
|
1427
|
+
raise SourceContractError(
|
|
1428
|
+
"NEURAL_ZERO_VECTOR",
|
|
1429
|
+
"embedding.model",
|
|
1430
|
+
"the pinned model emitted a zero-norm vector",
|
|
1431
|
+
)
|
|
1432
|
+
normalized = pooled / norm
|
|
1433
|
+
magnitude = np.floor(np.abs(normalized) * VECTOR_SCALE + np.float32(0.5)).astype(np.int64)
|
|
1434
|
+
quantized = np.where(normalized < 0, -magnitude, magnitude)
|
|
1435
|
+
if bool(np.any(quantized < _INT32_MIN)) or bool(np.any(quantized > _INT32_MAX)):
|
|
1436
|
+
raise SourceContractError(
|
|
1437
|
+
"NEURAL_VECTOR_RANGE",
|
|
1438
|
+
"embedding.vector",
|
|
1439
|
+
"quantized output exceeded signed int32",
|
|
1440
|
+
)
|
|
1441
|
+
return tuple(int(value) for value in quantized[0])
|
|
1442
|
+
|
|
1443
|
+
|
|
1444
|
+
def _runtime_worker(
|
|
1445
|
+
connection: Any,
|
|
1446
|
+
model_bytes: bytes,
|
|
1447
|
+
tokenizer_bytes: bytes,
|
|
1448
|
+
expected_closure_sha256: str,
|
|
1449
|
+
snapshot_root: Path,
|
|
1450
|
+
) -> None:
|
|
1451
|
+
runtime: tuple[Any, ...] | None = None
|
|
1452
|
+
try:
|
|
1453
|
+
runtime = _load_runtime(
|
|
1454
|
+
model_bytes, tokenizer_bytes, expected_closure_sha256, snapshot_root
|
|
1455
|
+
)
|
|
1456
|
+
connection.send({"status": "ready"})
|
|
1457
|
+
while True:
|
|
1458
|
+
command, value = connection.recv()
|
|
1459
|
+
if command == "close":
|
|
1460
|
+
return
|
|
1461
|
+
if command != "encode" or not isinstance(value, str):
|
|
1462
|
+
raise SourceContractError(
|
|
1463
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
1464
|
+
"embedding.runtime",
|
|
1465
|
+
"the bounded neural worker received an invalid request",
|
|
1466
|
+
)
|
|
1467
|
+
vector = _encode_with_runtime(runtime, value)
|
|
1468
|
+
connection.send({"peak_rss_bytes": _peak_rss_bytes(), "status": "ok", "vector": vector})
|
|
1469
|
+
except SourceContractError as error:
|
|
1470
|
+
connection.send(
|
|
1471
|
+
{"code": error.code, "detail": error.detail, "path": error.path, "status": "error"}
|
|
1472
|
+
)
|
|
1473
|
+
except (EOFError, BrokenPipeError, OSError):
|
|
1474
|
+
return
|
|
1475
|
+
except Exception:
|
|
1476
|
+
try:
|
|
1477
|
+
connection.send(
|
|
1478
|
+
{
|
|
1479
|
+
"code": "NEURAL_SESSION_UNAVAILABLE",
|
|
1480
|
+
"detail": "the bounded neural worker failed",
|
|
1481
|
+
"path": "embedding.runtime",
|
|
1482
|
+
"status": "error",
|
|
1483
|
+
}
|
|
1484
|
+
)
|
|
1485
|
+
except (BrokenPipeError, EOFError, OSError):
|
|
1486
|
+
pass
|
|
1487
|
+
finally:
|
|
1488
|
+
if runtime is not None:
|
|
1489
|
+
runtime[3].__exit__(None, None, None)
|
|
1490
|
+
shutil.rmtree(runtime[4], ignore_errors=True)
|
|
1491
|
+
connection.close()
|
|
1492
|
+
|
|
1493
|
+
|
|
1494
|
+
def _start_worker(
|
|
1495
|
+
model_bytes: bytes, tokenizer_bytes: bytes, expected_closure_sha256: str
|
|
1496
|
+
) -> tuple[Any, Any, Path]:
|
|
1497
|
+
_require_runtime_closure(expected_closure_sha256)
|
|
1498
|
+
snapshot_root = Path(tempfile.mkdtemp(prefix="mostlyright-neural-runtime-"))
|
|
1499
|
+
context = multiprocessing.get_context("spawn")
|
|
1500
|
+
parent, child = context.Pipe(duplex=True)
|
|
1501
|
+
process = context.Process(
|
|
1502
|
+
target=_runtime_worker,
|
|
1503
|
+
args=(child, model_bytes, tokenizer_bytes, expected_closure_sha256, snapshot_root),
|
|
1504
|
+
daemon=True,
|
|
1505
|
+
name="mostlyright-local-neural",
|
|
1506
|
+
)
|
|
1507
|
+
try:
|
|
1508
|
+
process.start()
|
|
1509
|
+
except Exception:
|
|
1510
|
+
parent.close()
|
|
1511
|
+
child.close()
|
|
1512
|
+
shutil.rmtree(snapshot_root, ignore_errors=True)
|
|
1513
|
+
raise SourceContractError(
|
|
1514
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
1515
|
+
"embedding.runtime",
|
|
1516
|
+
"the bounded neural worker could not start",
|
|
1517
|
+
) from None
|
|
1518
|
+
child.close()
|
|
1519
|
+
try:
|
|
1520
|
+
response = _receive_worker_result(
|
|
1521
|
+
parent,
|
|
1522
|
+
process,
|
|
1523
|
+
timeout_seconds=MAX_RUNTIME_INITIALIZATION_SECONDS,
|
|
1524
|
+
snapshot_root=snapshot_root,
|
|
1525
|
+
timeout_detail=(
|
|
1526
|
+
"runtime initialization exceeded the pinned wall-time limit and its worker was "
|
|
1527
|
+
"terminated"
|
|
1528
|
+
),
|
|
1529
|
+
)
|
|
1530
|
+
except SourceContractError:
|
|
1531
|
+
shutil.rmtree(snapshot_root, ignore_errors=True)
|
|
1532
|
+
raise
|
|
1533
|
+
if response.get("status") == "error":
|
|
1534
|
+
_terminate_worker(parent, process, snapshot_root)
|
|
1535
|
+
raise SourceContractError(
|
|
1536
|
+
response.get("code", "NEURAL_SESSION_UNAVAILABLE"),
|
|
1537
|
+
response.get("path", "embedding.runtime"),
|
|
1538
|
+
response.get("detail", "the bounded neural worker failed during initialization"),
|
|
1539
|
+
)
|
|
1540
|
+
if response != {"status": "ready"}:
|
|
1541
|
+
_terminate_worker(parent, process, snapshot_root)
|
|
1542
|
+
raise SourceContractError(
|
|
1543
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
1544
|
+
"embedding.runtime",
|
|
1545
|
+
"the bounded neural worker returned an invalid initialization response",
|
|
1546
|
+
)
|
|
1547
|
+
return parent, process, snapshot_root
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
def _terminate_worker(connection: Any, process: Any, snapshot_root: Path | None = None) -> None:
|
|
1551
|
+
if process.is_alive():
|
|
1552
|
+
try:
|
|
1553
|
+
connection.send(("close", None))
|
|
1554
|
+
except (BrokenPipeError, EOFError, OSError):
|
|
1555
|
+
pass
|
|
1556
|
+
process.join(_WORKER_JOIN_SECONDS)
|
|
1557
|
+
try:
|
|
1558
|
+
connection.close()
|
|
1559
|
+
except OSError:
|
|
1560
|
+
pass
|
|
1561
|
+
if process.is_alive():
|
|
1562
|
+
process.terminate()
|
|
1563
|
+
process.join(_WORKER_JOIN_SECONDS)
|
|
1564
|
+
if process.is_alive():
|
|
1565
|
+
process.kill()
|
|
1566
|
+
process.join(_WORKER_JOIN_SECONDS)
|
|
1567
|
+
if snapshot_root is not None:
|
|
1568
|
+
shutil.rmtree(snapshot_root, ignore_errors=True)
|
|
1569
|
+
|
|
1570
|
+
|
|
1571
|
+
def _receive_worker_result(
|
|
1572
|
+
connection: Any,
|
|
1573
|
+
process: Any,
|
|
1574
|
+
*,
|
|
1575
|
+
timeout_seconds: float,
|
|
1576
|
+
snapshot_root: Path | None = None,
|
|
1577
|
+
timeout_detail: str = (
|
|
1578
|
+
"encoding exceeded the pinned wall-time limit and its worker was terminated"
|
|
1579
|
+
),
|
|
1580
|
+
) -> dict[str, Any]:
|
|
1581
|
+
try:
|
|
1582
|
+
ready = connection.poll(timeout_seconds)
|
|
1583
|
+
except OSError:
|
|
1584
|
+
_terminate_worker(connection, process, snapshot_root)
|
|
1585
|
+
raise SourceContractError(
|
|
1586
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
1587
|
+
"embedding.runtime",
|
|
1588
|
+
"the bounded neural worker exited without a result",
|
|
1589
|
+
) from None
|
|
1590
|
+
if not ready:
|
|
1591
|
+
_terminate_worker(connection, process, snapshot_root)
|
|
1592
|
+
raise SourceContractError(
|
|
1593
|
+
"NEURAL_TIME_LIMIT",
|
|
1594
|
+
"embedding.runtime",
|
|
1595
|
+
timeout_detail,
|
|
1596
|
+
)
|
|
1597
|
+
try:
|
|
1598
|
+
response = connection.recv()
|
|
1599
|
+
except (EOFError, OSError):
|
|
1600
|
+
_terminate_worker(connection, process, snapshot_root)
|
|
1601
|
+
raise SourceContractError(
|
|
1602
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
1603
|
+
"embedding.runtime",
|
|
1604
|
+
"the bounded neural worker exited without a result",
|
|
1605
|
+
) from None
|
|
1606
|
+
if not isinstance(response, dict):
|
|
1607
|
+
_terminate_worker(connection, process, snapshot_root)
|
|
1608
|
+
raise SourceContractError(
|
|
1609
|
+
"NEURAL_SESSION_UNAVAILABLE",
|
|
1610
|
+
"embedding.runtime",
|
|
1611
|
+
"the bounded neural worker returned an invalid result",
|
|
1612
|
+
)
|
|
1613
|
+
return response
|
|
1614
|
+
|
|
1615
|
+
|
|
1616
|
+
def _peak_rss_bytes() -> int:
|
|
1617
|
+
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
|
1618
|
+
return peak if sys.platform == "darwin" else peak * 1024
|