1use crate::PredictionProvider;
2use crate::metrics::ClassificationMetrics;
3use crate::paths::WORKTREES_DIR;
4use crate::qa::QaResult;
5use anyhow::{Context as _, Result};
6use collections::HashMap;
7use edit_prediction::example_spec::ExampleSpec;
8use edit_prediction::udiff::OpenedBuffers;
9use gpui::Entity;
10use http_client::Url;
11use language::{Anchor, Buffer};
12use project::Project;
13use serde::{Deserialize, Serialize};
14use std::{
15 borrow::Cow,
16 collections::VecDeque,
17 io::Read,
18 path::{Path, PathBuf},
19};
20use zeta_prompt::ZetaPromptInput;
21
22#[derive(Clone, Debug, Serialize, Deserialize)]
23pub struct Example {
24 #[serde(flatten)]
25 pub spec: ExampleSpec,
26
27 /// The full content of the file where an edit is being predicted, and the
28 /// actual cursor offset.
29 #[serde(skip_serializing_if = "Option::is_none")]
30 pub prompt_inputs: Option<ZetaPromptInput>,
31
32 /// The input and expected output from the edit prediction model.
33 #[serde(skip_serializing_if = "Option::is_none")]
34 pub prompt: Option<ExamplePrompt>,
35
36 /// The actual predictions from the model.
37 #[serde(default, skip_serializing_if = "Vec::is_empty")]
38 pub predictions: Vec<ExamplePrediction>,
39
40 /// The scores, for how well the actual predictions match the expected
41 /// predictions.
42 #[serde(default, skip_serializing_if = "Vec::is_empty")]
43 pub score: Vec<ExampleScore>,
44
45 /// QA evaluation results for each prediction (indexed parallel to `predictions`).
46 #[serde(default, skip_serializing_if = "Vec::is_empty")]
47 pub qa: Vec<Option<QaResult>>,
48
49 /// The Zed version used to generate this example.
50 pub zed_version: Option<String>,
51
52 /// The application state used to process this example.
53 #[serde(skip)]
54 pub state: Option<ExampleState>,
55}
56
57#[derive(Clone, Debug)]
58pub struct ExampleState {
59 pub project: Entity<Project>,
60 pub buffer: Entity<Buffer>,
61 pub cursor_position: Anchor,
62 pub _open_buffers: OpenedBuffers,
63}
64
65#[derive(Clone, Debug, Serialize, Deserialize)]
66pub struct ExamplePrompt {
67 pub input: String,
68 pub expected_output: String,
69 pub rejected_output: Option<String>, // For DPO
70 #[serde(default)]
71 pub prefill: Option<String>,
72 pub provider: PredictionProvider,
73}
74
75#[derive(Clone, Debug, Serialize, Deserialize)]
76pub struct ExamplePrediction {
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub actual_patch: Option<String>,
79 #[serde(deserialize_with = "deserialize_null_as_empty_string")]
80 pub actual_output: String,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub actual_cursor: Option<ActualCursor>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub error: Option<String>,
85 pub provider: PredictionProvider,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub cumulative_logprob: Option<f64>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub avg_logprob: Option<f64>,
90}
91
92#[derive(Clone, Debug, Serialize, Deserialize)]
93pub struct ActualCursor {
94 pub path: String,
95 pub row: u32,
96 pub column: u32,
97 pub offset: usize,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub editable_region_offset: Option<usize>,
100}
101
102impl ActualCursor {
103 /// Construct an `ActualCursor` from a cursor offset within the new editable region.
104 ///
105 /// - `path`: file path the cursor is in
106 /// - `editable_region_cursor_offset`: byte offset of the cursor within the new editable region text
107 /// - `new_editable_region`: the full new editable region text (after marker removal)
108 /// - `content`: the full file content (before the edit)
109 /// - `editable_region_byte_offset`: byte offset where the editable region starts in `content`
110 /// - `editable_region_start_line`: 0-based line number where the editable region starts in `content`
111 pub fn from_editable_region(
112 path: &std::path::Path,
113 editable_region_cursor_offset: usize,
114 new_editable_region: &str,
115 content: &str,
116 editable_region_byte_offset: usize,
117 editable_region_start_line: usize,
118 ) -> Self {
119 let global_offset = editable_region_byte_offset + editable_region_cursor_offset;
120 let new_region_prefix = &new_editable_region[..editable_region_cursor_offset];
121 let row = (editable_region_start_line + new_region_prefix.matches('\n').count()) as u32;
122 let column = match new_region_prefix.rfind('\n') {
123 Some(pos) => (editable_region_cursor_offset - pos - 1) as u32,
124 None => {
125 let content_prefix = &content[..editable_region_byte_offset];
126 let content_column = match content_prefix.rfind('\n') {
127 Some(pos) => editable_region_byte_offset - pos - 1,
128 None => editable_region_byte_offset,
129 };
130 (content_column + editable_region_cursor_offset) as u32
131 }
132 };
133 ActualCursor {
134 path: path.to_string_lossy().to_string(),
135 row,
136 column,
137 offset: global_offset,
138 editable_region_offset: Some(editable_region_cursor_offset),
139 }
140 }
141}
142
143fn deserialize_null_as_empty_string<'de, D>(deserializer: D) -> Result<String, D::Error>
144where
145 D: serde::Deserializer<'de>,
146{
147 let opt = Option::<String>::deserialize(deserializer)?;
148 Ok(opt.unwrap_or_default())
149}
150
151#[derive(Clone, Debug, Serialize, Deserialize)]
152pub struct ExampleScore {
153 pub delta_chr_f: f32,
154 #[serde(default)]
155 pub delta_chr_f_true_positives: usize,
156 #[serde(default)]
157 pub delta_chr_f_false_positives: usize,
158 #[serde(default)]
159 pub delta_chr_f_false_negatives: usize,
160 #[serde(default)]
161 pub delta_chr_f_precision: f64,
162 #[serde(default)]
163 pub delta_chr_f_recall: f64,
164 #[serde(default)]
165 pub delta_chr_f_beta: f64,
166 pub braces_disbalance: usize,
167 #[serde(default)]
168 pub exact_lines_tp: usize,
169 #[serde(default)]
170 pub exact_lines_fp: usize,
171 #[serde(default)]
172 pub exact_lines_fn: usize,
173 #[serde(default)]
174 pub reversal_ratio: f32,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub cursor_distance: Option<usize>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub cursor_exact_match: Option<bool>,
179 pub wrong_editable_region: Option<bool>,
180 #[serde(default)]
181 pub has_isolated_whitespace_changes: bool,
182 #[serde(default)]
183 pub inserted_tokens: usize,
184 #[serde(default)]
185 pub deleted_tokens: usize,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub kept_rate: Option<f64>,
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub recall_rate: Option<f64>,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub kept_chars: Option<usize>,
192 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub correctly_deleted_chars: Option<usize>,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub discarded_chars: Option<usize>,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub cumulative_logprob: Option<f64>,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub avg_logprob: Option<f64>,
200}
201
202impl ExampleScore {
203 pub fn delta_chr_f_counts(&self) -> ClassificationMetrics {
204 ClassificationMetrics {
205 true_positives: self.delta_chr_f_true_positives,
206 false_positives: self.delta_chr_f_false_positives,
207 false_negatives: self.delta_chr_f_false_negatives,
208 }
209 }
210
211 pub fn exact_lines_counts(&self) -> ClassificationMetrics {
212 ClassificationMetrics {
213 true_positives: self.exact_lines_tp,
214 false_positives: self.exact_lines_fp,
215 false_negatives: self.exact_lines_fn,
216 }
217 }
218}
219
220impl Example {
221 pub fn repo_name(&self) -> Result<RepoName<'_>> {
222 // git@github.com:owner/repo.git
223 if self.spec.repository_url.contains('@') {
224 let (owner, repo) = self
225 .spec
226 .repository_url
227 .split_once(':')
228 .context("expected : in git url")?
229 .1
230 .split_once('/')
231 .context("expected / in git url")?;
232 Ok(RepoName {
233 owner: Cow::Borrowed(owner),
234 name: Cow::Borrowed(repo.trim_end_matches(".git")),
235 })
236 // http://github.com/owner/repo.git
237 } else {
238 let url = Url::parse(&self.spec.repository_url)?;
239 let mut segments = url.path_segments().context("empty http url")?;
240 let owner = segments
241 .next()
242 .context("expected owner path segment")?
243 .to_string();
244 let repo = segments
245 .next()
246 .context("expected repo path segment")?
247 .trim_end_matches(".git")
248 .to_string();
249 assert!(segments.next().is_none());
250
251 Ok(RepoName {
252 owner: Cow::Owned(owner),
253 name: Cow::Owned(repo),
254 })
255 }
256 }
257}
258
259pub struct RepoName<'a> {
260 pub owner: Cow<'a, str>,
261 pub name: Cow<'a, str>,
262}
263
264impl RepoName<'_> {
265 pub fn worktree_path(&self) -> PathBuf {
266 WORKTREES_DIR
267 .join(self.owner.as_ref())
268 .join(self.name.as_ref())
269 }
270}
271
272pub fn read_example_files(inputs: &[PathBuf]) -> Vec<Example> {
273 let mut examples = Vec::new();
274
275 for path in inputs {
276 let is_stdin = path.as_path() == Path::new("-");
277 let content = if is_stdin {
278 let mut buffer = String::new();
279 std::io::stdin()
280 .read_to_string(&mut buffer)
281 .expect("Failed to read from stdin");
282 buffer
283 } else {
284 std::fs::read_to_string(path)
285 .unwrap_or_else(|_| panic!("Failed to read path: {:?}", &path))
286 };
287 let filename = path.file_stem().unwrap().to_string_lossy().to_string();
288 let ext = if !is_stdin {
289 path.extension()
290 .map(|ext| ext.to_string_lossy().to_string())
291 .unwrap_or_else(|| panic!("{} should have an extension", path.display()))
292 } else {
293 "jsonl".to_string()
294 };
295
296 match ext.as_ref() {
297 "json" => {
298 let mut example =
299 serde_json::from_str::<Example>(&content).unwrap_or_else(|error| {
300 panic!("Failed to parse example file: {}\n{error}", path.display())
301 });
302 if example.spec.name.is_empty() {
303 example.spec.name = filename;
304 }
305 examples.push(example);
306 }
307 "jsonl" => examples.extend(
308 content
309 .lines()
310 .enumerate()
311 .map(|(line_ix, line)| {
312 let mut example =
313 serde_json::from_str::<Example>(line).unwrap_or_else(|error| {
314 panic!(
315 "Failed to parse example on {}:{}\n{error}",
316 path.display(),
317 line_ix + 1
318 )
319 });
320 if example.spec.name.is_empty() {
321 example.spec.name = format!("{filename}-{line_ix}")
322 }
323 example
324 })
325 .collect::<Vec<Example>>(),
326 ),
327 "md" => {
328 let mut example = parse_markdown_example(&content).unwrap();
329 if example.spec.name.is_empty() {
330 example.spec.name = filename;
331 }
332 examples.push(example);
333 }
334 ext => {
335 panic!("{} has invalid example extension `{ext}`", path.display())
336 }
337 }
338 }
339
340 examples
341}
342
343pub fn sort_examples_by_repo_and_rev(examples: &mut [Example]) {
344 examples.sort_by(|a, b| {
345 a.spec
346 .repository_url
347 .cmp(&b.spec.repository_url)
348 .then(b.spec.revision.cmp(&a.spec.revision))
349 });
350}
351
352pub fn group_examples_by_repo(examples: Vec<Example>) -> VecDeque<Vec<Example>> {
353 let mut examples_by_repo: HashMap<String, Vec<Example>> = HashMap::default();
354 let mut ungrouped = Vec::new();
355 for example in examples {
356 if example.spec.repository_url.is_empty() {
357 ungrouped.push(example);
358 } else {
359 examples_by_repo
360 .entry(example.spec.repository_url.clone())
361 .or_insert_with(Vec::new)
362 .push(example);
363 }
364 }
365 let mut result: VecDeque<Vec<Example>> = examples_by_repo.into_values().collect();
366 for example in ungrouped {
367 result.push_back(vec![example]);
368 }
369 result
370}
371
372fn parse_markdown_example(input: &str) -> Result<Example> {
373 let spec = ExampleSpec::from_markdown(input)?;
374 Ok(Example {
375 spec,
376 prompt_inputs: None,
377 prompt: None,
378 predictions: Vec::new(),
379 score: Vec::new(),
380 qa: Vec::new(),
381 state: None,
382 zed_version: None,
383 })
384}