1use std::fmt::Write as _;
2use std::num::NonZeroUsize;
3use std::time::{Duration, Instant};
4
5use code_system_graph_model::stable_id;
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10mod tracker;
11
12pub use tracker::{MonotonicClock, ScanJobTracker};
13
14pub const DEFAULT_MAX_SCAN_WALL_TIME_MS: u64 = 21_600_000;
16pub const DEFAULT_MAX_NO_PROGRESS_TIME_MS: u64 = 300_000;
18pub const DEFAULT_MAX_CODEGRAPH_SYNC_WALL_TIME_MS_PER_REPO: u64 = 3_600_000;
20pub const DEFAULT_MAX_CODEGRAPH_CORROBORATION_ANCHORS_PER_REPO: i64 = 50;
22pub const DEFAULT_MAX_WORKER_MEMORY_BYTES: u64 = 17_179_869_184;
24pub const DEFAULT_GRACEFUL_TERMINATION_MS: u64 = 5_000;
26pub const DEFAULT_WATCH_IDLE_TIMEOUT_MS: u64 = 28_800_000;
28pub const DEFAULT_MAX_WATCH_SESSION_WALL_TIME_MS: u64 = 86_400_000;
30pub const DEFAULT_MIN_WATCH_RESCAN_INTERVAL_MS: u64 = 10_000;
32pub const DEFAULT_MAX_CHECKPOINT_CACHE_BYTES: u64 = 10_737_418_240;
34pub const DEFAULT_MAX_EXPLORE_WALL_TIME_MS: u64 = 8_000;
35pub const DEFAULT_MAX_EXPLORE_CODEGRAPH_OPERATIONS: u64 = 8;
36pub const DEFAULT_MAX_EXPLORE_CONCURRENT_CODEGRAPH_PROCESSES: u64 = 2;
37pub const DEFAULT_MAX_EXPLORE_SOURCE_FILES: u64 = 25;
38pub const DEFAULT_MAX_EXPLORE_RESOLVED_SYMBOLS: u64 = 5;
39pub const DEFAULT_MAX_EXPLORE_ANCHORS: u64 = 3;
40pub const DEFAULT_MAX_EXPLORE_NEIGHBORS_PER_DIRECTION: u64 = 8;
41pub const DEFAULT_MAX_EXPLORE_LOCAL_RELATIONSHIPS: u64 = 48;
42pub const DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS_PER_ANCHOR: u64 = 10;
43pub const DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS: u64 = 30;
44pub const DEFAULT_MAX_EXPLORE_EVIDENCE_LOCATIONS_PER_HANDOFF: u64 = 4;
45pub const DEFAULT_MAX_EXPLORE_SOURCE_MARKDOWN_BYTES: u64 = 262_144;
46pub const DEFAULT_MAX_EXPLORE_ENRICHMENT_BYTES: u64 = 65_536;
47pub const DEFAULT_MAX_AGENT_NEXT_ACTIONS_PER_RESPONSE: u64 = 12;
48pub const DEFAULT_MAX_QUERY_REPOSITORY_SUGGESTIONS: u64 = 20;
49pub const DEFAULT_MAX_MCP_TOOL_RESPONSE_BYTES: u64 = 524_288;
50pub const DEFAULT_MAX_MCP_RESOURCE_ITEMS: u64 = 100;
51pub const DEFAULT_MAX_MCP_RESOURCE_BYTES: u64 = 262_144;
52pub const DEFAULT_MAX_MCP_SCHEMA_CATALOG_BYTES: u64 = 2_097_152;
53pub const MIN_MCP_MARKDOWN_BYTES: u64 = 256;
55
56macro_rules! with_agent_policy_fields {
61 ($consumer:ident) => {
62 $consumer! {
63 max_explore_wall_time_ms: DEFAULT_MAX_EXPLORE_WALL_TIME_MS => "maxExploreWallTimeMs";
64 max_explore_codegraph_operations: DEFAULT_MAX_EXPLORE_CODEGRAPH_OPERATIONS => "maxExploreCodeGraphOperations";
65 max_explore_concurrent_codegraph_processes: DEFAULT_MAX_EXPLORE_CONCURRENT_CODEGRAPH_PROCESSES => "maxExploreConcurrentCodeGraphProcesses";
66 max_explore_source_files: DEFAULT_MAX_EXPLORE_SOURCE_FILES => "maxExploreSourceFiles";
67 max_explore_resolved_symbols: DEFAULT_MAX_EXPLORE_RESOLVED_SYMBOLS => "maxExploreResolvedSymbols";
68 max_explore_anchors: DEFAULT_MAX_EXPLORE_ANCHORS => "maxExploreAnchors";
69 max_explore_neighbors_per_direction: DEFAULT_MAX_EXPLORE_NEIGHBORS_PER_DIRECTION => "maxExploreNeighborsPerDirection";
70 max_explore_local_relationships: DEFAULT_MAX_EXPLORE_LOCAL_RELATIONSHIPS => "maxExploreLocalRelationships";
71 max_explore_federated_handoffs_per_anchor: DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS_PER_ANCHOR => "maxExploreFederatedHandoffsPerAnchor";
72 max_explore_federated_handoffs: DEFAULT_MAX_EXPLORE_FEDERATED_HANDOFFS => "maxExploreFederatedHandoffs";
73 max_explore_evidence_locations_per_handoff: DEFAULT_MAX_EXPLORE_EVIDENCE_LOCATIONS_PER_HANDOFF => "maxExploreEvidenceLocationsPerHandoff";
74 max_explore_source_markdown_bytes: DEFAULT_MAX_EXPLORE_SOURCE_MARKDOWN_BYTES => "maxExploreSourceMarkdownBytes";
75 max_explore_enrichment_bytes: DEFAULT_MAX_EXPLORE_ENRICHMENT_BYTES => "maxExploreEnrichmentBytes";
76 max_agent_next_actions_per_response: DEFAULT_MAX_AGENT_NEXT_ACTIONS_PER_RESPONSE => "maxAgentNextActionsPerResponse";
77 max_query_repository_suggestions: DEFAULT_MAX_QUERY_REPOSITORY_SUGGESTIONS => "maxQueryRepositorySuggestions";
78 max_mcp_tool_response_bytes: DEFAULT_MAX_MCP_TOOL_RESPONSE_BYTES => "maxMcpToolResponseBytes";
79 max_mcp_resource_items: DEFAULT_MAX_MCP_RESOURCE_ITEMS => "maxMcpResourceItems";
80 max_mcp_resource_bytes: DEFAULT_MAX_MCP_RESOURCE_BYTES => "maxMcpResourceBytes";
81 max_mcp_schema_catalog_bytes: DEFAULT_MAX_MCP_SCHEMA_CATALOG_BYTES => "maxMcpSchemaCatalogBytes";
82 }
83 };
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, JsonSchema)]
91pub enum CodeGraphCorroborationAnchorLimit {
92 Bounded(NonZeroUsize),
94 Unlimited,
96}
97
98impl CodeGraphCorroborationAnchorLimit {
99 #[must_use]
101 pub const fn bounded(self) -> Option<NonZeroUsize> {
102 match self {
103 Self::Bounded(limit) => Some(limit),
104 Self::Unlimited => None,
105 }
106 }
107}
108
109impl TryFrom<i64> for CodeGraphCorroborationAnchorLimit {
110 type Error = InvalidExecutionPolicy;
111
112 fn try_from(value: i64) -> Result<Self, Self::Error> {
113 if value == -1 {
114 return Ok(Self::Unlimited);
115 }
116 let limit = usize::try_from(value)
117 .ok()
118 .and_then(NonZeroUsize::new)
119 .ok_or(InvalidExecutionPolicy::InvalidValue {
120 field: "maxCodeGraphCorroborationAnchorsPerRepo",
121 value: value.unsigned_abs(),
122 })?;
123 Ok(Self::Bounded(limit))
124 }
125}
126
127impl Serialize for CodeGraphCorroborationAnchorLimit {
128 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129 where
130 S: serde::Serializer,
131 {
132 let value = match self {
133 Self::Bounded(limit) => i64::try_from(limit.get()).map_err(|_| {
134 serde::ser::Error::custom("CodeGraph corroboration anchor limit exceeds i64")
135 })?,
136 Self::Unlimited => -1,
137 };
138 serializer.serialize_i64(value)
139 }
140}
141
142impl<'de> Deserialize<'de> for CodeGraphCorroborationAnchorLimit {
143 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
144 where
145 D: serde::Deserializer<'de>,
146 {
147 i64::deserialize(deserializer)?
148 .try_into()
149 .map_err(serde::de::Error::custom)
150 }
151}
152
153impl std::fmt::Display for CodeGraphCorroborationAnchorLimit {
154 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 match self {
156 Self::Bounded(limit) => limit.fmt(formatter),
157 Self::Unlimited => formatter.write_str("-1"),
158 }
159 }
160}
161
162#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
164#[serde(rename_all = "camelCase", deny_unknown_fields)]
165pub struct ExecutionPolicyOverrides {
166 pub max_scan_wall_time_ms: Option<u64>,
168 pub max_no_progress_time_ms: Option<u64>,
170 #[serde(rename = "maxCodeGraphSyncWallTimeMsPerRepo")]
172 pub max_codegraph_sync_wall_time_ms_per_repo: Option<u64>,
173 pub max_worker_memory_bytes: Option<u64>,
175 pub graceful_termination_ms: Option<u64>,
177 pub watch_idle_timeout_ms: Option<u64>,
179 pub max_watch_session_wall_time_ms: Option<u64>,
181 pub min_watch_rescan_interval_ms: Option<u64>,
183 pub max_checkpoint_cache_bytes: Option<u64>,
185 #[serde(rename = "maxCodeGraphCorroborationAnchorsPerRepo")]
187 pub max_codegraph_corroboration_anchors_per_repo: Option<i64>,
188 pub max_explore_wall_time_ms: Option<u64>,
190 #[serde(rename = "maxExploreCodeGraphOperations")]
192 pub max_explore_codegraph_operations: Option<u64>,
193 #[serde(rename = "maxExploreConcurrentCodeGraphProcesses")]
195 pub max_explore_concurrent_codegraph_processes: Option<u64>,
196 pub max_explore_source_files: Option<u64>,
198 pub max_explore_resolved_symbols: Option<u64>,
200 pub max_explore_anchors: Option<u64>,
202 pub max_explore_neighbors_per_direction: Option<u64>,
204 pub max_explore_local_relationships: Option<u64>,
206 pub max_explore_federated_handoffs_per_anchor: Option<u64>,
208 pub max_explore_federated_handoffs: Option<u64>,
210 pub max_explore_evidence_locations_per_handoff: Option<u64>,
212 pub max_explore_source_markdown_bytes: Option<u64>,
214 pub max_explore_enrichment_bytes: Option<u64>,
216 pub max_agent_next_actions_per_response: Option<u64>,
218 pub max_query_repository_suggestions: Option<u64>,
220 pub max_mcp_tool_response_bytes: Option<u64>,
222 pub max_mcp_resource_items: Option<u64>,
224 pub max_mcp_resource_bytes: Option<u64>,
226 pub max_mcp_schema_catalog_bytes: Option<u64>,
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
232#[serde(rename_all = "camelCase")]
233pub struct ExecutionPolicy {
234 pub max_scan_wall_time_ms: u64,
236 pub max_no_progress_time_ms: u64,
238 #[serde(rename = "maxCodeGraphSyncWallTimeMsPerRepo")]
240 pub max_codegraph_sync_wall_time_ms_per_repo: u64,
241 pub max_worker_memory_bytes: u64,
243 pub graceful_termination_ms: u64,
245 pub watch_idle_timeout_ms: u64,
247 pub max_watch_session_wall_time_ms: u64,
249 pub min_watch_rescan_interval_ms: u64,
251 pub max_checkpoint_cache_bytes: u64,
253 #[serde(rename = "maxCodeGraphCorroborationAnchorsPerRepo")]
255 #[schemars(with = "i64")]
256 pub max_codegraph_corroboration_anchors_per_repo: CodeGraphCorroborationAnchorLimit,
257 pub max_explore_wall_time_ms: u64,
259 #[serde(rename = "maxExploreCodeGraphOperations")]
261 pub max_explore_codegraph_operations: u64,
262 #[serde(rename = "maxExploreConcurrentCodeGraphProcesses")]
264 pub max_explore_concurrent_codegraph_processes: u64,
265 pub max_explore_source_files: u64,
267 pub max_explore_resolved_symbols: u64,
269 pub max_explore_anchors: u64,
271 pub max_explore_neighbors_per_direction: u64,
273 pub max_explore_local_relationships: u64,
275 pub max_explore_federated_handoffs_per_anchor: u64,
277 pub max_explore_federated_handoffs: u64,
279 pub max_explore_evidence_locations_per_handoff: u64,
281 pub max_explore_source_markdown_bytes: u64,
283 pub max_explore_enrichment_bytes: u64,
285 pub max_agent_next_actions_per_response: u64,
287 pub max_query_repository_suggestions: u64,
289 pub max_mcp_tool_response_bytes: u64,
291 pub max_mcp_resource_items: u64,
293 pub max_mcp_resource_bytes: u64,
295 pub max_mcp_schema_catalog_bytes: u64,
297}
298
299impl Default for ExecutionPolicy {
300 fn default() -> Self {
301 macro_rules! policy_defaults {
302 ($($field:ident: $default:ident => $external:literal;)*) => {
303 Self {
304 max_scan_wall_time_ms: DEFAULT_MAX_SCAN_WALL_TIME_MS,
305 max_no_progress_time_ms: DEFAULT_MAX_NO_PROGRESS_TIME_MS,
306 max_codegraph_sync_wall_time_ms_per_repo:
307 DEFAULT_MAX_CODEGRAPH_SYNC_WALL_TIME_MS_PER_REPO,
308 max_worker_memory_bytes: DEFAULT_MAX_WORKER_MEMORY_BYTES,
309 graceful_termination_ms: DEFAULT_GRACEFUL_TERMINATION_MS,
310 watch_idle_timeout_ms: DEFAULT_WATCH_IDLE_TIMEOUT_MS,
311 max_watch_session_wall_time_ms: DEFAULT_MAX_WATCH_SESSION_WALL_TIME_MS,
312 min_watch_rescan_interval_ms: DEFAULT_MIN_WATCH_RESCAN_INTERVAL_MS,
313 max_checkpoint_cache_bytes: DEFAULT_MAX_CHECKPOINT_CACHE_BYTES,
314 max_codegraph_corroboration_anchors_per_repo:
315 CodeGraphCorroborationAnchorLimit::try_from(
316 DEFAULT_MAX_CODEGRAPH_CORROBORATION_ANCHORS_PER_REPO,
317 )
318 .expect("the built-in corroboration limit is valid"),
319 $($field: $default,)*
320 }
321 };
322 }
323 with_agent_policy_fields!(policy_defaults)
324 }
325}
326
327impl ExecutionPolicy {
328 pub fn resolve(
334 overrides: Option<&ExecutionPolicyOverrides>,
335 ) -> Result<Self, InvalidExecutionPolicy> {
336 let mut policy = Self::default();
337 if let Some(values) = overrides {
338 macro_rules! apply {
339 ($field:ident) => {
340 if let Some(value) = values.$field {
341 policy.$field = value;
342 }
343 };
344 }
345 apply!(max_scan_wall_time_ms);
346 apply!(max_no_progress_time_ms);
347 apply!(max_codegraph_sync_wall_time_ms_per_repo);
348 apply!(max_worker_memory_bytes);
349 apply!(graceful_termination_ms);
350 apply!(watch_idle_timeout_ms);
351 apply!(max_watch_session_wall_time_ms);
352 apply!(min_watch_rescan_interval_ms);
353 apply!(max_checkpoint_cache_bytes);
354 if let Some(value) = values.max_codegraph_corroboration_anchors_per_repo {
355 policy.max_codegraph_corroboration_anchors_per_repo = value.try_into()?;
356 }
357 macro_rules! apply_agent_overrides {
358 ($($field:ident: $default:ident => $external:literal;)*) => {
359 $(apply!($field);)*
360 };
361 }
362 with_agent_policy_fields!(apply_agent_overrides);
363 }
364 policy.validate()?;
365 Ok(policy)
366 }
367
368 fn validate(&self) -> Result<(), InvalidExecutionPolicy> {
369 self.validate_scalar_values()?;
370 self.validate_mcp_minimums()?;
371 self.validate_scan_relationships()?;
372 self.validate_explore_relationships()
373 }
374
375 fn validate_mcp_minimums(&self) -> Result<(), InvalidExecutionPolicy> {
376 for (field, value) in [
377 ("maxMcpToolResponseBytes", self.max_mcp_tool_response_bytes),
378 ("maxMcpResourceBytes", self.max_mcp_resource_bytes),
379 (
380 "maxMcpSchemaCatalogBytes",
381 self.max_mcp_schema_catalog_bytes,
382 ),
383 ] {
384 if value < MIN_MCP_MARKDOWN_BYTES {
385 return Err(InvalidExecutionPolicy::BelowMinimum {
386 field,
387 value,
388 minimum: MIN_MCP_MARKDOWN_BYTES,
389 });
390 }
391 }
392 Ok(())
393 }
394
395 fn validate_scalar_values(&self) -> Result<(), InvalidExecutionPolicy> {
396 for (field, value) in self
397 .scan_canonical_values()
398 .into_iter()
399 .chain(self.agent_canonical_values())
400 {
401 let invalid_bytes = field.ends_with("Bytes") && usize::try_from(value).is_err();
402 let invalid_count = !field.ends_with("Ms") && usize::try_from(value).is_err();
403 let invalid_sqlite_quota =
404 field == "maxCheckpointCacheBytes" && i64::try_from(value).is_err();
405 let invalid_deadline = field.ends_with("Ms")
406 && Instant::now()
407 .checked_add(Duration::from_millis(value))
408 .is_none();
409 if value == 0
410 || invalid_bytes
411 || invalid_count
412 || invalid_sqlite_quota
413 || invalid_deadline
414 {
415 return Err(InvalidExecutionPolicy::InvalidValue { field, value });
416 }
417 }
418 Ok(())
419 }
420
421 fn validate_scan_relationships(&self) -> Result<(), InvalidExecutionPolicy> {
422 Self::require_not_greater(
423 "maxNoProgressTimeMs",
424 self.max_no_progress_time_ms,
425 "maxScanWallTimeMs",
426 self.max_scan_wall_time_ms,
427 )?;
428 Self::require_not_greater(
429 "maxCodeGraphSyncWallTimeMsPerRepo",
430 self.max_codegraph_sync_wall_time_ms_per_repo,
431 "maxScanWallTimeMs",
432 self.max_scan_wall_time_ms,
433 )?;
434 Self::require_not_greater(
435 "gracefulTerminationMs",
436 self.graceful_termination_ms,
437 "maxNoProgressTimeMs",
438 self.max_no_progress_time_ms,
439 )?;
440 Self::require_not_greater(
441 "watchIdleTimeoutMs",
442 self.watch_idle_timeout_ms,
443 "maxWatchSessionWallTimeMs",
444 self.max_watch_session_wall_time_ms,
445 )?;
446 Self::require_not_greater(
447 "minWatchRescanIntervalMs",
448 self.min_watch_rescan_interval_ms,
449 "watchIdleTimeoutMs",
450 self.watch_idle_timeout_ms,
451 )
452 }
453
454 fn validate_explore_relationships(&self) -> Result<(), InvalidExecutionPolicy> {
455 Self::require_not_greater(
456 "maxExploreAnchors",
457 self.max_explore_anchors,
458 "maxExploreResolvedSymbols",
459 self.max_explore_resolved_symbols,
460 )?;
461 Self::require_not_greater(
462 "maxExploreConcurrentCodeGraphProcesses",
463 self.max_explore_concurrent_codegraph_processes,
464 "maxExploreCodeGraphOperations",
465 self.max_explore_codegraph_operations,
466 )?;
467 let local_ceiling = self
468 .max_explore_anchors
469 .checked_mul(2)
470 .and_then(|value| value.checked_mul(self.max_explore_neighbors_per_direction))
471 .ok_or(InvalidExecutionPolicy::ArithmeticOverflow {
472 expression: "maxExploreAnchors × 2 × maxExploreNeighborsPerDirection",
473 })?;
474 Self::require_not_greater(
475 "maxExploreLocalRelationships",
476 self.max_explore_local_relationships,
477 "anchor neighbor capacity",
478 local_ceiling,
479 )?;
480 let handoff_ceiling = self
481 .max_explore_anchors
482 .checked_mul(self.max_explore_federated_handoffs_per_anchor)
483 .ok_or(InvalidExecutionPolicy::ArithmeticOverflow {
484 expression: "maxExploreAnchors × maxExploreFederatedHandoffsPerAnchor",
485 })?;
486 Self::require_not_greater(
487 "maxExploreFederatedHandoffs",
488 self.max_explore_federated_handoffs,
489 "anchor handoff capacity",
490 handoff_ceiling,
491 )?;
492 Self::require_not_greater(
493 "maxExploreSourceMarkdownBytes",
494 self.max_explore_source_markdown_bytes,
495 "maxMcpToolResponseBytes",
496 self.max_mcp_tool_response_bytes,
497 )?;
498 Self::require_not_greater(
499 "maxExploreEnrichmentBytes",
500 self.max_explore_enrichment_bytes,
501 "maxMcpToolResponseBytes",
502 self.max_mcp_tool_response_bytes,
503 )
504 }
505
506 fn require_not_greater(
507 field: &'static str,
508 value: u64,
509 maximum_field: &'static str,
510 maximum: u64,
511 ) -> Result<(), InvalidExecutionPolicy> {
512 if value > maximum {
513 return Err(InvalidExecutionPolicy::InvalidRelationship {
514 field,
515 value,
516 maximum_field,
517 maximum,
518 });
519 }
520 Ok(())
521 }
522
523 fn scan_canonical_values(&self) -> [(&'static str, u64); 9] {
524 [
525 ("maxScanWallTimeMs", self.max_scan_wall_time_ms),
526 ("maxNoProgressTimeMs", self.max_no_progress_time_ms),
527 (
528 "maxCodeGraphSyncWallTimeMsPerRepo",
529 self.max_codegraph_sync_wall_time_ms_per_repo,
530 ),
531 ("maxWorkerMemoryBytes", self.max_worker_memory_bytes),
532 ("gracefulTerminationMs", self.graceful_termination_ms),
533 ("watchIdleTimeoutMs", self.watch_idle_timeout_ms),
534 (
535 "maxWatchSessionWallTimeMs",
536 self.max_watch_session_wall_time_ms,
537 ),
538 (
539 "minWatchRescanIntervalMs",
540 self.min_watch_rescan_interval_ms,
541 ),
542 ("maxCheckpointCacheBytes", self.max_checkpoint_cache_bytes),
543 ]
544 }
545
546 fn agent_canonical_values(&self) -> Vec<(&'static str, u64)> {
547 macro_rules! canonical_agent_values {
548 ($($field:ident: $default:ident => $external:literal;)*) => {
549 vec![$(($external, self.$field),)*]
550 };
551 }
552 with_agent_policy_fields!(canonical_agent_values)
553 }
554
555 #[must_use]
557 pub fn scan_fingerprint(&self) -> String {
558 let mut canonical = self
559 .scan_canonical_values()
560 .into_iter()
561 .map(|(name, value)| format!("{name}={value}"))
562 .collect::<Vec<_>>()
563 .join(";");
564 write!(
565 canonical,
566 ";maxCodeGraphCorroborationAnchorsPerRepo={}",
567 self.max_codegraph_corroboration_anchors_per_repo
568 )
569 .expect("writing to a String cannot fail");
570 stable_id("execution-policy", &canonical)
571 }
572
573 #[must_use]
574 pub fn fingerprint(&self) -> String {
576 self.scan_fingerprint()
577 }
578
579 #[must_use]
581 pub fn fingerprint_with_codegraph_limit(
582 &self,
583 limit: CodeGraphCorroborationAnchorLimit,
584 ) -> String {
585 let mut canonical = self
586 .scan_canonical_values()
587 .into_iter()
588 .map(|(name, value)| format!("{name}={value}"))
589 .collect::<Vec<_>>()
590 .join(";");
591 write!(
592 canonical,
593 ";maxCodeGraphCorroborationAnchorsPerRepo={limit}"
594 )
595 .expect("writing to a String cannot fail");
596 stable_id("execution-policy", &canonical)
597 }
598
599 #[must_use]
601 pub fn agent_delivery_fingerprint(&self) -> String {
602 let mut canonical = String::new();
603 for (index, (name, value)) in self.agent_canonical_values().into_iter().enumerate() {
604 if index > 0 {
605 canonical.push(';');
606 }
607 write!(canonical, "{name}={value}").expect("writing to a String cannot fail");
608 }
609 stable_id("agent-delivery-policy", &canonical)
610 }
611}
612
613#[derive(Debug, Clone, PartialEq, Eq, Error)]
615pub enum InvalidExecutionPolicy {
616 #[error("execution policy `{field}` must be positive and representable; received {value}")]
618 InvalidValue {
619 field: &'static str,
621 value: u64,
623 },
624 #[error("execution policy `{field}` must be at least {minimum}; received {value}")]
626 BelowMinimum {
627 field: &'static str,
629 value: u64,
631 minimum: u64,
633 },
634 #[error("execution policy `{field}` ({value}) must not exceed `{maximum_field}` ({maximum})")]
636 InvalidRelationship {
637 field: &'static str,
639 value: u64,
641 maximum_field: &'static str,
643 maximum: u64,
645 },
646 #[error("execution policy arithmetic overflow in `{expression}`")]
648 ArithmeticOverflow {
649 expression: &'static str,
651 },
652}
653
654#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
656#[serde(rename_all = "snake_case")]
657pub enum JobPhase {
658 Configuration,
660 Discovery,
662 Fingerprinting,
664 Extraction,
666 GraphAssembly,
668 Communities,
670 Publication,
672 CodeGraphSync,
674}
675
676#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
678#[serde(rename_all = "snake_case")]
679pub enum ExecutionResource {
680 WallTimeMs,
682 NoProgressTimeMs,
684 WorkerMemoryBytes,
686 WorkUnits,
688 WorkerProcess,
690 WorkerProtocolBytes,
692 Cancellation,
694}
695
696#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
698#[serde(rename_all = "camelCase")]
699pub struct ExecutionSummary {
700 pub run_id: String,
702 pub duration_ms: u64,
704 pub peak_worker_memory_bytes: u64,
706 pub completed_work_units: u64,
708 pub checkpoint_hits: u64,
710 pub checkpoints_written: u64,
712 pub measured_artifacts: u64,
714 pub artifact_duration_p50_ms: u64,
716 pub artifact_duration_p95_ms: u64,
718 pub artifact_duration_p99_ms: u64,
720}
721
722#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Error)]
724#[error(
725 "execution `{run_id}` exceeded {resource:?} during {phase:?}: observed {observed}, maximum {maximum}, completed {completed_units} units"
726)]
727pub struct ExecutionLimitExceeded {
728 pub run_id: String,
730 pub phase: JobPhase,
732 pub resource: ExecutionResource,
734 pub observed: u64,
736 pub maximum: u64,
738 pub completed_units: u64,
740}
741
742#[cfg(test)]
743mod tests {
744 use super::*;
745
746 #[test]
747 fn defaults_should_be_generous_and_finite() {
748 let policy = ExecutionPolicy::default();
749
750 assert_eq!(policy.max_scan_wall_time_ms, 21_600_000);
751 assert_eq!(
752 CodeGraphCorroborationAnchorLimit::try_from(
753 DEFAULT_MAX_CODEGRAPH_CORROBORATION_ANCHORS_PER_REPO
754 )
755 .expect("default anchor limit")
756 .bounded()
757 .map(NonZeroUsize::get),
758 Some(50)
759 );
760 assert_eq!(policy.max_worker_memory_bytes, 17_179_869_184);
761 assert_eq!(policy.max_checkpoint_cache_bytes, 10_737_418_240);
762 }
763
764 #[test]
765 fn partial_override_should_preserve_other_defaults() {
766 let policy = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
767 max_scan_wall_time_ms: Some(28_800_000),
768 ..ExecutionPolicyOverrides::default()
769 }))
770 .expect("valid override");
771
772 assert_eq!(policy.max_scan_wall_time_ms, 28_800_000);
773 assert_eq!(policy.max_no_progress_time_ms, 300_000);
774 }
775
776 #[test]
777 fn zero_should_be_rejected() {
778 let error = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
779 max_worker_memory_bytes: Some(0),
780 ..ExecutionPolicyOverrides::default()
781 }))
782 .expect_err("zero must fail");
783
784 assert!(matches!(
785 error,
786 InvalidExecutionPolicy::InvalidValue {
787 field: "maxWorkerMemoryBytes",
788 value: 0
789 }
790 ));
791 }
792
793 #[test]
794 fn corroboration_anchor_limit_should_accept_positive_or_unlimited() {
795 let bounded =
796 CodeGraphCorroborationAnchorLimit::try_from(12).expect("positive anchor limit");
797 let unlimited =
798 CodeGraphCorroborationAnchorLimit::try_from(-1).expect("unlimited anchor limit");
799
800 assert_eq!(bounded.bounded().map(NonZeroUsize::get), Some(12));
801 assert_eq!(unlimited.bounded(), None);
802 assert_ne!(
803 ExecutionPolicy::default().fingerprint_with_codegraph_limit(bounded),
804 ExecutionPolicy::default().fingerprint_with_codegraph_limit(unlimited)
805 );
806 assert_eq!(
807 serde_json::to_value(bounded).expect("bounded limit serializes"),
808 serde_json::json!(12)
809 );
810 assert_eq!(
811 serde_json::to_value(unlimited).expect("unlimited limit serializes"),
812 serde_json::json!(-1)
813 );
814 }
815
816 #[test]
817 fn corroboration_anchor_limit_should_reject_zero_and_values_below_sentinel() {
818 for value in [0, -2] {
819 let error = CodeGraphCorroborationAnchorLimit::try_from(value)
820 .expect_err("invalid anchor limit");
821
822 assert!(matches!(
823 error,
824 InvalidExecutionPolicy::InvalidValue {
825 field: "maxCodeGraphCorroborationAnchorsPerRepo",
826 value: observed
827 } if observed == value.unsigned_abs()
828 ));
829 }
830 }
831
832 #[test]
833 fn technically_unrepresentable_values_should_be_rejected() {
834 let quota = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
835 max_checkpoint_cache_bytes: Some(u64::MAX),
836 ..ExecutionPolicyOverrides::default()
837 }))
838 .expect_err("SQLite quota overflow must fail");
839
840 assert!(matches!(quota, InvalidExecutionPolicy::InvalidValue { .. }));
841 }
842
843 #[test]
844 fn mcp_markdown_budgets_should_enforce_the_control_block_minimum() {
845 for overrides in [
846 ExecutionPolicyOverrides {
847 max_mcp_tool_response_bytes: Some(MIN_MCP_MARKDOWN_BYTES - 1),
848 ..ExecutionPolicyOverrides::default()
849 },
850 ExecutionPolicyOverrides {
851 max_mcp_resource_bytes: Some(MIN_MCP_MARKDOWN_BYTES - 1),
852 ..ExecutionPolicyOverrides::default()
853 },
854 ExecutionPolicyOverrides {
855 max_mcp_schema_catalog_bytes: Some(MIN_MCP_MARKDOWN_BYTES - 1),
856 ..ExecutionPolicyOverrides::default()
857 },
858 ] {
859 assert!(matches!(
860 ExecutionPolicy::resolve(Some(&overrides)),
861 Err(InvalidExecutionPolicy::BelowMinimum {
862 minimum: MIN_MCP_MARKDOWN_BYTES,
863 ..
864 })
865 ));
866 }
867
868 let minimum = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
869 max_mcp_tool_response_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
870 max_mcp_resource_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
871 max_mcp_schema_catalog_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
872 max_explore_source_markdown_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
873 max_explore_enrichment_bytes: Some(MIN_MCP_MARKDOWN_BYTES),
874 ..ExecutionPolicyOverrides::default()
875 }));
876 assert!(minimum.is_ok());
877 }
878
879 #[test]
880 fn subordinate_deadline_should_not_exceed_scan_deadline() {
881 let error = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
882 max_scan_wall_time_ms: Some(1_000),
883 max_no_progress_time_ms: Some(1_001),
884 max_codegraph_sync_wall_time_ms_per_repo: Some(1_000),
885 graceful_termination_ms: Some(500),
886 ..ExecutionPolicyOverrides::default()
887 }))
888 .expect_err("relationship must fail");
889
890 assert!(matches!(
891 error,
892 InvalidExecutionPolicy::InvalidRelationship {
893 field: "maxNoProgressTimeMs",
894 ..
895 }
896 ));
897 }
898
899 #[test]
900 fn fingerprint_should_ignore_yaml_field_order() {
901 let first = ExecutionPolicy::default();
902 let second = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides::default()))
903 .expect("defaults valid");
904
905 assert_eq!(first.fingerprint(), second.fingerprint());
906 }
907
908 #[test]
909 fn agent_delivery_limits_should_not_change_scan_fingerprint() {
910 let baseline = ExecutionPolicy::default();
911 let changed = ExecutionPolicy::resolve(Some(&ExecutionPolicyOverrides {
912 max_mcp_tool_response_bytes: Some(600_000),
913 max_explore_source_markdown_bytes: Some(300_000),
914 ..ExecutionPolicyOverrides::default()
915 }))
916 .expect("agent-only override is valid");
917
918 assert_eq!(baseline.scan_fingerprint(), changed.scan_fingerprint());
919 assert_ne!(
920 baseline.agent_delivery_fingerprint(),
921 changed.agent_delivery_fingerprint()
922 );
923 }
924
925 #[test]
926 fn explore_capacity_relationships_should_be_checked() {
927 for overrides in [
928 ExecutionPolicyOverrides {
929 max_explore_anchors: Some(6),
930 ..ExecutionPolicyOverrides::default()
931 },
932 ExecutionPolicyOverrides {
933 max_explore_concurrent_codegraph_processes: Some(9),
934 ..ExecutionPolicyOverrides::default()
935 },
936 ExecutionPolicyOverrides {
937 max_explore_local_relationships: Some(49),
938 ..ExecutionPolicyOverrides::default()
939 },
940 ExecutionPolicyOverrides {
941 max_explore_federated_handoffs: Some(31),
942 ..ExecutionPolicyOverrides::default()
943 },
944 ExecutionPolicyOverrides {
945 max_explore_source_markdown_bytes: Some(524_289),
946 ..ExecutionPolicyOverrides::default()
947 },
948 ] {
949 assert!(matches!(
950 ExecutionPolicy::resolve(Some(&overrides)),
951 Err(InvalidExecutionPolicy::InvalidRelationship { .. })
952 ));
953 }
954 }
955}