Skip to content

Commit 8864c22

Browse files
authored
perf(location): read sync pages back to back and check git HEAD at most every 2 s (#1454)
* perf(location): read sync pages back to back and ask git for HEAD at most every 2 s A synchronization sent one 100-row page per 250 ms watch tick, so a 10,000-row reconcile spent most of its time waiting for the next tick. While a sync has a page due, the loop now skips the tick; idle work polling is unchanged. Only the watch tick asks git for HEAD, at most every 2 s; the work and metadata fences compare project files only. The SQLite consumption lifecycle case now inserts recorded_at as text, the way the writer does. * test(location): take the held-lock case's warehouse lock between syncs The DuckDB overlap case took its write lock while the restored sync was still reading, so the busy report landed on whichever table that sync had reached. With pages read back to back that is no longer source_freshness. The case now waits for the sync to finish and expects the next sync's first table to report the lock.
1 parent dba15f4 commit 8864c22

11 files changed

Lines changed: 241 additions & 25 deletions

File tree

‎benchmarks/duckshop/edge_cases/orchestration/incremental_warehouse_history.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
"held_write_lock": {
1919
"duckdb": [
2020
{
21-
"held": {"failure": "busy", "tables": ["source_freshness"]},
21+
"held": {"failure": "busy", "tables": ["fingerprints"]},
2222
"released": {"failure": null, "tables": ["fingerprints", "source_freshness"]}
2323
}
2424
],

‎crates/sqlbuild-cli/src/native_commands/_helpers/execution.rs‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
5454
use tokio::process::{Child, Command};
5555
use tokio::sync::{mpsc, oneshot, watch};
5656
use tokio::task::JoinSet;
57-
use tokio::time::{Instant, MissedTickBehavior};
57+
use tokio::time::{Instant, Interval, MissedTickBehavior};
5858
use uuid::Uuid;
5959

6060
use crate::argv::models::{Namespace, Stream, Value};
@@ -86,8 +86,8 @@ use crate::native_commands::main::_run_control::run_control;
8686
use crate::native_commands::main::_run_cost::run_cost;
8787
use crate::native_commands::models::{
8888
CommandOutput, InstalledPackage, LocationCompileRequest, LocationCompiler,
89-
LocationMetadataPage, LocationMetadataSync, LocationServe, LostStdout, MetadataReply,
90-
NativeCommand, NativeInvocation, ProjectLocation, ScanToken,
89+
LocationMetadataPage, LocationMetadataSync, LocationServe, LocationWatch, LostStdout,
90+
MetadataReply, NativeCommand, NativeInvocation, ProjectLocation, ScanToken,
9191
};
9292
use crate::native_commands::types::LocationPublication;
9393
use crate::workers::main::docker_image_sources::docker_image_sources;
@@ -1310,3 +1310,28 @@ async fn exchange_metadata_read(
13101310
.await;
13111311
(reader, result)
13121312
}
1313+
1314+
/// Wait for the next tick unless a synchronization's next page is due; `Some` means shutdown.
1315+
pub(crate) async fn next_turn(
1316+
clock: &mut Interval,
1317+
(published, watch, metadata): (Option<i64>, &LocationWatch, &Option<LocationMetadataSync>),
1318+
stopped: impl Future<Output = Result<(), ControlError>>,
1319+
) -> Option<Result<(), ControlError>> {
1320+
if published.is_some()
1321+
&& watch.attempted.as_ref() == Some(&watch.observed)
1322+
&& metadata.as_ref().is_some_and(LocationMetadataSync::paging)
1323+
{
1324+
return None;
1325+
}
1326+
tokio::select! {
1327+
result = stopped => Some(result),
1328+
_ = clock.tick() => None,
1329+
}
1330+
}
1331+
1332+
/// The location's 250 ms turn; a slow turn skips missed ticks instead of bursting.
1333+
pub(crate) fn location_clock() -> Interval {
1334+
let mut clock = tokio::time::interval(Duration::from_millis(250));
1335+
clock.set_missed_tick_behavior(MissedTickBehavior::Skip);
1336+
clock
1337+
}

‎crates/sqlbuild-cli/src/native_commands/_helpers/paths.rs‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use sqlbuild_core::git_revisions::main::head_commit::head_commit;
1212
use sqlbuild_rules::project_tree::main::project_real_path::project_real_path;
1313
use tokio::time::Instant;
1414

15+
use crate::native_commands::constants::LOCATION_COMMIT_CHECK_SECONDS;
1516
use crate::native_commands::errors::PythonNeeded;
1617
use crate::native_commands::models::{LocationWatch, ProjectLocation};
1718
use crate::replay::main::output_file_identities::output_file_identities;
@@ -25,12 +26,16 @@ pub(crate) fn location_watch(root: &Path) -> LocationWatch {
2526
.collect();
2627
let local_files = location_database_files(root, files);
2728
LocationWatch {
28-
observed: location_inputs(root, &rules, &local_files),
29+
observed: (
30+
location_files(root, &rules, &local_files),
31+
head_commit(root),
32+
),
2933
rules,
3034
local_files,
3135
attempted: None,
3236
changed_at: tokio::time::Instant::now(),
3337
retry_at: None,
38+
commit_checked_at: tokio::time::Instant::now(),
3439
}
3540
}
3641

@@ -39,7 +44,18 @@ pub(crate) fn observe_location_inputs(
3944
root: &Path,
4045
mut watch: LocationWatch,
4146
) -> (LocationWatch, bool) {
42-
let current = location_inputs(root, &watch.rules, &watch.local_files);
47+
let commit = if watch.commit_checked_at.elapsed()
48+
>= Duration::from_secs(LOCATION_COMMIT_CHECK_SECONDS)
49+
{
50+
watch.commit_checked_at = Instant::now();
51+
head_commit(root)
52+
} else {
53+
watch.observed.1.clone()
54+
};
55+
let current = (
56+
location_files(root, &watch.rules, &watch.local_files),
57+
commit,
58+
);
4359
if watch.observed != current {
4460
watch.observed = current;
4561
watch.changed_at = Instant::now();
@@ -74,12 +90,12 @@ fn location_rules() -> SnapshotRules {
7490
}
7591
}
7692

77-
/// Git commits matter to publication metadata even when no working-tree file changes.
78-
pub(crate) fn location_inputs(
93+
/// The project files a location publishes; the watch adds the git commit on its own cadence.
94+
pub(crate) fn location_files(
7995
root: &Path,
8096
rules: &SnapshotRules,
8197
local_files: &[PathBuf],
82-
) -> (Vec<PathStamp>, Option<String>) {
98+
) -> Vec<PathStamp> {
8399
let mut stamps = snapshot_project_files(root, rules);
84100
stamps.retain(|stamp| {
85101
!rules
@@ -107,7 +123,7 @@ pub(crate) fn location_inputs(
107123
});
108124
}
109125
stamps.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
110-
(stamps, head_commit(root))
126+
stamps
111127
}
112128

113129
/// Apply resolved exclusions to retained observations, never a fresh snapshot of possible source edits.

‎crates/sqlbuild-cli/src/native_commands/constants.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,8 @@ pub(crate) const SENSOR_RESULT_BYTES: u64 = 1_048_576;
9494
pub(crate) const METADATA_POLL_SECONDS: u64 = 30;
9595
/// A metadata reader that ignores end of input this long after a synchronization is killed.
9696
pub(crate) const METADATA_READER_CLOSE_SECONDS: u64 = 5;
97+
/// How often a location asks git whether `HEAD` moved.
98+
pub(crate) const LOCATION_COMMIT_CHECK_SECONDS: u64 = 2;
9799
/// How often an idle location asks the server, never the warehouse, whether a run ended.
98100
pub(crate) const METADATA_SYNC_CHECK_SECONDS: u64 = 5;
99101
/// Full key-set reconciliation is independent of the incremental poll and overlap window.

‎crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::native_commands::_helpers::execution::{
1818
metadata_health, next_scan, statistics_page,
1919
};
2020
use crate::native_commands::_helpers::execution::{finish_metadata_page, read_metadata_page};
21-
use crate::native_commands::_helpers::paths::location_inputs;
21+
use crate::native_commands::_helpers::paths::location_files;
2222
use crate::native_commands::_helpers::terminal::write_output;
2323
use crate::native_commands::constants::METADATA_POLL_SECONDS;
2424
use crate::native_commands::models::{LocationMetadataSync, LocationServe, LocationWatch};
@@ -32,7 +32,8 @@ pub(super) async fn sync_location_metadata(
3232
) -> Result<Option<LocationMetadataSync>, ControlError> {
3333
if Instant::now() < state.next_at
3434
|| state.locations.is_empty()
35-
|| location_inputs(&options.project_dir, &watch.rules, &watch.local_files) != watch.observed
35+
|| location_files(&options.project_dir, &watch.rules, &watch.local_files)
36+
!= watch.observed.0
3637
{
3738
return Ok(Some(state));
3839
}
@@ -80,7 +81,8 @@ pub(super) async fn sync_location_metadata(
8081
let Some(page) = page else {
8182
return failed_read(state, (client, poll), started, stopped.as_mut()).await;
8283
};
83-
if location_inputs(&options.project_dir, &watch.rules, &watch.local_files) != watch.observed
84+
if location_files(&options.project_dir, &watch.rules, &watch.local_files)
85+
!= watch.observed.0
8486
{
8587
return Ok(Some(state));
8688
}

‎crates/sqlbuild-cli/src/native_commands/main/_location_work.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use uuid::Uuid;
1515

1616
use crate::argv::models::Stream;
1717
use crate::native_commands::_helpers::execution::check_location_connection;
18-
use crate::native_commands::_helpers::paths::location_inputs;
18+
use crate::native_commands::_helpers::paths::location_files;
1919
use crate::native_commands::_helpers::terminal::write_output;
2020
use crate::native_commands::main::_location_plan::plan_location;
2121
use crate::native_commands::main::_location_sensor::evaluate_location_sensor;
@@ -48,7 +48,8 @@ pub(super) async fn run_location_work(
4848
.unwrap_or_default();
4949
let mut files: Vec<PathBuf> = Vec::new();
5050
let outcome = if generation == Some(claim.generation)
51-
&& location_inputs(&options.project_dir, &watch.rules, &watch.local_files) == watch.observed
51+
&& location_files(&options.project_dir, &watch.rules, &watch.local_files)
52+
== watch.observed.0
5253
{
5354
let mut shutting_down = false;
5455
let expires = async {
@@ -73,7 +74,7 @@ pub(super) async fn run_location_work(
7374
.retain(|stamp| !files.contains(&options.project_dir.join(&stamp.relative_path)));
7475
let mut excluded = watch.local_files.clone();
7576
excluded.extend(files.clone());
76-
if location_inputs(&options.project_dir, &watch.rules, &excluded) == expected {
77+
if location_files(&options.project_dir, &watch.rules, &excluded) == expected.0 {
7778
outcome
7879
} else {
7980
LocationWorkOutcome::Superseded {}

‎crates/sqlbuild-cli/src/native_commands/main/_run_location.rs‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,14 @@ use sqlbuild_orchestration::platform::models::{
1010
};
1111
use sqlbuild_orchestration::store::errors::ControlError;
1212
use tokio::sync::mpsc;
13-
use tokio::time::{Instant, MissedTickBehavior};
13+
use tokio::time::Instant;
1414
use uuid::Uuid;
1515

1616
use crate::argv::models::Stream;
1717
use crate::native_commands::_helpers::execution::{
18-
check_published_location, close_metadata_reader, compile_generation, location_generation,
19-
location_heartbeats, metadata_sync, report_location_health, shutdown_signal,
18+
check_published_location, close_metadata_reader, compile_generation, location_clock,
19+
location_generation, location_heartbeats, metadata_sync, next_turn, report_location_health,
20+
shutdown_signal,
2021
};
2122
use crate::native_commands::_helpers::paths::{
2223
exclude_location_databases, location_watch, observe_location_inputs,
@@ -63,18 +64,22 @@ async fn watch_location(
6364
let mut work_at = Instant::now() + Duration::from_secs(2);
6465
let mut published_generation = None;
6566
let mut metadata = None;
66-
let mut clock = tokio::time::interval(Duration::from_millis(250));
67-
clock.set_missed_tick_behavior(MissedTickBehavior::Skip);
67+
let mut clock = location_clock();
6868
let stopped = shutdown_signal();
6969
tokio::pin!(stopped);
7070
drop(write_output(&[(
7171
Stream::Stderr,
7272
"Starting code location; watching project inputs...\n",
7373
)]));
7474
loop {
75-
tokio::select! {
76-
result = &mut stopped => return result,
77-
_ = clock.tick() => {},
75+
if let Some(result) = next_turn(
76+
&mut clock,
77+
(published_generation, &watch, &metadata),
78+
stopped.as_mut(),
79+
)
80+
.await
81+
{
82+
return result;
7883
}
7984
let ready;
8085
(watch, ready) = observe_location_inputs(&options.project_dir, watch);

‎crates/sqlbuild-cli/src/native_commands/models.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,8 @@ pub(crate) struct LocationWatch {
163163
pub(crate) attempted: Option<(Vec<PathStamp>, Option<String>)>,
164164
pub(crate) changed_at: tokio::time::Instant,
165165
pub(crate) retry_at: Option<tokio::time::Instant>,
166+
/// Git commits matter to publication metadata, but asking git every tick spawns a process each time.
167+
pub(crate) commit_checked_at: tokio::time::Instant,
166168
}
167169

168170
/// A bounded supervisor request; dropping the reply cancels and reaps an active compiler.
@@ -292,6 +294,11 @@ impl LocationMetadataSync {
292294
+ std::time::Duration::from_secs(super::constants::METADATA_POLL_SECONDS);
293295
}
294296

297+
/// A synchronization is mid-flight and its next page is due, so the loop need not wait a tick.
298+
pub(crate) fn paging(&self) -> bool {
299+
!self.idle && tokio::time::Instant::now() >= self.next_at
300+
}
301+
295302
pub(crate) fn reconciling(&self) -> bool {
296303
self.kind() != WarehouseHistoryKind::Statistics
297304
&& (self.reconcile || self.kind() == WarehouseHistoryKind::Catalog)

‎tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,20 @@ class StateEventsTestCase(CatalogConnectionTestCase):
211211
legacy_columns: tuple[str, ...] = ()
212212

213213

214+
@dataclass(frozen=True)
215+
class SyncPacingTestCase:
216+
"""A tick-paced sync waits `added_rows / 100` ticks of 250 ms; git is asked every 2 s."""
217+
218+
description: str
219+
adapter_name: str
220+
connection_key: str
221+
expected_run_id: str
222+
added_rows: int
223+
idle_seconds: float
224+
expected_max_seconds: float
225+
expected_max_git_calls: int
226+
227+
214228
@dataclass(frozen=True)
215229
class AutomaticHistoryTestCase:
216230
description: str

‎tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ def append_consumption_history(adapter: Any, connection: Any, fixture: dict[str,
299299
columns: list[str] = list(fixture["record"])[2:]
300300
types: dict[str, StateSqlValueType] = dict.fromkeys(columns, StateSqlValueType.STRING) | {
301301
"input_count": StateSqlValueType.INTEGER,
302-
"recorded_at": StateSqlValueType.TIMESTAMP,
302+
"recorded_at": StateSqlValueType.TEXT_TIMESTAMP,
303303
}
304304
rows: list[dict[str, Any]] = [
305305
row | {"recorded_at": datetime.fromisoformat(row["recorded_at"])}
@@ -525,6 +525,18 @@ def wait_for_log(
525525
time.sleep(0.02)
526526

527527

528+
def wait_for_idle_sync(process: subprocess.Popen[bytes], log: Path) -> None:
529+
"""Wait until the latest synchronization has completed, so a held lock meets the next one."""
530+
531+
deadline: float = time.monotonic() + 45
532+
text: str = log.read_text()
533+
while text.rfind("synchronization completed.") < text.rfind("Reading warehouse history"):
534+
assert process.poll() is None, text
535+
assert time.monotonic() < deadline, text
536+
time.sleep(0.05)
537+
text = log.read_text()
538+
539+
528540
def location_health_reports(api: SnapshotApi) -> list[dict[str, Any]]:
529541
request: Request = Request(
530542
f"{api.url}/api/locations/{api.location_id}/health",

0 commit comments

Comments
 (0)