Skip to content

Commit 091a40e

Browse files
committed
fix: observe and retire native ports during startup
1 parent 4791d04 commit 091a40e

20 files changed

Lines changed: 380 additions & 66 deletions

File tree

‎docs/reference/v5-model-coverage.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ liveness/reachability controls have their own documented assumptions.
141141
| [authority-lifetime](../../tests/models/tla/authority-lifetime/Lifetime.tla) | 9 | 2 |
142142
| [publication-journal](../../tests/models/tla/publication-journal/Journal.tla) | 50 | 2 |
143143
| [publication](../../tests/models/tla/publication/Publication.tla) | 16 | 2 |
144-
| [per-service-publication](../../tests/models/tla/per-service-publication/COVERAGE.md) | 622 | 3 |
144+
| [per-service-publication](../../tests/models/tla/per-service-publication/COVERAGE.md) | 669 | 4 |
145145
| [fence-first](../../tests/models/tla/fence-first/First.tla) | 24 | 2 |
146146
| [fence-pending](../../tests/models/tla/fence-pending/Fence.tla) | 7 | 2 |
147147
| [relay-staging](../../tests/models/tla/relay-staging/Stage.tla) | 9 | 2 |

‎docs/versions/v5/native/start.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,12 @@ launchers if requested. After an uncertain outcome, inspect
122122
[recovery instructions](https://github.com/hack-dance/hack/blob/5002cf87bb50686b17ceae8a4c835f524ee1b3a5/docs/guides/native-candidate.md#normal-native-exec).
123123

124124
Native `up --detach` and `up --json` wait for the background owner to report ready.
125+
A loopback port can accept connections as soon as its own service is ready.
126+
During startup, `hack ps` shows verified loopback publications, and
127+
`hack open <service>` can open a service with one verified loopback address.
128+
Other services can still be starting. If the start fails or is cancelled,
129+
the owner retires the ports it has already published. HTTPS addresses still
130+
depend on the HTTPS frontend being ready.
125131
See [native command forms and startup limits](https://github.com/hack-dance/hack/blob/next/docs/native/limits.md) for the
126132
separate detached and graph readiness limits. If detached startup times out,
127133
run `down` next. It waits up to two minutes for a pending owner and stops what

‎packages/runtime-core/src/provider/graph/bridges.rs‎

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -680,10 +680,12 @@ pub(super) fn admit_ready_service(
680680
input: &input,
681681
},
682682
&mut load_store(candidate, engine, false)?,
683-
run,
684-
&selected,
683+
StartSelection {
684+
run,
685+
selected: &selected,
686+
ready_service: scope,
687+
},
685688
&digest,
686-
scope,
687689
)
688690
}
689691

@@ -974,10 +976,12 @@ pub(in crate::provider::graph) fn start_bridges(
974976
input: &input,
975977
},
976978
&mut store,
977-
run,
978-
selected,
979+
StartSelection {
980+
run,
981+
selected,
982+
ready_service: None,
983+
},
979984
&digest,
980-
None,
981985
)
982986
}
983987

@@ -1025,16 +1029,25 @@ impl RelayGuest for LeasedRelays<'_, '_> {
10251029
///
10261030
/// A refusal after step 4 leaves every intent recorded for the caller's cleanup,
10271031
/// exactly as a refused single start did.
1032+
struct StartSelection<'a> {
1033+
run: &'a str,
1034+
selected: &'a [(u8, &'a str)],
1035+
ready_service: Option<(&'a str, &'a str)>,
1036+
}
1037+
10281038
fn start_selected(
10291039
candidate: &Candidate,
10301040
inspection: &impl Inspection,
10311041
guest: &impl RelayGuest,
10321042
store: &mut Store,
1033-
run: &str,
1034-
selected: &[(u8, &str)],
1043+
selection: StartSelection<'_>,
10351044
digest: &str,
1036-
ready_service: Option<(&str, &str)>,
10371045
) -> Result<Vec<(u8, Assignment)>, CandidateError> {
1046+
let StartSelection {
1047+
run,
1048+
selected,
1049+
ready_service,
1050+
} = selection;
10381051
let inspect = |services: &std::collections::BTreeSet<&str>| {
10391052
inspect_targets_scoped(candidate, inspection, run, services, ready_service)
10401053
};
@@ -1231,16 +1244,7 @@ pub fn publish_bridge(
12311244
hostnames: &[String],
12321245
) -> Result<(), CandidateError> {
12331246
let engine = connect_waiting(candidate)?;
1234-
let upstream = publication_upstream(
1235-
candidate,
1236-
&engine,
1237-
run,
1238-
slot,
1239-
reservation,
1240-
port,
1241-
hostnames,
1242-
None,
1243-
)?;
1247+
let upstream = publication_upstream(&engine, run, slot, reservation, port, hostnames, None)?;
12441248
super::super::publication::launch(
12451249
candidate,
12461250
super::super::publication::Launch {
@@ -1257,7 +1261,6 @@ pub fn publish_bridge(
12571261

12581262
/// Revalidate the exact frontend and relay under the caller's provider lease.
12591263
pub(super) fn publication_upstream(
1260-
candidate: &Candidate,
12611264
engine: &Engine<'_>,
12621265
run: &str,
12631266
slot: u8,
@@ -1266,6 +1269,7 @@ pub(super) fn publication_upstream(
12661269
hostnames: &[String],
12671270
ready_service: Option<(&str, &str)>,
12681271
) -> Result<std::path::PathBuf, CandidateError> {
1272+
let candidate = engine.guest().candidate();
12691273
let store = load_store(candidate, engine, false)?;
12701274
let a = store
12711275
.slots

‎packages/runtime-core/src/provider/graph/bridges/batch_tests.rs‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -282,10 +282,12 @@ fn start(batch: &Batch, guest: &Guest) -> Result<Vec<(u8, Assignment)>, Candidat
282282
guest,
283283
guest,
284284
&mut store,
285-
RUN,
286-
&selected,
285+
StartSelection {
286+
run: RUN,
287+
selected: &selected,
288+
ready_service: None,
289+
},
287290
&"9".repeat(64),
288-
None,
289291
)
290292
}
291293

@@ -467,10 +469,12 @@ fn a_changed_or_repeated_reservation_refuses_before_any_guest_call() {
467469
&guest,
468470
&guest,
469471
&mut store,
470-
RUN,
471-
&selected,
472+
StartSelection {
473+
run: RUN,
474+
selected: &selected,
475+
ready_service: None
476+
},
472477
&"9".repeat(64),
473-
None,
474478
)
475479
.is_err()
476480
);

‎packages/runtime-core/src/provider/graph/foreground/publishers.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,6 @@ impl EarlyPublications {
128128
};
129129
let upstream = || {
130130
graph::bridges::publication_upstream(
131-
candidate,
132131
engine,
133132
run,
134133
slot,
@@ -178,6 +177,8 @@ impl EarlyPublications {
178177
return Err(refused());
179178
}
180179
if published(candidate, owned).is_ok() {
180+
#[cfg(debug_assertions)]
181+
graph::publisher_recovery_fault(candidate, run, "publisher-bound")?;
181182
return Ok(());
182183
}
183184
std::thread::sleep(PUBLISHED_POLL);

‎packages/runtime-core/src/provider/graph/mod.rs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,8 @@ pub struct Snapshot {
330330
#[cfg(target_os = "macos")]
331331
pub interrupted_start_cleanup_incomplete: bool,
332332
pub observations: BTreeMap<String, Value>,
333+
#[serde(skip_serializing_if = "Vec::is_empty")]
334+
pub startup_observed_ports: Vec<u16>,
333335
pub guest_endpoints: BTreeMap<String, GuestEndpoint>,
334336
/// Ready containers' loopback publication targets, keyed by
335337
/// [`port_endpoint_key`]. Independent of HTTP probes: a published port
@@ -779,7 +781,7 @@ struct Session<'a, 's> {
779781
/// diagnostic (HACK-2416).
780782
probe_findings: BTreeMap<String, crate::ProbeFinding>,
781783
}
782-
#[cfg(test)]
784+
#[cfg(any(test, all(debug_assertions, target_os = "macos")))]
783785
pub(super) fn fault_pause(
784786
root: &std::path::Path,
785787
run: &str,
@@ -796,7 +798,7 @@ pub(super) fn fault_pause(
796798
}
797799
Ok(())
798800
}
799-
#[cfg(all(test, target_os = "macos"))]
801+
#[cfg(all(any(test, debug_assertions), target_os = "macos"))]
800802
pub(super) fn publisher_recovery_fault(
801803
candidate: &Candidate,
802804
run: &str,
@@ -2163,6 +2165,7 @@ fn inspect_using(
21632165
#[cfg(target_os = "macos")]
21642166
interrupted_start_cleanup_incomplete,
21652167
observations,
2168+
startup_observed_ports: Vec::new(),
21662169
guest_endpoints,
21672170
port_endpoints,
21682171
storage_references,

‎packages/runtime-core/src/provider/graph/status.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,19 @@ fn inspect_with(
7777
stable(&directory(candidate, run)?, || {
7878
observer.verify()?;
7979
let snapshot = inspect_using(candidate, observer, run)?;
80+
#[cfg(target_os = "macos")]
81+
let snapshot = {
82+
let mut snapshot = snapshot;
83+
if matches!(snapshot.receipt.phase.as_str(), "preparing" | "restoring") {
84+
snapshot.startup_observed_ports = super::super::publication::observed_run_ports(
85+
candidate,
86+
&snapshot.receipt.owner,
87+
run,
88+
)
89+
.unwrap_or_default();
90+
}
91+
snapshot
92+
};
8093
observer.verify()?;
8194
if snapshot.journal_incomplete {
8295
return Err(changed());

‎packages/runtime-core/src/provider/publication.rs‎

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ pub(super) fn launch_child(
8787
options: &Launch<'_>,
8888
check: impl FnOnce() -> Result<(), CandidateError>,
8989
) -> Result<std::process::Child, CandidateError> {
90-
let mut command = Command::new(std::env::current_exe().map_err(state::io)?);
90+
let executable = std::env::current_exe().map_err(state::io)?;
91+
let mut command = super::process::publisher_command(&executable);
9192
command.arg("--internal-publication-child");
9293
launch_child_with(candidate, options, check, command)
9394
}
@@ -108,9 +109,13 @@ fn launch_child_with(
108109
let mut committed = false;
109110
let result = (|| {
110111
let mut gate = child.stdin.take().ok_or_else(error)?;
112+
#[cfg(debug_assertions)]
113+
super::graph::publisher_recovery_fault(candidate, options.run, "publisher-gated")?;
111114
let process = identity::observe(child.id() as i32)?;
112115
let entry = stage_launch(candidate, options, process)?;
113116
committed = true;
117+
#[cfg(debug_assertions)]
118+
super::graph::publisher_recovery_fault(candidate, options.run, "publisher-committed")?;
114119
let request = ChildLaunch {
115120
entry,
116121
upstream: options.upstream.into(),
@@ -122,7 +127,11 @@ fn launch_child_with(
122127
check()?;
123128
// Encode authorization after the complete payload. EOF alone is a refusal.
124129
gate.write_all(&bytes).map_err(state::io)?;
125-
gate.write_all(b"\n").map_err(state::io)
130+
gate.write_all(b"\n").map_err(state::io)?;
131+
#[cfg(debug_assertions)]
132+
let _ =
133+
super::graph::publisher_recovery_fault(candidate, options.run, "publisher-authorized");
134+
Ok(())
126135
})();
127136
if let Err(error) = result {
128137
child.wait().map_err(state::io)?;
@@ -700,10 +709,13 @@ fn check_socket(
700709
.map_err(state::io)
701710
}
702711
fn cleanup(e: &Entry) -> Result<(), CandidateError> {
712+
let control = directory(e).join("control");
713+
#[cfg(target_os = "macos")]
714+
wait_for_authorized_child(e, &control)?;
703715
let options = publisher::StopOptions {
704716
process: &e.process,
705717
binary: &e.process.executable,
706-
control: &directory(e).join("control"),
718+
control: &control,
707719
token: &e.token,
708720
};
709721
#[cfg(target_os = "macos")]
@@ -793,6 +805,28 @@ fn cleanup(e: &Entry) -> Result<(), CandidateError> {
793805
.map_err(state::io)
794806
}
795807

808+
/// A committed child may still be between authorization and the control bind.
809+
/// Wait only for that exact incarnation to exit or reach the normal stop path.
810+
#[cfg(target_os = "macos")]
811+
fn wait_for_authorized_child(e: &Entry, control: &Path) -> Result<(), CandidateError> {
812+
use std::time::{Duration, Instant};
813+
if !e.binary.as_ref().is_some_and(|binary| binary.ready) {
814+
return Ok(());
815+
}
816+
let deadline = Instant::now() + Duration::from_secs(2);
817+
loop {
818+
match fs::symlink_metadata(control) {
819+
Ok(_) => return Ok(()),
820+
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
821+
Err(error) => return Err(state::io(error)),
822+
}
823+
if entry_gone(e)? || Instant::now() >= deadline {
824+
return Ok(());
825+
}
826+
std::thread::sleep(Duration::from_millis(10));
827+
}
828+
}
829+
796830
/// The caller holds the provider lease; require every selected recorded process to be absent before
797831
/// any guest cleanup. A reused, live or inaccessible PID conservatively refuses.
798832
#[cfg(target_os = "macos")]
@@ -1055,6 +1089,30 @@ fn verify_claim_snapshot(
10551089
}
10561090
Ok(())
10571091
}
1092+
1093+
/// Lease-free presentation of the verified TCP listeners of one receipt.
1094+
#[cfg(target_os = "macos")]
1095+
pub(super) fn observed_run_ports(
1096+
candidate: &Candidate,
1097+
owner: &str,
1098+
run: &str,
1099+
) -> Result<Vec<u16>, CandidateError> {
1100+
let entries = load(candidate, owner)?;
1101+
let observed = entries
1102+
.values()
1103+
.filter(|entry| entry.run == run && !entry.unix)
1104+
.filter(|entry| observe_publication(entry).is_ok())
1105+
.collect::<Vec<_>>();
1106+
let after_owner = state::Owner::load(candidate)?;
1107+
let after = load(candidate, &after_owner.token)?;
1108+
observed
1109+
.into_iter()
1110+
.map(|entry| {
1111+
verify_claim_snapshot(entry, &after, &after_owner.token)?;
1112+
Ok(entry.port)
1113+
})
1114+
.collect()
1115+
}
10581116
/// A point-in-time observation, not a persistent capability or guest health claim.
10591117
pub fn lookup_hostname(c: &Candidate, value: &str) -> Result<serde_json::Value, CandidateError> {
10601118
let name = normalize_hostname(value)?;

‎scripts/lib/tla-runtime-models.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2428,7 +2428,7 @@ const contracts: readonly ModelContract[] = [
24282428
{
24292429
name: "per-service-publication",
24302430
module: "PerServicePublication",
2431-
states: 622,
2431+
states: 669,
24322432
invariant: "Safe",
24332433
action: "Record",
24342434
fields: ['recorded = {"first"}', 'first |-> "gated"'],
@@ -2439,6 +2439,13 @@ const contracts: readonly ModelContract[] = [
24392439
action: "Bind",
24402440
fields: ['first |-> "uncommitted-bind"', "recorded = {}"],
24412441
},
2442+
{
2443+
name: "dead-authorization",
2444+
negative: true,
2445+
invariant: "NoDeadAuthorizedBind",
2446+
action: "Bind",
2447+
fields: ["lateBind = TRUE", 'phase = "dead"'],
2448+
},
24422449
],
24432450
},
24442451
{

0 commit comments

Comments
 (0)