Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions pkgs/atlas-search/book/reference/atlas-github-comments.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ Progress is reported on stdout as it goes: an opening `estate: <n> repos`

### Idempotency and dedupe shape

Re-running the tool is the normal case, and it is safe by construction:
Each repository starts from its last completed checkpoint. Issue comments and review comments both compare against the **same starting cutoff**. The per-PR submitted-review walk has its own cutoff and compares every PR to the start of that walk. A new issue comment therefore cannot hide an older eligible review. With `--skip-reviews`, submitted reviews retain their previous position.

- Extraction is **incremental per repository** via the watermark: the state file stores each repo's `updated_at` watermark, and a run only extracts what is newer than the stored mark. Already-extracted comments are not emitted again.
- Watermarks are **persisted after every repository**, not at the end of the run. An interrupted run therefore resumes where it stopped: rerun the same command and the repos already done are skipped by their watermarks, with their records already in `--out`.
- A `gh` failure stops the run, but with state saved: the error carries the suffix `(state saved; rerun resumes)`, and the rerun picks up from the last persisted watermark rather than starting over.
The state file keeps the original `repos` map for comment streams and a `reviews` map for submitted reviews. On the first run with an older state file, the tool uses its saved cutoff for both. Upgrading preserves resume position. Historical omissions below a pre-upgrade cutoff require a separate reconciliation against source records, using a fresh state and separate output.

A completed repository's output is synced before its state is replaced. On a handled failure, the feed removes that repository's partial append and preserves its previous checkpoint. The process holds an advisory lock on the output and on a sibling `.lock` file next to the state. A hard crash between the append and checkpoint can leave replayed output; downstream promotion must deduplicate by source occurrence and revision. The feed's checkpoint only establishes extraction progress. Classification, promotion, publication, and retrieval need their own receipts.

### The HTTP 451 exception

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,13 @@ struct RepoCounts {

fn extract_repo(
repo: &str,
state: &mut CommentWatermarks,
baseline: &CommentWatermarks,
pending: &mut CommentWatermarks,
skip_reviews: bool,
observed_date: &str,
out: &mut fs::File,
) -> Result<RepoCounts, String> {
let since = state.since_for(repo).map(str::to_string);
let since = baseline.since_for(repo).map(str::to_string);
let since_q = since
.as_deref()
.map(|s| format!("&since={s}"))
Expand Down Expand Up @@ -248,17 +249,16 @@ fn extract_repo(
})
})
.collect();
for c in state.select_delta(repo, &comments) {
for c in baseline.select_delta(repo, &comments) {
let thread = raw
.iter()
.find(|r| r.get("id").and_then(Json::as_u64) == Some(c.id))
.and_then(|r| thread_number(r, "issue_url"))
.and_then(|n| threads.get(&n));
if let Some(thread) = thread {
emit(thread, c, &mut counts)?;
counts.issue_comments += 1;
}
state.observe(repo, &c.updated_at);
let thread = thread.ok_or("missing thread context for issue comment")?;
emit(thread, c, &mut counts)?;
counts.issue_comments += 1;
pending.observe(repo, &c.updated_at);
}

// Review comments (repo-wide stream, watermark-bounded).
Expand All @@ -279,17 +279,16 @@ fn extract_repo(
})
})
.collect();
for c in state.select_delta(repo, &comments) {
for c in baseline.select_delta(repo, &comments) {
let thread = raw
.iter()
.find(|r| r.get("id").and_then(Json::as_u64) == Some(c.id))
.and_then(|r| thread_number(r, "pull_request_url"))
.and_then(|n| threads.get(&n));
if let Some(thread) = thread {
emit(thread, c, &mut counts)?;
counts.review_comments += 1;
}
state.observe(repo, &c.updated_at);
let thread = thread.ok_or("missing thread context for review comment")?;
emit(thread, c, &mut counts)?;
counts.review_comments += 1;
pending.observe(repo, &c.updated_at);
}

// Reviews: no repo-wide stream exists, so walk the PR
Expand Down Expand Up @@ -318,12 +317,18 @@ fn extract_repo(
})
})
.collect();
for c in state.select_delta(repo, &reviews) {
for c in &reviews {
if baseline
.reviews_since_for(repo)
.is_some_and(|since| c.updated_at.as_str() <= since)
{
continue;
}
if let Some(thread) = threads.get(&number) {
emit(thread, c, &mut counts)?;
counts.reviews += 1;
}
state.observe(repo, &c.updated_at);
pending.observe_review(repo, &c.updated_at);
}
}
}
Expand All @@ -348,26 +353,58 @@ fn run() -> Result<(), String> {
} else {
args.repos.clone()
};
let mut lock_name = args.state.as_os_str().to_os_string();
lock_name.push(".lock");
let lock = fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(lock_name)
.map_err(|e| format!("open watermark lock: {e}"))?;
lock.try_lock()
.map_err(|e| format!("lock watermarks: {e}"))?;
let mut state = load_watermarks(&args.state);
let mut out = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&args.out)
.map_err(|e| format!("open {}: {e}", args.out.display()))?;

out.try_lock().map_err(|e| format!("lock records: {e}"))?;
println!("estate: {} repos", repos.len());
let mut totals = (0usize, 0usize, 0usize, 0usize);
let mut skipped = 0usize;
for repo in &repos {
match extract_repo(
// Filter all streams against completed checkpoints. Rows discovered
// in an earlier branch must never hide a later branch in this pass.
let start = out
.metadata()
.map_err(|e| format!("stat records: {e}"))?
.len();
let mut pending = state.clone();
let result = extract_repo(
repo,
&mut state,
&state,
&mut pending,
args.skip_reviews,
&observed_date,
&mut out,
) {
)
.and_then(|counts| {
out.sync_data().map_err(|e| format!("sync records: {e}"))?;
save_watermarks(&args.state, &pending)?;
Ok(counts)
});
if result.is_err() {
// Roll back only our incomplete repository while holding the
// output lock. Other completed repositories remain committed.
out.set_len(start)
.and_then(|()| out.sync_data())
.map_err(|e| format!("restore records after failed extraction: {e}"))?;
}
match result {
Ok(counts) => {
save_watermarks(&args.state, &state)?;
state = pending;
println!(
"{repo}: issue_comments={} review_comments={} reviews={} documents={}",
counts.issue_comments, counts.review_comments, counts.reviews, counts.documents
Expand All @@ -383,12 +420,10 @@ fn run() -> Result<(), String> {
// the skip and continue; the watermark is left
// unadvanced, so if the block is ever lifted a
// later run extracts the repo in full.
save_watermarks(&args.state, &state)?;
println!("{repo}: skipped — repository access blocked (HTTP 451)");
skipped += 1;
}
Err(e) => {
save_watermarks(&args.state, &state)?;
println!(
"totals: issue_comments={} review_comments={} reviews={} documents={}",
totals.0, totals.1, totals.2, totals.3
Expand Down
40 changes: 33 additions & 7 deletions pkgs/atlas-search/crates/atlas-core/src/github_comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ pub fn document_from_record(record: &Json) -> Option<CommentDocument> {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CommentWatermarks {
repos: BTreeMap<String, String>,
reviews: BTreeMap<String, String>,
}

impl CommentWatermarks {
Expand Down Expand Up @@ -297,10 +298,26 @@ impl CommentWatermarks {
}
}

/// Cutoff for submitted reviews, whose walk can be skipped independently.
pub fn reviews_since_for(&self, repo: &str) -> Option<&str> {
self.reviews.get(repo).map(String::as_str)
}

/// Record a submitted review in a completed review walk.
pub fn observe_review(&mut self, repo: &str, submitted_at: &str) {
if self
.reviews_since_for(repo)
.is_none_or(|old| submitted_at > old)
{
self.reviews
.insert(repo.to_owned(), submitted_at.to_owned());
}
}

/// Serialise the state as the JSON the extraction CLI
/// persists between runs.
pub fn to_json(&self) -> Json {
json!({ "repos": self.repos })
json!({ "repos": self.repos, "reviews": self.reviews })
}

/// Load state persisted by [`CommentWatermarks::to_json`];
Expand All @@ -309,13 +326,22 @@ impl CommentWatermarks {
/// silently skipping comments.
pub fn from_json(value: &Json) -> Self {
let mut state = CommentWatermarks::new();
if let Some(repos) = value.get("repos").and_then(Json::as_object) {
for (repo, wm) in repos {
if let Some(wm) = wm.as_str() {
state.repos.insert(repo.clone(), wm.to_string());
}
}
fn read_map(value: Option<&Json>) -> BTreeMap<String, String> {
value
.and_then(Json::as_object)
.into_iter()
.flatten()
.filter_map(|(repo, wm)| Some((repo.clone(), wm.as_str()?.to_string())))
.collect()
}
state.repos = read_map(value.get("repos"));
// V1 persisted a single cutoff for every stream. Preserve its resume
// position on upgrade. An explicit empty reviews map means no review
// pass has completed yet, e.g. after running with --skip-reviews.
state.reviews = match value.get("reviews") {
Some(reviews) => read_map(Some(reviews)),
None => state.repos.clone(),
};
state
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//! Exercise the production CLI across multiple runs using the synthetic gh fixture.
use std::process::Command;

#[test]
fn github_comments_checkpoint_preserves_eligible_records() {
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/test_github_comments_checkpoint.py"
);
let status = Command::new("python3")
.arg(fixture)
.arg(env!("CARGO_BIN_EXE_atlas-github-comments"))
.status()
.expect("run Python 3 synthetic GitHub CLI fixture");
assert!(status.success(), "checkpoint CLI oracle failed: {status}");
}
71 changes: 71 additions & 0 deletions pkgs/atlas-search/tests/test_github_comments_checkpoint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Offline CLI oracle: stable cutoff, independent review cursor, and handled-error recovery."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile

REPO = "developing-today/atlas-fixture"
BASE = "2026-01-01T00:00:00Z"
FAKE_GH = """#!/usr/bin/env python3
import json, os, sys
route = sys.argv[2].split("?")[0]
def stamp(n):
return f"2026-01-01T00:00:0{n}Z"
def record(n, key, thread):
return {"id":n, "user":{"login":"fixture"}, "body":"fixture",
"created_at":stamp(n), "submitted_at":stamp(n), "updated_at":stamp(n),
key:f"https://api.github.com/repos/developing-today/atlas-fixture/issues/{thread}"}
if route.endswith("/issues"):
rows = [{"number":n, "pull_request":{}, "labels":[]} for n in (1, 2)]
elif route.endswith("/issues/comments"):
rows = [record(5, "issue_url", 1)]
elif route.endswith("/pulls/comments"):
rows = [record(3, "pull_request_url", 2)]
elif route.endswith("/pulls/1/reviews"):
rows = [record(4, "unused", 1)]
elif route.endswith("/pulls/2/reviews"):
if os.environ.get("FIXTURE_FAILURE"):
sys.exit(1)
rows = [record(2, "unused", 2)]
else:
raise SystemExit("unexpected fixture route")
for row in rows:
print(json.dumps(row))
"""


def exercise(directory, cli):
gh = directory / "gh"
gh.write_text(FAKE_GH)
gh.chmod(0o700)
state = directory / "state.json"
output = directory / "records.jsonl"
initial = json.dumps({"repos": {REPO: BASE}})
state.write_text(initial)
output.write_text("")
env = dict(os.environ, PATH=f"{directory}:{os.environ['PATH']}")
cmd = [str(cli), "--repo", REPO, "--state", str(state), "--out", str(output),
"--observed-date", "2026-01-02"]

def ids():
return [json.loads(line)["comment_id"] for line in output.read_text().splitlines()]

# Independent oracle: an unsuccessful last stream leaves the entire prior
# checkpoint and append unchanged. Successful retry emits every eligible ID.
failure = subprocess.run(cmd, env=dict(env, FIXTURE_FAILURE="1"), capture_output=True)
assert failure.returncode == 1 and b"rerun resumes" in failure.stderr
assert state.read_text() == initial and ids() == []
Comment on lines +55 to +59

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add property-based coverage for the new checkpoint invariants

The new checkpoint behavior is covered only by a fixed fixture with four records and one failure position. The repository's Testing doctrine explicitly requires property-based tests for state-machine and serialization invariants; example-based acceptance tests do not replace them. Add proptest coverage generating timestamp orderings and skip/retry sequences, checking that cursors never regress, skipped reviews retain their cutoff, and failed repository passes preserve the prior checkpoint and output. proptest is already an atlas-core dev-dependency.

AGENTS.md reference: AGENTS.md:L34-L39

Useful? React with 👍 / 👎.

subprocess.run(cmd + ["--skip-reviews"], env=env, check=True)
assert ids() == [5, 3]
assert json.loads(state.read_text())["reviews"][REPO] == BASE
subprocess.run(cmd, env=env, check=True)
assert ids() == [5, 3, 4, 2]
subprocess.run(cmd, env=env, check=True)
assert ids() == [5, 3, 4, 2]


if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
exercise(Path(tmp), Path(sys.argv[1]).resolve())