From e51510a1159a2205d0b5cc1a55ce141ed6f12544 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 06:56:02 +0000 Subject: [PATCH 1/2] Strict latency contracts: big late-game customers who pay for a latency SLA (#137) From customer level 7, low-latency wholesale routes ask for 1.6 or 3.2 Tbps between two cities with the latency limit trading links already have (REQS.lat on the circuit latency compute() measures). They pay about three times a hyperscaler DCI per Gbps on the same route, never grow past 3.2 Tbps, and every day over the limit after the provisioning grace credits a day's fee and costs extra patience. New rule F9 in gameplay-rules. --- .claude/skills/gameplay-rules/SKILL.md | 1 + CHANGELOG.md | 1 + site/i18n/de.js | 6 +- site/i18n/es.js | 6 +- site/i18n/fr.js | 6 +- site/i18n/it.js | 6 +- site/i18n/pt.js | 6 +- src/game/40-progress/10-businesses.js | 6 +- src/game/60-features/38-latency-contracts.js | 25 +++ src/game/80-simulation/50-sanitize.js | 2 +- .../80-simulation/70-customers-and-events.js | 2 +- .../80-simulation/75-customer-lifecycle.js | 3 +- src/game/88-days/10-day-tick.js | 6 +- src/i18n/en.js | 6 +- tests/gameplay-rules.test.js | 24 +++ tests/latency-contracts.test.js | 162 ++++++++++++++++++ 16 files changed, 255 insertions(+), 13 deletions(-) create mode 100644 src/game/60-features/38-latency-contracts.js create mode 100644 tests/latency-contracts.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index d6fba4b..f1a5bee 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -72,6 +72,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). | | F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). | | F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. | +| F9 | A strict latency contract (`BIZ_T.lowlat`, #137) comes only from customer level 7, is 1.6T or 3.2T and never grows past 3.2T, has a latency limit something you can build meets (`latMaxOf`, as trading links), pays more per Gbps than any other big circuit on the same route even with all their extras, and once its 15-day grace is over credits a day's fee and loses patience faster for every day over its limit. | Real low-latency routes sell at a premium for guaranteed milliseconds and pay service credits when they miss; the cap keeps one contract from carrying a level. | ## DDoS diff --git a/CHANGELOG.md b/CHANGELOG.md index 744dfae..124425f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137). - A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). ## [3.3.0] — 2026-11-09 diff --git a/site/i18n/de.js b/site/i18n/de.js index 5402b72..b0339b6 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -407,7 +407,6 @@ "broker.win_text":"{name} (AS{asn}) hat in {days} Tagen eigene Kabel auf {n} Kontinente verlegt und verkauft anderen Carriern Kapazität für {mo} im Monat. Die Ozeane sind jetzt dein Graben.", "broker.won_on_date":"Gewonnen am {date}: Deine eigenen Kabel überspannen die Ozeane, und Carrier zahlen dir für ihre Nutzung.", "broker.your_glass_gear_is_already_yours":"Als Kabelmakler gehören dir jede Fiber, jedes Leitungssystem, jede Optik, jedes Seekabel und die Router, um sie zu beleuchten, schon jetzt, egal was das Level sagt.", -"businesses.a_free_pni_with_voda_phony":"Ein kostenloser PNI mit Voda-Phony. Hardware: Absolute-Unit-3.2T-Router, 3.2T-Ports und 12.8T-Waves.", "businesses.agi_lab_allegedly":"AGI-Labor (angeblich)", "businesses.agi_labs_allegedly_wanting_ai_wans":"AGI-Labore (angeblich), die KI-WANs mit 12,8 bis 25,6 Tbps wollen, und kostenlose PNIs mit Du-opoly und Ooh-redoo. Hardware: Mikrowtik-CCR-3.2T-Router.", "businesses.ai_gpu_data_center":"KI-GPU-Rechenzentrum", @@ -436,6 +435,8 @@ "businesses.hundreds_of_fiber_pairs":"Hunderte Faserpaare", "businesses.internet_weather_system":"Internet-Wettersystem", "businesses.it_s_not_dns_there_s":"Es ist nicht DNS. Auf keinen Fall ist es DNS. Es war DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Low-Latency-Wholesale-Routen (ab 1.6T, mit Latenz-SLA) und ein kostenloser PNI mit Voda-Phony. Hardware: Absolute-Unit-3.2T-Router, 3.2T-Ports und 12.8T-Waves.", +"businesses.low_latency_wholesale_route":"Low-Latency-Wholesale-Route", "businesses.mars_mission_ground_station":"Bodenstation für die Marsmission", "businesses.mars_mission_ground_stations_gear":"Bodenstationen für die Marsmission. Hardware: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Mars-Mission über deine Pies", @@ -2656,6 +2657,9 @@ "keys.show_this_list":"Diese Liste zeigen", "keys.space":"Leertaste", "keys.zoom_the_map_out_or":"Karte heraus- oder hineinzoomen", +"latency_contracts.credits_paid":"{price} an SLA-Gutschriften gezahlt", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} läuft mit {ms} ms, über den {max} ms aus dem Vertrag. Jeder Tag darüber kostet dich eine Tagesgebühr an SLA-Gutschriften ({price}).", +"latency_contracts.sla_terms":"Latenz-SLA {ms} ms: eine Tagesgebühr zurück für jeden Tag darüber · nie mehr als {max}", "lease_swaps.cap_fabric_circuit":"{cap}-Fabric-Verbindung", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} auf einer Dark-Fiber-IRU", "lease_swaps.cap_wave":"{cap}-Wave", diff --git a/site/i18n/es.js b/site/i18n/es.js index feaa272..c4bdb73 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) tendió sus propios cables hasta {n} continentes y vende {mo} al mes de capacidad a otros operadores, en {days} días. Los océanos son ahora tu zanja.", "broker.won_on_date":"Ganado el {date}: tus propios cables cruzan los océanos y los operadores te pagan por usarlos.", "broker.your_glass_gear_is_already_yours":"Como bróker de cables, toda la fibra, los sistemas de línea, los ópticos, los cables submarinos y los routers para iluminarlos ya son tuyos, diga lo que diga el nivel.", -"businesses.a_free_pni_with_voda_phony":"Un PNI gratis con Voda-Phony. Equipo: routers Absolute Unit 3.2T, puertos de 3.2T y ondas de 12.8T.", "businesses.agi_lab_allegedly":"Laboratorio de AGI (supuestamente)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratorios de AGI (supuestamente) que quieren WAN de IA de 12.8 a 25.6 Tbps, y PNIs gratis con Du-opoly y Ooh-redoo. Equipo: routers Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Centro de datos de GPU para IA", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Cientos de pares de fibra", "businesses.internet_weather_system":"Sistema meteorológico de internet", "businesses.it_s_not_dns_there_s":"No es el DNS. Imposible que sea el DNS. Era el DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Rutas mayoristas de baja latencia (desde 1.6T, con SLA de latencia) y un PNI gratis con Voda-Phony. Equipo: routers Absolute Unit 3.2T, puertos de 3.2T y ondas de 12.8T.", +"businesses.low_latency_wholesale_route":"Ruta mayorista de baja latencia", "businesses.mars_mission_ground_station":"Estación terrestre de misión a Marte", "businesses.mars_mission_ground_stations_gear":"Estaciones terrestres de misiones a Marte. Equipo: El Router del Fin del Universo.", "businesses.mars_mission_over_your_pies":"Misión a Marte por tus pies", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Mostrar esta lista", "keys.space":"Espacio", "keys.zoom_the_map_out_or":"Alejar o acercar el mapa", +"latency_contracts.credits_paid":"{price} pagados en créditos SLA", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} va a {ms} ms, por encima de los {max} ms del contrato. Cada día por encima te cuesta un día de cuota en créditos SLA ({price}).", +"latency_contracts.sla_terms":"SLA de latencia {ms} ms: un día de cuota devuelto por cada día por encima · nunca más de {max}", "lease_swaps.cap_fabric_circuit":"Circuito de fabric de {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} en una IRU de fibra oscura", "lease_swaps.cap_wave":"Onda de {cap}", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f971279..0b0b12e 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) a posé ses propres câbles jusqu’à {n} continents et vend {mo} de capacité par mois à d’autres opérateurs, en {days} jours. Les océans sont ta tranchée maintenant.", "broker.won_on_date":"Gagné le {date} : tes propres câbles traversent les océans, et les opérateurs te paient pour s’en servir.", "broker.your_glass_gear_is_already_yours":"En courtier en câbles, toute la fibre, les systèmes de ligne, les optiques, les câbles sous-marins et les routeurs pour les allumer sont déjà à toi, quoi que dise le niveau.", -"businesses.a_free_pni_with_voda_phony":"Un PNI gratuit avec Voda-Phony. Matos : routeurs Absolute Unit 3.2T, ports 3.2T et longueurs d’onde 12.8T.", "businesses.agi_lab_allegedly":"Labo d’AGI (soi-disant)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Des labos d’AGI (soi-disant) qui veulent des WAN IA de 12,8 à 25,6 Tbps, et des PNI gratuits avec Du-opoly et Ooh-redoo. Matos : routeurs Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Datacenter GPU pour l’IA", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Des centaines de paires de fibre", "businesses.internet_weather_system":"Météo d’Internet", "businesses.it_s_not_dns_there_s":"Ce n’est pas le DNS. Impossible que ce soit le DNS. C’était le DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Des routes de gros à faible latence (à partir de 1.6T, avec SLA de latence), et un PNI gratuit avec Voda-Phony. Matos : routeurs Absolute Unit 3.2T, ports 3.2T et longueurs d’onde 12.8T.", +"businesses.low_latency_wholesale_route":"Route de gros à faible latence", "businesses.mars_mission_ground_station":"Station sol de mission martienne", "businesses.mars_mission_ground_stations_gear":"Stations sol de missions martiennes. Matos : The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Mission martienne via tes pies", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Afficher cette liste", "keys.space":"Espace", "keys.zoom_the_map_out_or":"Dézoomer ou zoomer la carte", +"latency_contracts.credits_paid":"{price} versés en crédits SLA", +"latency_contracts.over_sla":"{name} : {a} ⇄ {b} tourne à {ms} ms, au-delà des {max} ms du contrat. Chaque jour au-dessus te coûte une journée de facture en crédits SLA ({price}).", +"latency_contracts.sla_terms":"SLA de latence {ms} ms : une journée de facture remboursée par jour au-dessus · jamais plus de {max}", "lease_swaps.cap_fabric_circuit":"circuit fabric {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} sur un IRU de fibre noire", "lease_swaps.cap_wave":"longueur d’onde {cap}", diff --git a/site/i18n/it.js b/site/i18n/it.js index 9034753..e95b6a2 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) ha posato i propri cavi fino a {n} continenti e vende {mo} al mese di capacità ad altri operatori, in {days} giorni. Gli oceani ora sono la tua trincea.", "broker.won_on_date":"Vinto il {date}: i tuoi cavi attraversano gli oceani e gli operatori ti pagano per usarli.", "broker.your_glass_gear_is_already_yours":"Da broker di cavi, ogni fibra, sistema di linea, ottica, cavo sottomarino e i router per accenderli sono già tuoi, qualunque cosa dica il livello.", -"businesses.a_free_pni_with_voda_phony":"Un PNI gratuito con Voda-Phony. Gear: router Absolute Unit 3.2T, porte 3.2T e wave 12.8T.", "businesses.agi_lab_allegedly":"Laboratorio AGI (a sentir loro)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratori AGI (a sentir loro) che vogliono AI WAN da 12.8 a 25.6 Tbps, e PNI gratuiti con Du-opoly e Ooh-redoo. Gear: router Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Data center GPU per l’AI", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Centinaia di coppie in fibra", "businesses.internet_weather_system":"Sistema meteorologico di internet", "businesses.it_s_not_dns_there_s":"Non è il DNS. Non può essere il DNS. Era il DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Rotte wholesale a bassa latenza (da 1.6T in su, con SLA di latenza) e un PNI gratuito con Voda-Phony. Gear: router Absolute Unit 3.2T, porte 3.2T e wave 12.8T.", +"businesses.low_latency_wholesale_route":"Rotta wholesale a bassa latenza", "businesses.mars_mission_ground_station":"Stazione di terra per una missione su Marte", "businesses.mars_mission_ground_stations_gear":"Stazioni di terra per missioni su Marte. Gear: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Missione su Marte via i tuoi pie", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Mostra questo elenco", "keys.space":"Spazio", "keys.zoom_the_map_out_or":"Zoom indietro o avanti sulla mappa", +"latency_contracts.credits_paid":"{price} pagati in crediti SLA", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} viaggia a {ms} ms, oltre i {max} ms del contratto. Ogni giorno sopra ti costa un giorno di canone in crediti SLA ({price}).", +"latency_contracts.sla_terms":"SLA di latenza {ms} ms: un giorno di canone restituito per ogni giorno sopra · mai più di {max}", "lease_swaps.cap_fabric_circuit":"circuito fabric da {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} su una dark fiber IRU", "lease_swaps.cap_wave":"wave da {cap}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 0657f8f..11e4a50 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -405,7 +405,6 @@ "broker.win_text":"{name} (AS{asn}) lançou os próprios cabos até {n} continentes e vende {mo} por mês de capacidade a outras operadoras, em {days} dias. Os oceanos agora são a sua vala.", "broker.won_on_date":"Vencido em {date}: seus próprios cabos cruzam os oceanos e as operadoras pagam para usá-los.", "broker.your_glass_gear_is_already_yours":"Como corretor de cabos, toda fibra, sistema de linha, óptico, cabo submarino e os roteadores para acendê-los já são seus, diga o nível o que disser.", -"businesses.a_free_pni_with_voda_phony":"Um PNI grátis com a Voda-Phony. Gear: routers Absolute Unit 3.2T, portas 3.2T e waves de 12.8T.", "businesses.agi_lab_allegedly":"Laboratório de AGI (supostamente)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratórios de AGI (supostamente) querendo AI WANs de 12.8 a 25.6 Tbps, e PNIs grátis com a Du-opoly e a Ooh-redoo. Gear: routers Mikrowtik CCR 3.2T.", "businesses.ai_gpu_data_center":"Data center de GPU para IA", @@ -434,6 +433,8 @@ "businesses.hundreds_of_fiber_pairs":"Centenas de pares de fibra", "businesses.internet_weather_system":"Sistema meteorológico da internet", "businesses.it_s_not_dns_there_s":"Não é DNS. Não tem como ser DNS. Era DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Rotas atacadistas de baixa latência (a partir de 1.6T, com SLA de latência) e um PNI grátis com a Voda-Phony. Gear: routers Absolute Unit 3.2T, portas 3.2T e waves de 12.8T.", +"businesses.low_latency_wholesale_route":"Rota atacadista de baixa latência", "businesses.mars_mission_ground_station":"Estação terrestre de missão a Marte", "businesses.mars_mission_ground_stations_gear":"Estações terrestres de missões a Marte. Gear: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Missão a Marte pelos seus pies", @@ -2654,6 +2655,9 @@ "keys.show_this_list":"Mostrar esta lista", "keys.space":"Espaço", "keys.zoom_the_map_out_or":"Afastar ou aproximar o mapa", +"latency_contracts.credits_paid":"{price} pagos em créditos de SLA", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} roda a {ms} ms, acima dos {max} ms do contrato. Cada dia acima te custa um dia de mensalidade em créditos de SLA ({price}).", +"latency_contracts.sla_terms":"SLA de latência {ms} ms: um dia de mensalidade devolvido por cada dia acima · nunca mais que {max}", "lease_swaps.cap_fabric_circuit":"circuito de fabric de {cap}", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} numa IRU de dark fiber", "lease_swaps.cap_wave":"wave de {cap}", diff --git a/src/game/40-progress/10-businesses.js b/src/game/40-progress/10-businesses.js index a79314c..dc45c81 100644 --- a/src/game/40-progress/10-businesses.js +++ b/src/game/40-progress/10-businesses.js @@ -28,6 +28,10 @@ const BIZ_T={ pairs:{l:tr('businesses.hundreds_of_fiber_pairs'),opts:[1],rate:0,fiber:true,mega:true,lv:4,names:['A Hyperscaler Who Shall Not Be Named','Planet-Scale AI WAN Team','The Fiber-Hungry Giant','Project Very Long Glass']}, esport:{l:tr('businesses.esports_world_final'),opts:[400,800,1600,3200],rate:0,event:true,lv:5,names:['League of Lag Finals','Counter-Ping Major','Fortnightly World Cup','Dota Two Many Viewers','Rocket Leak Championship','Street Frighter Evo']}, sov:{l:tr('businesses.sovereign_cloud_region'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.6,lv:6,names:['Gaia-Ex Sovereign Cloud','Bundeswolke (Very Secure)','Le Cloud Souverain','Datenschutz Deluxe','Your Data Stays Here, Probably','A Cloud With a Flag on It','Data Residency Is a State of Mind']}, + // Strict latency contracts (#137): a carrier or market-data network buys big capacity on one route with a latency SLA, + // the premium paid for the guaranteed milliseconds (km), credits paid for every day over it (38-latency-contracts.js), + // and never more than max: one customer cannot carry a whole level. + lowlat:{l:tr('businesses.low_latency_wholesale_route'),opts:[1600,3200],max:3200,rate:0,l2:true,lat:true,sla:true,km:2,lv:7,names:['Great Circle Clearing House','Straight Line Settlements','Millisecond Markets Exchange','Photon Arbitrage Partners','Shortest Path Securities','Tick Feed Torrent Co.','Matching Engine Mirror Ltd','Speed-of-Glass Replication','Order Book Express','Consolidated Tape Worm']}, cgame:{l:tr('businesses.cloud_gaming_platform'),gaming:true,opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, metav:{l:tr('common.metaverse_platform'),opts:[1600,3200,6400],rate:35,lv:9,names:['Meh-taverse','Second Second Life','Horizon Worlds Apart','The Oasis (Ready Player Done)','Legs Finally Shipped Inc.','Decentra-landlocked']}, agi:{l:tr('businesses.agi_lab_allegedly'),opts:[12800,25600],rate:0,l2:true,div:true,mega:true,km:0.4,lv:11,names:['Almost General Intelligence Inc.','Superintelligence Pending','The Lab That Said Two More Years','Paperclip Maximizer Labs','Deep Thought Two','Benevolent Overlord Research']}, @@ -49,7 +53,7 @@ const LEVELS=[ {n:tr('common.big_league'),q:tr('businesses.your_mtu_is_9000_on_every'),req:tr('businesses.peak_3_tbps_10_pops_3'),unlock:tr('businesses.ai_training_interconnects_and')}, {n:tr('common.continental_carrier'),q:tr('businesses.your_noc_has_a_chat_channel'),req:tr('businesses.peak_6_tbps_15_pops_4'),era:1.15,unlock:tr('businesses.esports_world_finals_and_the_4k')}, {n:tr('common.transcontinental'),q:tr('businesses.you_joined_the_outages_mailing_list'),req:tr('businesses.peak_9_tbps_and_20_pops'),unlock:tr('businesses.sovereign_cloud_regions_and_a_free')}, - {n:tr('common.global_backbone'),q:tr('businesses.your_asn_now_shows_up_in'),req:tr('businesses.peak_12_tbps_25_pops_5'),unlock:tr('businesses.a_free_pni_with_voda_phony')}, + {n:tr('common.global_backbone'),q:tr('businesses.your_asn_now_shows_up_in'),req:tr('businesses.peak_12_tbps_25_pops_5'),unlock:tr('businesses.low_latency_routes_and_a_free_pni')}, {n:tr('common.packet_empire'),q:tr('businesses.your_maintenance_window_is_2_a'),req:tr('businesses.peak_16_tbps_and_32_pops'),era:1.15,unlock:tr('businesses.cloud_gaming_platforms_and_the_cloud')}, {n:tr('businesses.six_continent_carrier'),q:tr('businesses.somewhere_on_every_continent_a'),req:tr('businesses.peak_21_tbps_40_pops_6'),unlock:tr('businesses.metaverse_platforms_it_finally_took')}, {n:tr('businesses.backbone_of_backbones'),q:tr('businesses.your_routing_table_needs_its_own'),req:tr('businesses.peak_26_tbps_and_50_pops'),era:1.2,unlock:tr('businesses.the_vr_era_eyeballs_want_20')}, diff --git a/src/game/60-features/38-latency-contracts.js b/src/game/60-features/38-latency-contracts.js new file mode 100644 index 0000000..d430c54 --- /dev/null +++ b/src/game/60-features/38-latency-contracts.js @@ -0,0 +1,25 @@ +/* ---------- Strict latency contracts (#137) ---------- + Late in the game, carriers and market-data networks buy 1.6 or 3.2T on one route with a latency SLA, the way real + low-latency wholesale is sold: a premium per Gbps for guaranteed milliseconds, and a service credit for every day the + circuit runs over them. They are an ordinary customer type (BIZ_T.lowlat) with the latency requirement every trading + link has (REQS.lat on R.l2lat, the one-way path latency compute() measures), offered from customer level LC_LV, and + never bigger than BIZ_T.lowlat.max: one contract cannot carry a level on its own. */ +const LC_LV=BIZ_T.lowlat.lv,LC_MOOD=3,LC_GRACE=15; +// Once a day for each customer, from the mood check: a latency customer over its SLA after the provisioning grace is +// credited that day's fee and loses patience faster than for a bandwidth problem alone. Returns that extra mood lost. +function lcBreach(b,d){const T=BIZ_T[b.type];if(!T||!T.sla)return 0; + if(d-(b.since||0)0)||REQS.lat.ok(b)){delete b.lcB;return 0;} + const cr=Math.round(bizMo(b)/monLen(d));S.cash-=cr;b.lcCr=(b.lcCr||0)+cr; + if(!b.lcB){b.lcB=1;const v=R.l2lat[b.id]; + toast(tr('latency_contracts.over_sla',{name:esc(b.name),a:CITY[b.city].name,b:CITY[b.city2].name,ms:isFinite(v)?v.toFixed(1):'∞',max:b.latMax,price:fmt$(cr)}),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);} + return LC_MOOD;} +// The contract, on its offer and customer rows (bRisk()). +function lcNote(b){const T=BIZ_T[b.type];if(!T||!T.sla)return ''; + return `
⏱️ ${tr('latency_contracts.sla_terms',{ms:b.latMax,max:fmtG(T.max)})}${b.lcCr>0?' · '+tr('latency_contracts.credits_paid',{price:fmt$(b.lcCr)}):''}
`;} +// Saves: credits paid and the breach flag are numbers and a flag; a contract is never bigger than its type allows. +function lcSanitize(s){for(const b of [...s.biz,...s.offers]){const T=BIZ_T[b.type]; + if(b.lcCr!==undefined){const v=Math.round(+b.lcCr);if(Number.isFinite(v)&&v>0)b.lcCr=v;else delete b.lcCr;} + if(b.lcB!==undefined){if(b.lcB)b.lcB=1;else delete b.lcB;} + if(T&&T.max)b.bw=Math.min(T.max,Math.max(T.opts[0],b.bw)); + if(T&&T.sla&&Array.isArray(b.reqs)&&!b.reqs.includes('lat'))b.reqs.unshift('lat'); + if(T&&T.sla&&!(b.latMax>0)&&isCity(b.city)&&b.city2&&isCity(b.city2))b.latMax=latMaxOf(b.city,b.city2);}} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index db35e34..7d0d9cd 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -113,7 +113,7 @@ function sanitize(s){ three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */ {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} - specSanitize(s); + specSanitize(s);lcSanitize(s); cmFix(s); pieSanitize(s);pieIncFix(s);volFix(s); if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} diff --git a/src/game/80-simulation/70-customers-and-events.js b/src/game/80-simulation/70-customers-and-events.js index cf037a7..f2a906c 100644 --- a/src/game/80-simulation/70-customers-and-events.js +++ b/src/game/80-simulation/70-customers-and-events.js @@ -5,7 +5,7 @@ function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boole function bHas(o){return !!BIZ_T[o.type].cap||!!BIZ_T[o.type].orbit||bCities(o).every(c=>S.pops[c]);} function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day⚠️ ${tr('customers_and_events.gaming_attracts_attacks')}`:'';} +function bRisk(b){return (BIZ_T[b.type]?.gaming&&!ddosOff()?`
⚠️ ${tr('customers_and_events.gaming_attracts_attacks')}
`:'')+lcNote(b);} function bTerms(o){const T=BIZ_T[o.type];if(T.cap)return capTerms(o); if(T.event){const live=S.day>=o.start;return tr('customers_and_events.bw_extra_for_d_days_when',{bw:fmtG(o.bw),d:o.dur,when:live?tr('customers_and_events.day_n_of_d',{n:S.day-o.start+1,d:o.dur}):tr('customers_and_events.starting_in_n_d',{n:o.start-S.day}),fee:fmt$(o.fee)});} if(T.sdwan)return tr('customers_and_events.n_sites_list_bw_per_site',{n:o.sites.length,list:o.sites.map(c=>CITY[c].name).join(', '),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)}); diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index aa9bc4c..b93f6be 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -59,7 +59,8 @@ function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);} const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ '); // Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. -function clGrow(b){const T=BIZ_T[b.type];if(T.fiber)return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=up||b.bw*2;return true;} +// A type with a most (max) never grows past it (#137). +function clGrow(b){const T=BIZ_T[b.type];if(T.fiber||(T.max&&b.bw>=T.max))return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=T.max?Math.min(T.max,up||b.bw*2):up||b.bw*2;return true;} // Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says. function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))}; if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 572e7ed..f4b3f58 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -69,10 +69,10 @@ function* dayPost(d){ (a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; toast(tr('day_tick.sla_breach_name_the_attack_on',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood - const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b); + const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b),lcX=lcBreach(b,d); if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2); else if(S.day-(b.since||0)<15){} - else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm; + else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0)+lcX);b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm; // An orbit customer served in full but promised more (the shark's full sky) grumbles, and never cancels over it. if(BIZ_T[b.type].orbit&&sf>=0.95&&reachOk)b.mood=Math.max(b.mood,Math.min(b.pm,PIE_GRUMBLE)); if(b.mood<=0){S.biz=S.biz.filter(x=>x!==b);toast(tr('day_tick.name_cancelled_too_many_outages_and',{name:esc(b.name),city:CITY[b.city].name}),'bad');sfx('err');} @@ -134,7 +134,7 @@ function spawnOffer(){ const bk=broker(),dfR=S.links.some(l=>l.kind==='df'&&l.ready<=S.day),dfO=S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day); if(dfR)types.push('wwave','wwave');if(dfO)types.push('dfpair');if(bk){if(dfR)types.push('wwave','wwave','wwave','wwave');if(dfO)types.push('dfpair','dfpair','dfpair');}if(lv>=3)types.push('gpu','gpu','onramp','onramp');if(lv>=4)types.push('ai','ai','hyper','hyper'); if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if((lv>=4||bk)&&dfO)types.push('pairs'); - if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); + if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=LC_LV&&mine.length>=2)types.push('lowlat','lowlat');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor'); // Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. const dense=mine.filter(c=>(CITY_PDB[c]||[])[2]>=2000);if(lv>=2&&dense.length)types.push('isp'); diff --git a/src/i18n/en.js b/src/i18n/en.js index bb7bbc3..10697f3 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -406,7 +406,6 @@ "broker.win_text":"{name} (AS{asn}) laid its own cables onto {n} continents and sells {mo} a month of capacity to other carriers, in {days} days. The oceans are your trench now.", "broker.won_on_date":"Won on {date}: your own cables span the oceans, and carriers pay you to use them.", "broker.your_glass_gear_is_already_yours":"As a Cable broker, every fiber, line system, optic, subsea cable and the routers to light them are yours already, whatever the level says.", -"businesses.a_free_pni_with_voda_phony":"A free PNI with Voda-Phony. Gear: Absolute Unit 3.2T routers, 3.2T ports and 12.8T waves.", "businesses.agi_lab_allegedly":"AGI lab (allegedly)", "businesses.agi_labs_allegedly_wanting_ai_wans":"AGI labs (allegedly) wanting AI WANs of 12.8 to 25.6 Tbps, and free PNIs with Du-opoly and Ooh-redoo. Gear: Mikrowtik CCR 3.2T routers.", "businesses.ai_gpu_data_center":"AI GPU data center", @@ -435,6 +434,8 @@ "businesses.hundreds_of_fiber_pairs":"Hundreds of fiber pairs", "businesses.internet_weather_system":"Internet weather system", "businesses.it_s_not_dns_there_s":"It's not DNS. There's no way it's DNS. It was DNS.", +"businesses.low_latency_routes_and_a_free_pni":"Low-latency wholesale routes (1.6T and up, with a latency SLA), and a free PNI with Voda-Phony. Gear: Absolute Unit 3.2T routers, 3.2T ports and 12.8T waves.", +"businesses.low_latency_wholesale_route":"Low-latency wholesale route", "businesses.mars_mission_ground_station":"Mars mission ground station", "businesses.mars_mission_ground_stations_gear":"Mars mission ground stations. Gear: The Router at the End of the Universe.", "businesses.mars_mission_over_your_pies":"Mars mission over your pies", @@ -2655,6 +2656,9 @@ "keys.show_this_list":"Show this list", "keys.space":"Space", "keys.zoom_the_map_out_or":"Zoom the map out or in", +"latency_contracts.credits_paid":"{price} paid in SLA credits", +"latency_contracts.over_sla":"{name}: {a} ⇄ {b} runs at {ms} ms, over the {max} ms in its contract. Every day over costs you a day's fee in SLA credits ({price}).", +"latency_contracts.sla_terms":"Latency SLA {ms} ms: a day's fee back for every day over it · never more than {max}", "lease_swaps.cap_fabric_circuit":"{cap} fabric circuit", "lease_swaps.cap_on_a_dark_fiber_iru":"{cap} on a dark fiber IRU", "lease_swaps.cap_wave":"{cap} wave", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 44414ca..4352927 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -485,6 +485,30 @@ test('F8: a managed wave costs your own capacity, rides one optic, and is priced assert.deepEqual(g.errors, []); }); +test('F9: a latency contract is late, capped, achievable, paid for its latency and credited when over it (#137)', () => { + const T = J('BIZ_T.lowlat'); + assert.ok(T.lv >= 7, `F9: from customer level 7, not ${T.lv}`); + assert.ok(T.l2 && T.lat && T.sla, 'F9: a circuit with a latency limit and an SLA'); + assert.ok(Math.min(...T.opts) >= 1600 && Math.max(...T.opts) <= T.max && T.max <= 3200, 'F9: 1.6T and up, never past 3.2T'); + assert.equal(ev("(()=>{const x={type:'lowlat',bw:BIZ_T.lowlat.max};return clGrow(x)||x.bw!==BIZ_T.lowlat.max;})()"), false, 'F9: never grows past its most'); + // Per Gbps on the same route, the bare contract beats any other big circuit with every extra it can ask for. + const best = ev("Math.max(...['hyper','ai','aiwan'].map(t=>BIZ_T[t].km))*(1+REQS.diverse.bonus+REQS.metro.bonus+REQS.sharks.bonus+REQS.gen.bonus)"); + assert.ok(T.km > best, `F9: ${T.km} per km-unit against the best other big circuit's ${best}`); + const g = load(); + g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=BIZ_T.lowlat.lv-1;S.biz=[];S.offers=[];for(const c of ['nyc','chi','lon','fra','tok','sin'])if(!S.pops[c])ACT.buildPop({city:c});compute()"); + const spawn = (n) => g.ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();out.push(...S.offers.filter(o=>o.type==='lowlat'));}S.offers=[];return JSON.stringify(out);})()`); + assert.deepEqual(JSON.parse(spawn(400)), [], 'F9: none below its level'); + g.ev('S.lvl=BIZ_T.lowlat.lv'); + const os = JSON.parse(spawn(400)); + assert.ok(os.length > 0, 'F9: offered at its level'); + for (const o of os) assert.ok(g.ev(`Math.min(latFloor('${o.city}','${o.city2}'),bestLat('${o.city}','${o.city2}'))<=${o.latMax}`), `F9: ${o.city}–${o.city2} in ${o.latMax} ms can be built`); + g.ev("S.biz.push({id:'x',type:'lowlat',name:'X',city:'nyc',city2:'chi',bw:1600,rate:100,reqs:['lat'],latMax:0.1,mood:100,since:S.day-30});compute()"); + const cash = g.ev('S.cash'); + assert.equal(g.ev("lcBreach(S.biz.find(b=>b.id==='x'),S.day)"), g.ev('LC_MOOD'), 'F9: over its limit, it loses patience'); + assert.equal(Math.round(cash - g.ev('S.cash')), g.ev('Math.round(1600*100/monLen(S.day))'), "F9: and a day's fee comes back as a credit"); + assert.deepEqual(g.errors, []); +}); + // D1–D4: DDoS as networks see it (#242). tests/ddos-model.test.js plays each one in detail. const ddFra = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.rgen=RG.findIndex(r=>r.fsN===8);S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:10,rate:1,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'D',city:'fra',bw:5,rate:1,mood:80,since:0,reqs:[]});compute()"); const ddHit = (ev, g) => ev(`S.ev.ddos={id:'x',city:'fra',tgt:'g',vec:'dns',gbps:${g},start:S.day,until:S.day+2,bh:false};compute()`); diff --git a/tests/latency-contracts.test.js b/tests/latency-contracts.test.js new file mode 100644 index 0000000..df345f2 --- /dev/null +++ b/tests/latency-contracts.test.js @@ -0,0 +1,162 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Strict latency contracts (#137): big customers who pay for a latency SLA on one route, late in the game. +const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'nyc'})"; +const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};S.pops['${c}'].rgen=RG.length-1;`; +const wave = (id, a, b) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'wave',tier:6,n:1,km:kmBetween('${a}','${b}'),cut:0,mo:0,day:0,ready:0});`; +const CITIES = ['nyc', 'chi', 'ash', 'mia', 'lon', 'fra']; +const net = () => CITIES.map(pop).join('') + wave('nc', 'nyc', 'chi') + wave('na', 'nyc', 'ash') + wave('am', 'ash', 'mia') + wave('mc', 'mia', 'chi') + 'compute();'; +// Spawn n offers, each on its own, and keep them all. +const spawnMany = (ev, n) => JSON.parse(ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();out.push(...S.offers);}S.offers=[];return JSON.stringify(out);})()`)); +// A latency contract on New York ⇄ Chicago, signed long enough ago that its provisioning grace is over. +const sign = (bw = 1600) => `(()=>{const b={id:'lc1',city:'nyc',city2:'chi',name:'Shortest Path Securities',type:'lowlat',bw:${bw},rate:500,reqs:['lat'],latMax:latMaxOf('nyc','chi'),route:'fast',mood:100,since:S.day-30};S.biz.push(b);compute();return b.id;})()`; + +test('#137 latency contracts are offered only from their customer level, sized and priced as promised', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev('S.lvl=LC_LV-1'); + assert.ok(ev('LC_LV') >= 7, 'a late-game customer'); + const early = spawnMany(ev, 600); + assert.equal(early.filter((o) => o.type === 'lowlat').length, 0, 'never below its level'); + ev('S.lvl=LC_LV'); + const late = spawnMany(ev, 600); + const lc = late.filter((o) => o.type === 'lowlat'); + assert.ok(lc.length >= 5, `they call at their level (${lc.length})`); + for (const o of lc) { + assert.ok([1600, 3200].includes(o.bw), 'big: 1.6T or 3.2T'); + assert.equal(o.reqs[0], 'lat', 'always a latency limit'); + assert.equal(o.latMax, ev(`latMaxOf('${o.city}','${o.city2}')`), 'the limit every latency customer gets'); + assert.ok(ev(`Math.min(latFloor('${o.city}','${o.city2}'),bestLat('${o.city}','${o.city2}'))<=${o.latMax}`), 'and one something you can build meets'); + } + // Pay: per Gbps on the same route, above any other high-volume circuit (hyperscaler DCI, AI interconnects), whatever they ask for. + const per = (o) => o.rate / ev(`150+kmBetween('${o.city}','${o.city2}')*0.08`); + const big = late.filter((o) => ['hyper', 'ai', 'aiwan'].includes(o.type)); + assert.ok(big.length >= 5, 'there are other big circuits to compare with'); + assert.ok(Math.min(...lc.map(per)) > Math.max(...big.map(per)), 'a latency contract pays more per Gbps than any other big circuit'); + // Same size, same route: a 1.6T latency contract against a 1.6T hyperscaler DCI with every extra a DCI can ask for. + const o = lc[0], km = ev(`kmBetween('${o.city}','${o.city2}')`); + const dciBest = (150 + km * 0.08) * ev('BIZ_T.hyper.km') * (1 + ev("REQS.diverse.bonus+REQS.metro.bonus+REQS.sharks.bonus+REQS.gen.bonus")); + assert.ok(1600 * o.rate > 1600 * dciBest, 'beats a fully loaded DCI of the same size'); + assert.deepEqual(errors, []); +}); + +test('#137 the latency limit is the circuit latency the game already measures, and breaking it costs credits and the customer', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev('S.lvl=LC_LV'); + ev(sign()); + const b = "S.biz.find(b=>b.id==='lc1')"; + assert.ok(ev(`R.l2lat['lc1']<=${b}.latMax`), 'the direct wave meets it'); + assert.ok(ev(`REQS.lat.ok(${b})`)); + assert.ok(ev(`bizSf(${b})>=0.95`), 'and carries all of it'); + // Cut the direct wave: the circuit reroutes the long way round, still carried in full but too slow. + ev("S.links.find(l=>l.id==='nc').cut=S.day+400;compute()"); + assert.ok(ev(`bizSf(${b})>=0.95`), 'all the bandwidth still arrives'); + assert.ok(ev(`R.l2lat['lc1']>${b}.latMax`), 'over its limit'); + assert.ok(!ev(`REQS.lat.ok(${b})`), 'REQS.lat says so'); + assert.ok(ev(`bizWhy(${b}).some(w=>/latency/i.test(w))`), 'and the customer row says why'); + // A day over: a day's fee back as an SLA credit, and more patience lost than a plain latency customer (HFT) loses. + const cash = ev('S.cash'), mo = ev(`bizMo(${b})`), days = ev('monLen(S.day)'); + const extra = ev(`lcBreach(${b},S.day)`); + assert.equal(extra, ev('LC_MOOD')); + assert.equal(Math.round(cash - ev('S.cash')), Math.round(mo / days), "a day's fee credited"); + assert.equal(ev(`${b}.lcCr`), Math.round(mo / days)); + assert.equal(ev("lcBreach({type:'hft',since:0,latMax:1,city:'nyc',city2:'chi',reqs:['lat'],id:'x'},S.day)"), 0, 'only latency contracts pay credits'); + // In the provisioning grace (rule F1) nothing is credited and nothing is lost. + assert.equal(ev(`(()=>{const x={...${b},id:'lc2',since:S.day-3};return lcBreach(x,S.day);})()`), 0); + // Day after day over the limit: unhappy, warned, and gone, with credits paid every day. + const m0 = ev(`${b}.mood`); + ev('dayTick()'); + const m1 = ev(`${b}.mood`); + assert.ok(m0 - m1 >= 6 - 1e-9, `loses at least 6 a day over its SLA (${m0} → ${m1})`); + let gone = false; + for (let i = 0; i < 40 && !gone; i++) { + ev("S.links.find(l=>l.id==='nc').cut=S.day+400;dayTick()"); + gone = !ev("S.biz.some(b=>b.id==='lc1')"); + } + assert.ok(gone, 'a contract over its latency for weeks cancels'); + assert.deepEqual(errors, []); +}); + +test('#137 a latency contract within its limit stays happy and pays no credits', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev(sign()); + ev("S.biz.find(b=>b.id==='lc1').mood=90"); + for (let i = 0; i < 5; i++) ev("S.links.forEach(l=>l.cut=0);dayTick()"); + const b = ev("JSON.stringify(S.biz.find(b=>b.id==='lc1')||null)"); + const o = JSON.parse(b); + assert.ok(o, 'still a customer'); + assert.equal(o.lcCr, undefined, 'no credits'); + assert.equal(o.lcB, undefined, 'not in breach'); + assert.ok(o.mood > 90, `happier every day it is served (${o.mood})`); + assert.deepEqual(errors, []); +}); + +test('#137 the volume cap holds: renewals, a sales shark and an edited save never take one past 3.2T', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + ev(sign(1600)); + const b = "S.biz.find(b=>b.id==='lc1')"; + assert.ok(ev('Math.max(...BIZ_T.lowlat.opts)<=BIZ_T.lowlat.max'), 'a shark bumps an offer one size up its list, never past the most'); + assert.equal(ev(`clGrow(${b})`), true, 'grows to the next size once'); + assert.equal(ev(`${b}.bw`), 3200); + assert.equal(ev(`clGrow(${b})`), false, 'and never past it'); + assert.equal(ev(`${b}.bw`), 3200); + assert.equal(ev("(()=>{const x={type:'hyper',bw:6400};clGrow(x);return x.bw;})()"), 12800, 'other customers still double past their top size'); + // An edited save asking for more is cut back to the most the type sells. + ev(`${b}.bw=51200`); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev(`${b}.bw`), 3200); + assert.deepEqual(errors, []); +}); + +test('#137 old saves load, and new fields from a save are checked', () => { + const { ev, errors } = load(); + ev(start); + ev(net()); + // A save from before latency contracts: nothing of theirs in it. + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.ok(!ev("S.biz.some(b=>b.type==='lowlat')")); + // A save with a contract whose fields were edited or lost. + ev(sign()); + ev(`(()=>{const s=JSON.parse(JSON.stringify(S)),b=s.biz.find(b=>b.id==='lc1');b.lcCr='lots';b.lcB='yes';delete b.latMax;b.reqs=[];S=migrate(s);compute();})()`); + const b = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.id==='lc1'))")); + assert.equal(b.lcCr, undefined, 'junk credits dropped'); + assert.equal(b.lcB, 1, 'flag as a flag'); + assert.equal(b.latMax, ev("latMaxOf('nyc','chi')"), 'the latency limit comes back'); + assert.ok(b.reqs.includes('lat'), 'and its requirement'); + ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.biz.find(b=>b.id==='lc1').lcCr=${lit(1234.4)};S=migrate(s);})()`); + assert.equal(ev("S.biz.find(b=>b.id==='lc1').lcCr"), 1234); + assert.deepEqual(errors, []); +}); + +test('#137 offer and customer rows on a 390 px phone', () => { + const { ev, dom, errors } = load(); + ev(start); + ev(net()); + ev('S.lvl=LC_LV'); + ev("S.offers.push({id:'o1',city:'nyc',city2:'chi',name:'Great Circle Clearing House',type:'lowlat',bw:3200,rate:900,reqs:['lat'],latMax:latMaxOf('nyc','chi'),exp:S.day+40})"); + dom.window.innerWidth = 390; + ev("ACT.leftTab({t:'deals'});renderAll()"); + const html = dom.window.document.body.innerHTML; + assert.match(html, /Great Circle Clearing House/); + assert.match(html, /Low-latency wholesale route/); + assert.match(html, /Latency SLA [\d.]+ ms: a day's fee back for every day over it · never more than 3\.20 Tbps/); + ev("ACT.accept({id:'o1'})"); + const c = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.name==='Great Circle Clearing House'))")); + assert.equal(c.route, 'fast', 'routed for latency'); + assert.equal(c.latMax, ev("latMaxOf('nyc','chi')")); + ev(`S.biz.find(b=>b.id===${lit(c.id)}).lcCr=5000;renderAll()`); + const cs = ev('custSection()'); + assert.match(cs, /Low-latency wholesale route/); + assert.match(cs, /\$5\.0k paid in SLA credits/); + assert.deepEqual(errors, []); +}); From d8223bad0401f5bfe43ba5536eb2146667ef9391 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Tue, 10 Nov 2026 07:14:36 +0000 Subject: [PATCH 2/2] Tests: route fuzz compares the customer catalog, day steps waits longer for its trial A new customer type changes which offers a seeded late-game draws, so the fuzz games cannot play move for move like main (as with a world change), and the sales-trial race in day-steps comes on day 46 instead of before day 20. --- tests/day-steps.test.js | 3 ++- tests/route-fuzz.test.js | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/day-steps.test.js b/tests/day-steps.test.js index 027b065..866cc51 100644 --- a/tests/day-steps.test.js +++ b/tests/day-steps.test.js @@ -189,7 +189,8 @@ test('a customer dropped while a sales trial routes: the trial runs again on the p.ev(TICK_ERR); p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};"); let found = false; - for (let d = 0; d < 20 && !found; d++) { + // Which day such a trial comes depends on the offers the seeded game draws (day 46 since latency contracts joined them). + for (let d = 0; d < 60 && !found; d++) { p.ev('rwDay()'); for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) { if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; } diff --git a/tests/route-fuzz.test.js b/tests/route-fuzz.test.js index 8207da4..c0787f2 100644 --- a/tests/route-fuzz.test.js +++ b/tests/route-fuzz.test.js @@ -17,10 +17,10 @@ function pages() { let base = head; try { const b = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-base.html`); fs.writeFileSync(b, page.assembleRef('origin/main')); base = b; } catch (e) {} let P = { base: openPage(base, 'base'), head: openPage(head, 'head') }; - // A change to the world itself (cities, networks, cables) or to what links cost cannot route like main: there is no - // same game to compare. Then the base is this checkout too, and the cache on/off check still runs; equivalence with - // main resumes once it lands. - const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)])])"); + // A change to the world itself (cities, networks, cables, the kinds of customers that call) or to what links cost + // cannot route like main: there is no same game to compare. Then the base is this checkout too, and the cache on/off + // check still runs; equivalence with main resumes once it lands. + const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)]),Object.keys(BIZ_T).map(t=>[t,BIZ_T[t].lv||1,BIZ_T[t].opts])])"); if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world or its prices differ from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; } return P; }