From 0c4ac962fdbf1c937f836197e69b2ab04bf229f2 Mon Sep 17 00:00:00 2001 From: thorsten Date: Fri, 16 Oct 2026 10:17:26 +0200 Subject: [PATCH 1/2] Compose source decisions and complete neutral river model in retained Rust state --- docs/native-model-finalization-migration.md | 48 ++++ docs/rust-migration-worklist-20261015.md | 6 + rust/catalogue-geometry/src/main.rs | 1 + rust/catalogue-geometry/src/model_complete.rs | 240 ++++++++++++++++++ .../catalogue-geometry/src/worker_protocol.rs | 17 ++ src/riverfahrplan/worker_session.py | 6 + tests/test_model_complete_rust.py | 172 +++++++++++++ 7 files changed, 490 insertions(+) create mode 100644 docs/native-model-finalization-migration.md create mode 100644 rust/catalogue-geometry/src/model_complete.rs create mode 100644 tests/test_model_complete_rust.py diff --git a/docs/native-model-finalization-migration.md b/docs/native-model-finalization-migration.md new file mode 100644 index 00000000..b93dcf6a --- /dev/null +++ b/docs/native-model-finalization-migration.md @@ -0,0 +1,48 @@ +# Quellen und vollständiges Modell aus gehaltenem Zustand + +`dataset_model_finalize(dataset_key, model_key, save_as=..., way_river_ids=...)` +setzt nach `dataset_model_branches` fort. Der Aufruf liefert ausschließlich +ein Handle; `/model` enthält das vollständige neutrale `RiverModel.as_dict()`- +Format. Auch synthetische R-/W-Identitäten erhalten die bisherige Darstellung +mit `river_id` und leerem `wikidata_id`. + +Rust komponiert benannte Quellzuflüsse, verbrauchte Quellzweige, das +Formationsereignis, bewiesene Terminal-Spender, eindeutige vollständige +Seitennetz-Spender und gerichtete Quellfortsetzungen. Darauf folgen die +Quellbeschreibung, Quellpriorität, Identitätsanreicherung, stabile Ereignis- +und Zweigsortierung sowie sämtliche Modellmetadaten. Bestehende Fachkerne +bleiben für diese Entscheidungen verantwortlich. Python übergibt nur Handles, +Unicode-Faltung und die optionale deklarative Way-/Fluss-ID-Zuordnung. + +Endpunktkandidaten werden mit der final übergebenen ID-Zuordnung nativ erneut +ermittelt. Dadurch können spätere IDs keine veraltete Fortsetzung aus einem +früheren Aufruf übernehmen. Bei Formation werden nur die verbrauchten +repräsentativen Zweige entfernt; bei einem Spender nur dessen ausgewählter +Listenplatz. Untergeordnete Ereignisse und Zweige bleiben unverändert. +Kompakte Hauptlaufereignisse erhalten vor der finalen Sortierung wieder ihre +vollständigen Modellfelder einschließlich der OSM-Knoten-ID. + +Das fertige Modell wird unter einem eigenen Feld gehalten. Die bisherigen +Zwischenfelder bleiben als reproduzierbare Eingabe erhalten, sodass dieselbe +Fortsetzung auch auf ihrem eigenen Ergebnis wiederholbar bleibt. Datensatz- +revisionen und atomare Ergebnisablage nutzen den vorhandenen Worker-Vertrag. + +Die neuen PBF-Vergleichsfälle prüfen das gesamte Modell gegen den normalen +Python-Treiber, einschließlich Quellbildung und -veto, Wasserflächen-/Quell- +Priorität, Quellen und benannten Punkten, Spenderauswahl, +Fortsetzungsrichtungen, Relationsrang, leeren und nachgereichten IDs, +synthetischen Identitäten, Alternativrouten, Zufallsgraphen und Fehlerfällen. +Während der nativen Verkettung sind der Python-Modelltreiber, +Quell-/Spender-/Finalisierungsalgorithmen und `GEOD.inv` gesperrt. Die +Modellwiederherstellung mit `RiverModel.from_dict` wird ebenfalls geprüft. + +Python bleibt Standard; der normale Modell-/Regional-/CLI-Treiber verwendet +weiter seine bisherigen Adapter. Ein öffentlicher nativer Gesamteinstieg und +dessen Integration bleiben weitere Arbeit. Interne JSON-Kopien bestehen; +keine Leistungszusage oder harte RSS-Grenze. Große reale PBF-/Zeit-/RSS-Abnahmen +stehen weiter aus. + +## Prüfstand + +Die abschließenden Debug-/Release-Prüfzahlen und der Quellnachweis folgen nach +dem vollständigen Prüflauf. diff --git a/docs/rust-migration-worklist-20261015.md b/docs/rust-migration-worklist-20261015.md index c5fe2df7..d0c5c232 100644 --- a/docs/rust-migration-worklist-20261015.md +++ b/docs/rust-migration-worklist-20261015.md @@ -60,3 +60,9 @@ Hauptlaufzweige sowie Untergrund- und Seitenmerkmalsmontage laufen nun aus dem gehaltenen Zustand; siehe native-model-branches-migration.md. Nächste Grenze sind Quellbildung, Spenderentscheidungen und Modellfinalisierung, anschließend Regional-/CLI-Komposition. Python bleibt weiterhin Standard. + +Quellbildung, Spenderauswahl, Quellbeschreibung, Sortierung und vollständige +neutrale Modellmontage laufen nun ebenfalls aus gehaltenem Zustand; +siehe native-model-finalization-migration.md. Offen bleiben der öffentliche +native Gesamteinstieg, die Integration in Modell-/Regional-/CLI-Treiber und +die große reale PBF-/Zeit-/RSS-Abnahme. Python bleibt Standard. diff --git a/rust/catalogue-geometry/src/main.rs b/rust/catalogue-geometry/src/main.rs index 3c195892..3ae92f35 100644 --- a/rust/catalogue-geometry/src/main.rs +++ b/rust/catalogue-geometry/src/main.rs @@ -19,6 +19,7 @@ mod manifest; mod metro_render_plan; mod model_branches; mod model_canals; +mod model_complete; mod model_connections; mod model_features; mod model_finalize; diff --git a/rust/catalogue-geometry/src/model_complete.rs b/rust/catalogue-geometry/src/model_complete.rs new file mode 100644 index 00000000..d5ed4e44 --- /dev/null +++ b/rust/catalogue-geometry/src/model_complete.rs @@ -0,0 +1,240 @@ +//! Source decisions and neutral RiverModel assembly from retained branches. +use crate::{ + model_branches::{array, id, number}, + pbf, + worker_protocol::execute, +}; +use serde::Deserialize; +use serde_json::{json, Value}; +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct Configuration { + schema_version: u32, + casefold: Value, + way_river_ids: Value, +} +fn fields(value: &Value, names: &[&str]) -> Value { + Value::Object( + names + .iter() + .map(|k| ((*k).to_string(), value[*k].clone())) + .collect(), + ) +} +fn receiver(mut value: Value) -> Value { + if !value.is_null() { + for key in ["bank", "flow_direction", "connection_kind", "river_id"] { + if value.get(key).is_none() { + value[key] = Value::Null; + } + } + } + value +} +fn ordered(values: &[Value], order: &Value) -> Result, String> { + array(order)? + .iter() + .map(|i| { + values + .get( + i.as_u64() + .and_then(|n| usize::try_from(n).ok()) + .ok_or("invalid model permutation")?, + ) + .cloned() + .ok_or_else(|| "unknown model permutation index".into()) + }) + .collect() +} +fn prune(branches: &mut Vec, consumed: Value, donor: Option) -> Result<(), String> { + let plan = execute( + "--model-finalize", + json!({"schema_version":35,"mode":"prune","consumed_way_ids":consumed,"donor_owner":donor, + "branches":branches.iter().enumerate().map(|(i,b)|json!({"way_id":b["way_id"],"owner":i})).collect::>()}), + )?; + *branches = ordered(branches, &plan["keep_indices"])?; + Ok(()) +} +pub(crate) fn build(data: &pbf::Imported, state: Value, c: Configuration) -> Result { + if c.schema_version != 81 || state["schema_version"] != 1 { + return Err("model finalization requires schema_version 81 and native model state".into()); + } + // Require the complete prefix before recomputing endpoint candidates with + // the final identity mapping. This also prevents stale mapping candidates. + let mut branches = array(&state["branches"])?.clone(); + array(&state["underground_main_sections"])?; + array(&state["passages"])?; + let mut state = crate::model_connections::build( + data, + state, + serde_json::from_value(json!({"schema_version":77,"way_river_ids":c.way_river_ids})) + .map_err(|e| e.to_string())?, + )?; + let path = array(&state["positions"]["path_node_ids"])?; + let mouth = path.first().ok_or("empty final model path")?; + let source = path.last().ok_or("empty final model path")?; + let (mouth, source) = (id(mouth)?, id(source)?); + let mut events = array(&state["events"])?.clone(); + for e in &mut events { + let node_id = id(&e["node_id"])?; + let object = e.as_object_mut().ok_or("invalid final point event")?; + object.insert("object_type".into(), json!("node")); + object.insert("osm_id".into(), json!(node_id)); + for key in [ + "osm_id", + "match_method", + "boundary_object_type", + "boundary_osm_id", + "side_distance_km", + "side_route_index", + ] { + object.entry(key).or_insert(Value::Null); + } + for key in ["matched_node_ids", "matched_km_range"] { + object.entry(key).or_insert_with(|| json!([])); + } + } + let waterbody = receiver(state["source_waterbody"].clone()); + let context = &state["terminal_context"]; + let mut formation = json!({"source_branches":[],"candidates":[],"rejected_reason":null}); + if waterbody.is_null() && context.is_null() { + let order = data.order.as_ref().ok_or("missing native dataset order")?; + formation = execute( + "--source-formation", + json!({"schema_version":20,"source_node_id":source,"river_name":state["river_name"],"wikidata_id":state["river_id"],"casefold":c.casefold, + "ways":order.ways.iter().map(|id|json!({"id":id,"tags":data.ways[id].tags})).collect::>(), + "relations":order.relations.iter().map(|id|json!({"id":id,"tags":data.relations[id].tags})).collect::>(), + "branches":branches.iter().map(|b|fields(b,&["way_id","kind","label","junction_node_id","rejoin_node_id","transfer_role","way_ids","relation_id","waterway_type","side"])).collect::>()}), + )?; + if !array(&formation["source_branches"])?.is_empty() { + prune(&mut branches, formation["consumed_way_ids"].clone(), None)?; + events + .iter_mut() + .find(|e| e["node_id"] == source) + .ok_or("missing final source event")?["kind"] = json!("formation"); + } + } + let has_formation = !array(&formation["source_branches"])?.is_empty(); + let mut donor = if !context.is_null() && waterbody.is_null() { + state["terminal_source_donor"].clone() + } else { + Value::Null + }; + if waterbody.is_null() && !has_formation && context.is_null() { + let donor_branches = branches + .iter() + .map(|b| { + let mut packet = fields( + b, + &[ + "kind", + "relation_id", + "label", + "junction_node_id", + "rejoin_node_id", + "way_ids", + "path_node_ids", + ], + ); + packet["connections"] = json!(array(&b["connections"])? + .iter() + .map(|p| fields(p, &["node_id", "role"])) + .collect::>()); + Ok(packet) + }) + .collect::, String>>()?; + let selection = execute( + "--transfer-donor", + json!({"schema_version":23,"source_node_id":source,"mouth_node_id":mouth,"river_name":state["river_name"], + "mouth_receiver":if state["mouth_receiver"].is_null(){Value::Null}else{fields(&state["mouth_receiver"],&["object_type","osm_id","name"])}, + "branches":donor_branches}), + )?; + if let Some(index) = selection["donor_index"].as_u64() { + let index = usize::try_from(index).map_err(|e| e.to_string())?; + let b = branches.get(index).ok_or("unknown terminal donor index")?; + donor=execute("--model-finalize",json!({"schema_version":35,"mode":"donor","branch":fields(b,&["relation_id","label","waterway_type","wikidata_id","side"])}))?["receiver"].clone(); + prune(&mut branches, json!([]), Some(index))?; + } + } + if waterbody.is_null() && !has_formation && donor.is_null() { + donor = state["source_continuation_candidate"].clone(); + } + let empty = crate::raw::Tags::new(); + let mut description=execute("--source-description",json!({"schema_version":21,"source_node_id":source, + "node_tags":data.node_tags.get(&source).unwrap_or(&empty),"source_waterbody":if waterbody.is_null(){Value::Null}else{fields(&waterbody,&["object_type","osm_id","name","kind","wikidata_id"])},"has_source_branches":has_formation}))?["source"].clone(); + events.extend(array(&state["projected_events"])?.iter().cloned()); + let mut identities = serde_json::Map::new(); + for row in array(&c.way_river_ids)? { + identities.insert(id(&row["way_id"])?.to_string(), row["river_id"].clone()); + } + let mut mouth_receiver = state["mouth_receiver"].clone(); + let compact_receiver = |v: &Value| { + if v.is_null() { + Value::Null + } else { + fields( + v, + &[ + "object_type", + "osm_id", + "name", + "wikidata_id", + "river_id", + "connection_kind", + ], + ) + } + }; + let plan = execute( + "--model-finalize", + json!({"schema_version":35,"mode":"finalize","donor":compact_receiver(&donor),"mouth":compact_receiver(&mouth_receiver), + "has_waterbody":!waterbody.is_null(),"has_formation":has_formation,"identities":identities, + "events":events.iter().map(|e|fields(e,&["km","object_type","osm_id"])).collect::>(), + "branches":branches.iter().map(|b|fields(b,&["way_id","way_ids","relation_id","river_id","wikidata_id","junction_km"])).collect::>()}), + )?; + if !plan["mouth_update"].is_null() { + mouth_receiver["river_id"] = plan["mouth_update"]["river_id"].clone(); + } + for update in array(&plan["branch_updates"])? { + let index = update["index"] + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .ok_or("invalid branch update index")?; + branches + .get_mut(index) + .ok_or("unknown branch update index")?["river_id"] = update["river_id"].clone(); + } + if !plan["source_override"].is_null() { + description = plan["source_override"].clone(); + } + let mut terminal = context.clone(); + if let Some(object) = terminal.as_object_mut() { + for key in ["way_ids", "all_parent_way_ids", "route"] { + object.remove(key); + } + } + let mut metadata = json!({"main_way_count":array(&state["graph"]["main_way_ids"])?.len(),"terminal_parent_connection":terminal, + "terminal_connection_diagnostics":state["terminal_diagnostics"],"underground_main_sections":state["underground_main_sections"], + "node_count":array(&state["graph"]["node_order"])?.len(),"edge_count":array(&state["graph"]["edges"])?.len(), + "suppressed_mouth_way_ids":state["suppressed_mouth_way_ids"],"unresolved_side_stream_components":state["unresolved_side_stream_components"], + "source_waterbody_candidates":array(&state["source_waterbody_candidates"])?.iter().map(|v|fields(v,&["object_type","osm_id","name","kind"])).collect::>(), + "source_formation_candidates":formation["candidates"],"source_formation_rejected_reason":formation["rejected_reason"]}); + if !array(&state["incomplete_side_stream_paths"])?.is_empty() { + metadata["incomplete_side_stream_paths"] = state["incomplete_side_stream_paths"].clone(); + } + let distances = array(&state["positions"]["distances_m"])?; + let identity = state["river_id"] + .as_str() + .ok_or("missing final river identity")?; + let mut model = json!({"wikidata_id":identity,"name":state["river_name"],"mouth_node_id":mouth,"source_node_id":source, + "main_length_km":number(distances.last().ok_or("empty final distances")?)?/1000.,"main_path":path, + "events":ordered(&events,&plan["event_order"] )?,"branches":ordered(&branches,&plan["branch_order"] )?, + "mouth_receiver":mouth_receiver,"source_waterbody":waterbody,"source_donor":donor,"source_kind":plan["source_kind"], + "source_branches":formation["source_branches"],"passages":state["passages"],"metadata":metadata,"source":description}); + if identity.starts_with(['R', 'W']) { + model["river_id"] = json!(identity); + model["wikidata_id"] = Value::Null; + } + state["model"] = model; + Ok(state) +} diff --git a/rust/catalogue-geometry/src/worker_protocol.rs b/rust/catalogue-geometry/src/worker_protocol.rs index 14009b81..a7104193 100644 --- a/rust/catalogue-geometry/src/worker_protocol.rs +++ b/rust/catalogue-geometry/src/worker_protocol.rs @@ -63,6 +63,12 @@ enum Operation { casefold: HashMap, whitespace: String, }, + DatasetModelFinalize { + key: String, + model_key: String, + configuration: crate::model_complete::Configuration, + save_as: String, + }, DatasetModelBranches { key: String, model_key: String, @@ -456,6 +462,17 @@ pub(crate) fn serve(limit: usize) -> Result<(), String> { }); result.and_then(|value| store.result(value, Some(save_as), false)) } + Operation::DatasetModelFinalize { + key, + model_key, + configuration, + save_as, + } => { + let result = store.with_model(&key, &model_key, |data, state| { + crate::model_complete::build(data, state, configuration) + }); + result.and_then(|value| store.result(value, Some(save_as), false)) + } Operation::DatasetModelBranches { key, model_key, diff --git a/src/riverfahrplan/worker_session.py b/src/riverfahrplan/worker_session.py index 185b49fe..9f5b1eba 100644 --- a/src/riverfahrplan/worker_session.py +++ b/src/riverfahrplan/worker_session.py @@ -154,6 +154,12 @@ def dataset_model_features(self,key,model_key,*,save_as,timeout=300): 'way_rules':WAY_EVENT_RULES,'relation_rules':STRUCTURE_EVENT_RULES, 'whitespace':unicode_name_contract()[1]}},timeout=timeout) + def dataset_model_finalize(self,key,model_key,*,save_as,way_river_ids=None,timeout=300): + from .catalogue_rust import unicode_name_contract + return self.operation({'op':'dataset_model_finalize','key':key,'model_key':model_key,'save_as':save_as, + 'configuration':{'schema_version':81,'casefold':unicode_name_contract()[0], + 'way_river_ids':[{'way_id':way_id,'river_id':river_id} for way_id,river_id in (way_river_ids or {}).items()]}},timeout=timeout) + def dataset_model_branches(self,key,model_key,*,save_as,timeout=300): from .main_path_rust import id_order_contract from .catalogue_rust import unicode_name_contract diff --git a/tests/test_model_complete_rust.py b/tests/test_model_complete_rust.py new file mode 100644 index 00000000..0b5af096 --- /dev/null +++ b/tests/test_model_complete_rust.py @@ -0,0 +1,172 @@ +"""Full neutral RiverModel parity from retained PBF through finalization.""" +import json +import pytest +from riverfahrplan import hydrology +from riverfahrplan.graph import build_graph +from riverfahrplan.model import RiverModel +from riverfahrplan.osm import OsmDataset,OsmNode,OsmWay,OsmRelation +from riverfahrplan.pbf import load_pbf_dataset,REGIONAL_FILTER_EXPRESSIONS +from riverfahrplan.worker_session import RustWorkerSession +from test_graph_rust import worker,osmium,pbf_fixtures,ROOT,reference +from test_canal_orientation_rust import data as canal_data,CASES as CANAL_CASES +from test_direct_branches_rust import data as direct_data,CASES as DIRECT_CASES +from test_side_point_events_rust import side_data +from test_transfer_donor_rust import full_dataset +from test_graph_hydrology import _source_formation_data + + +def compare(source,identity,worker,osmium,monkeypatch,identities=None): + data=load_pbf_dataset(source,osmium,REGIONAL_FILTER_EXPRESSIONS) + expected=hydrology.build_river_model(data,build_graph(data,identity),identity,way_river_ids=identities).as_dict() + def forbidden(*a,**k):raise AssertionError('Python model/source/finalization algorithm called') + for target in ['riverfahrplan.hydrology.build_river_model','riverfahrplan.sources.find_source_formation_python', + 'riverfahrplan.sources.describe_source_python','riverfahrplan.hydrology.terminal_diversion_donor_python', + 'riverfahrplan.model_finalize.plan_python','riverfahrplan.model_finalize.prune_branches_python', + 'riverfahrplan.model_finalize.donor_python','riverfahrplan.hydrology._find_source_continuation_python']: + monkeypatch.setattr(target,forbidden) + monkeypatch.setattr(hydrology.GEOD,'inv',forbidden) + with RustWorkerSession(worker) as s: + s.import_pbf('data',[source],osmium_command=osmium) + s.dataset_model_start('data',identity,save_as='model') + for stage in ['features','connections','transfers','side_networks','branches']: + getattr(s,'dataset_model_'+stage)('data','model',save_as='model') + before=s.get('model',pointer='/branches') + result=s.dataset_model_finalize('data','model',save_as='final',way_river_ids=identities) + assert set(result)=={'retained'} + actual=s.get('final',pointer='/model') + assert actual==expected + assert RiverModel.from_dict(actual).as_dict()==expected + assert s.get('model',pointer='/branches')==before + with pytest.raises(ValueError,match='pointer'):s.get('model',pointer='/model') + assert s.dataset_model_finalize('data','final',save_as='final',way_river_ids=identities)==result + assert s.get('final',pointer='/model')==expected + return actual + + +@pytest.mark.parametrize('name,filename,identity,old',reference.CASES) +def test_frozen_models(name,filename,identity,old,worker,osmium,tmp_path,monkeypatch): + d=reference.load_case(filename,old) + if name=='equal_paths':del d.ways[13] + source=pbf_fixtures.make_pbf(d.to_overpass_json(),tmp_path/'input.pbf',osmium) + compare(source,identity,worker,osmium,monkeypatch) + + +@pytest.mark.parametrize('case',CANAL_CASES) +def test_terminal_priorities(case,worker,osmium,tmp_path,monkeypatch): + source=pbf_fixtures.make_pbf(canal_data(case).to_overpass_json(),tmp_path/'input.pbf',osmium) + compare(source,'Q2',worker,osmium,monkeypatch) + + +@pytest.mark.parametrize('case',[c for c in DIRECT_CASES if c not in {'lost_segment','foreign_membership','mouth_incomplete'}]) +def test_direct_branch_finalization(case,worker,osmium,tmp_path,monkeypatch): + source=pbf_fixtures.make_pbf(direct_data(case).to_overpass_json(),tmp_path/'input.pbf',osmium) + compare(source,'Q1',worker,osmium,monkeypatch) + + +@pytest.mark.parametrize('case',['base','reversed','same_name']) +def test_full_span_donor(case,worker,osmium,tmp_path,monkeypatch): + source=pbf_fixtures.make_pbf(full_dataset(case).to_overpass_json(),tmp_path/'input.pbf',osmium) + actual=compare(source,'QMAIN',worker,osmium,monkeypatch) + if case=='base':assert actual['source_donor']['osm_id']==900 and not actual['branches'] + + +@pytest.mark.parametrize('case',['base','one','unnamed','target_name','folded','unicode','relation_identity','destination', + 'spring','hot_spring','named','waterbody','waterbody_spring','partial_identity','all_identity','empty_identity','null_identity']) +def test_source_formation_and_priorities(case,worker,osmium,tmp_path,monkeypatch): + d=OsmDataset();d.merge_json(_source_formation_data()) + if case=='one':del d.ways[300] + if case=='unnamed':d.ways[200].tags.pop('name');d.relations[901].tags.pop('name',None) + if case=='target_name':d.ways[200].tags['name']='Oker';d.relations[901].tags['name']='Oker' + if case=='folded': + for wid,rid,name in [(200,901,'Straße'),(300,902,'STRASSE')]: + d.ways[wid].tags['name']=name;d.relations[rid].tags['name']=name + if case=='unicode': + for wid,rid,name in [(200,901,'Ä'),(300,902,'A\u0308')]: + d.ways[wid].tags['name']=name;d.relations[rid].tags['name']=name + if case=='relation_identity':d.relations[901].tags['wikidata']='QOKER' + if case=='destination':d.relations[901].tags['destination']='Oker' + if case in {'spring','hot_spring','named','waterbody','waterbody_spring'}: + del d.ways[300];del d.ways[200] + d.nodes[2].tags={'natural':'hot_spring' if case=='hot_spring' else 'spring','name':'Quellname','spring:type':'artesian','wikidata':'QSPRING'} + if case=='named':d.nodes[2].tags.pop('natural') + if case in {'waterbody','waterbody_spring'}: + for n,(x,y) in {500:(9.999,50.009),501:(10.001,50.009),502:(10.001,50.011),503:(9.999,50.011)}.items():d.nodes[n]=OsmNode(n,x,y) + d.ways[500]=OsmWay(500,[500,501,502,503,500],{'natural':'water','water':'pond','name':'Quellteich'}) + identities=None + if case in {'partial_identity','all_identity','empty_identity','null_identity'}: + d.relations.pop(901);d.relations.pop(902) + identities={200:{'empty_identity':'','null_identity':None}.get(case,'W200')} + if case=='all_identity':identities[300]='W300' + source=pbf_fixtures.make_pbf(d.to_overpass_json(),tmp_path/'input.pbf',osmium) + actual=compare(source,'QOKER',worker,osmium,monkeypatch,identities) + if case=='base':assert actual['source_kind']=='confluence' and len(actual['source_branches'])==2 + if case=='spring':assert actual['source']['kind']=='spring' + if case=='waterbody':assert actual['source_kind']=='waterbody' + + +@pytest.mark.parametrize('mapping',[{}, {204:'W204',212:'W212'},{204:'',212:None}]) +@pytest.mark.parametrize('fork',[False,True]) +def test_side_features_and_identity_enrichment(mapping,fork,worker,osmium,tmp_path,monkeypatch): + source=pbf_fixtures.make_pbf(side_data(fork).to_overpass_json(),tmp_path/'input.pbf',osmium) + compare(source,'QTEST',worker,osmium,monkeypatch,mapping) + + +@pytest.mark.parametrize('seed',range(20)) +def test_generated_full_models(seed,worker,osmium,tmp_path,monkeypatch): + from test_model_side_networks_rust import topology_data + import random + rng=random.Random(seed);d=topology_data('empty');nodes=[1,2,3,*range(10,16)] + for n in nodes:d.nodes[n]=OsmNode(n,10+rng.random()*.01,51+rng.random()*.01) + edges=[(a,b) for a in nodes for b in nodes if a!=b and rng.random()<.18] + for wid,(a,b) in zip(rng.sample(range(1000,10000),len(edges)),edges):d.ways[wid]=OsmWay(wid,[a,b],{'waterway':'stream','name':'Side'}) + source=pbf_fixtures.make_pbf(d.to_overpass_json(),tmp_path/'input.pbf',osmium) + compare(source,'QMAIN',worker,osmium,monkeypatch) + + +@pytest.mark.parametrize('case',['base','none','source_start','source_interior','source_repeated','pressure', + 'source_competitor','repeated_mouth','right_bank','collinear','missing_downstream','relation','relation_match', + 'relation_qid','relation_name','relation_numeric','empty_metadata','way_name_priority','way_kind_priority', + 'way_id_map','empty_id_map','no_wikidata','coastline','water_area','unknown_linear','unnamed','same_id','large_id']) +def test_directed_continuation_and_receiver(case,worker,osmium,tmp_path,monkeypatch): + from test_endpoint_connections_rust import case_data + d,_,_,_,mapping=case_data(case) + if case=='large_id': + # osmium's PBF index cannot address the kernel fixture's 2**60 ID. + way=d.ways.pop(2**60);way.osm_id=9007199254740993;d.ways[way.osm_id]=way + source=pbf_fixtures.make_pbf(d.to_overpass_json(),tmp_path/'input.pbf',osmium) + actual=compare(source,'QTEST',worker,osmium,monkeypatch,mapping) + if case=='way_id_map':assert actual['source_donor']['river_id']=='WUP' + + +@pytest.mark.parametrize('failure',['replace','missing_dataset','missing_model','schema','collision','bad_state','missing_branches','identities','duplicate_identity','casefold','bad_point','bad_connections']) +def test_errors_preserve_existing_model(failure,worker,osmium,tmp_path): + source=pbf_fixtures.make_pbf(side_data(True).to_overpass_json(),tmp_path/'input.pbf',osmium) + with RustWorkerSession(worker) as s: + s.import_pbf('data',[source],osmium_command=osmium) + s.dataset_model_start('data','QTEST',save_as='prefix') + for stage in ['features','connections','transfers','side_networks']: + getattr(s,'dataset_model_'+stage)('data','prefix',save_as='prefix') + s.dataset_model_branches('data','prefix',save_as='branches') + s.dataset_model_finalize('data','branches',save_as='final') + before=s.get('final',pointer='/model') + if failure=='replace':s.import_pbf('data',[source],osmium_command=osmium) + model='prefix' if failure=='missing_branches' else 'branches' + if failure=='bad_state':s.put('bad',{'schema_version':1,'dataset_snapshot':s.get('branches',pointer='/dataset_snapshot')});model='bad' + if failure in {'bad_point','bad_connections'}: + state=s.get('branches') + if failure=='bad_point':state['events'][0].pop('node_id') + else:state['branches'][0]['connections']=None + s.put('bad',state);model='bad' + original=s.operation;captured=[] + s.operation=lambda operation,**kwargs:captured.append(operation) + s.dataset_model_finalize('data',model,save_as='final');s.operation=original + operation=captured[0];config=operation['configuration'] + if failure=='missing_dataset':operation['key']='missing' + if failure=='missing_model':operation['model_key']='missing' + if failure=='collision':operation['save_as']='data' + if failure=='schema':config['schema_version']=0 + if failure=='identities':config['way_river_ids']=[{'way_id':True,'river_id':'W1'}] + if failure=='duplicate_identity':config['way_river_ids']=[{'way_id':204,'river_id':'W1'}]*2 + if failure=='casefold':config['casefold']={'ab':'x'} + with pytest.raises(ValueError):s.operation(operation) + assert s.get('final',pointer='/model')==before From cc27e227f182f9994b6d73fe11543c1d80b53b21 Mon Sep 17 00:00:00 2001 From: thorsten Date: Fri, 16 Oct 2026 10:22:22 +0200 Subject: [PATCH 2/2] Record full retained model validation and remaining driver integration --- ...model-finalization-reference-20261016.json | 48 +++++++++++++++++++ docs/native-model-finalization-migration.md | 18 +++++-- 2 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 docs/migration-proofs/native-model-finalization-reference-20261016.json diff --git a/docs/migration-proofs/native-model-finalization-reference-20261016.json b/docs/migration-proofs/native-model-finalization-reference-20261016.json new file mode 100644 index 00000000..efcb4b1c --- /dev/null +++ b/docs/migration-proofs/native-model-finalization-reference-20261016.json @@ -0,0 +1,48 @@ +{ + "date": "2026-10-16", + "parent_commit": "feccf32cc34c534ce24c76863313c8f762dfdf8b", + "source_commit": "0c4ac962fdbf1c937f836197e69b2ab04bf229f2", + "source_tree": "562bfd0a63e6888d3341029a1c768ddcb6ce34a6", + "source_sha256": { + "rust/catalogue-geometry/src/main.rs": "0efccf78a1e5223d4ecea19d5fd93f300cbe7d93e5da87b37a1817e5b710b668", + "rust/catalogue-geometry/src/model_complete.rs": "5fb6d8d77c3c59fc884e5afccf3c6aa4d6d289d0db3758fe15f01e32f64a8a66", + "rust/catalogue-geometry/src/worker_protocol.rs": "0caa9482bcebee8461ffc75317ebdb9f1456c3635bd43e7c1b648222d5ea1139", + "src/riverfahrplan/worker_session.py": "2ef7f1e877dc151d3aded8b0940a8e6d691d662cbbe2c84abf46cd8615593a2a", + "tests/test_model_complete_rust.py": "7da3f312cc5976eaed85a5b5d85e228fba873c83ec258833460aabc12c2bf86d" + }, + "release_worker_sha256": "73f69daffb57b8907b8c5db288f82283a66ea3da83c9baa93d55c0852a04861d", + "composition": [ + "named source formations and consumed branches", + "terminal parent and full-span side-network donors", + "directed source continuation with final identity mapping", + "source description and precedence", + "stable events and branches", + "identity enrichment and complete neutral model metadata" + ], + "limits": [ + "Python remains default; normal driver still uses existing adapters.", + "Public native entrypoint and model/regional/CLI integration remain open.", + "Internal JSON copies remain; no performance or hard RSS guarantee.", + "Large real-world PBF/time/RSS acceptance remains outstanding." + ], + "github_ci": { + "run": 38872738687, + "result": "failed before runner allocation", + "all_runner_ids": 0, + "executed_steps": 0 + }, + "validation": { + "full_python_integration_tests": 9378, + "full_suite_worker_profile": "debug", + "full_suite_seconds": 280.22, + "release_targeted_tests": 1290, + "release_targeted_seconds": 81.55, + "new_retained_complete_model_cases": 132, + "rust_tests": 35, + "rustfmt": true, + "clippy_deny_warnings_all_targets": true, + "debug_build": true, + "release_build": true, + "installed_wheel_four_full_models_debug_and_release": true + } +} diff --git a/docs/native-model-finalization-migration.md b/docs/native-model-finalization-migration.md index b93dcf6a..0cc56890 100644 --- a/docs/native-model-finalization-migration.md +++ b/docs/native-model-finalization-migration.md @@ -27,7 +27,7 @@ Zwischenfelder bleiben als reproduzierbare Eingabe erhalten, sodass dieselbe Fortsetzung auch auf ihrem eigenen Ergebnis wiederholbar bleibt. Datensatz- revisionen und atomare Ergebnisablage nutzen den vorhandenen Worker-Vertrag. -Die neuen PBF-Vergleichsfälle prüfen das gesamte Modell gegen den normalen +132 neue PBF-Vergleichsfälle prüfen das gesamte Modell gegen den normalen Python-Treiber, einschließlich Quellbildung und -veto, Wasserflächen-/Quell- Priorität, Quellen und benannten Punkten, Spenderauswahl, Fortsetzungsrichtungen, Relationsrang, leeren und nachgereichten IDs, @@ -44,5 +44,17 @@ stehen weiter aus. ## Prüfstand -Die abschließenden Debug-/Release-Prüfzahlen und der Quellnachweis folgen nach -dem vollständigen Prüflauf. +9.378 vollständige Python-/Integrationstests mit frischem Debug-Worker und +osmium sowie 1.290 gezielte Tests mit frischem Release-Worker bestehen. +35 Rust-Tests, rustfmt und Clippy mit `-D warnings` für alle Targets bestehen. +Ein separat installiertes Wheel vergleicht vier vollständige Modelle nach der +gesamten nativen Verkettung: Quellzusammenfluss, Speisekanal-Spender, +Seitenmerkmale/Alternativroute und synthetische Relationsidentität. Diese +Vergleiche bestehen mit Debug- und Release-Worker. + +Der Quellnachweis steht unter +`migration-proofs/native-model-finalization-reference-20261016.json`. +GitHub-CI scheitert erneut vor Runnerzuweisung: Im Lauf 38872738687 haben +alle fünf Jobs `runner_id=0` und keine ausgeführten Schritte. Die Ursache ist +aus diesen Jobdaten nicht bestimmbar. Lokale Prüfungen ersetzen keine +erfolgreiche GitHub-CI; der PR bleibt Draft.