1use std::sync::Arc;
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use tracing::{info, warn};
16
17use ailake_catalog::{
18 make_multi_column_data_file_entry, new_snapshot_id, CatalogProvider, ExtraVectorIndex,
19 NewSnapshot, SnapshotOperation, TableIdent, VectorIndexInfo,
20};
21use ailake_core::{AilakeError, AilakeResult, VectorStoragePolicy};
22use ailake_file::{AilakeFileReader, AilakeFileWriter, VectorColumnBatch};
23use ailake_store::Store;
24use ailake_vec::compute_centroid_and_radius;
25use arrow_array::{
26 Array, Float32Array, RecordBatch, TimestampMicrosecondArray, TimestampNanosecondArray,
27};
28use arrow_schema::{DataType, Field};
29
30const LAST_ACCESSED_COL: &str = "last_accessed_at";
31const RECENCY_WEIGHT_COL: &str = "recency_weight";
32
33pub struct MemoryDecayJob {
49 catalog: Arc<dyn CatalogProvider>,
50 store: Arc<dyn Store>,
51 policy: VectorStoragePolicy,
52 pub decay_lambda: f32,
55}
56
57impl MemoryDecayJob {
58 pub fn new(
59 catalog: Arc<dyn CatalogProvider>,
60 store: Arc<dyn Store>,
61 policy: VectorStoragePolicy,
62 decay_lambda: f32,
63 ) -> Self {
64 Self {
65 catalog,
66 store,
67 policy,
68 decay_lambda,
69 }
70 }
71
72 pub async fn run(&self, table: &TableIdent) -> AilakeResult<usize> {
77 let files = self.catalog.list_files(table, None).await?;
78 if files.is_empty() {
79 return Ok(0);
80 }
81
82 let today_day = current_day_since_epoch();
83 let mut new_entries = Vec::with_capacity(files.len());
84 let mut updated = 0usize;
85
86 for file_entry in &files {
87 let file_bytes = self.store.get(&file_entry.path).await?;
88 let orig_bytes = file_bytes.clone();
90 let reader =
91 AilakeFileReader::new(file_bytes, &self.policy.column_name, self.policy.dim);
92
93 if !reader.is_ailake_file() {
94 new_entries.push(file_entry.clone());
96 continue;
97 }
98
99 let (batch, embeddings) = match reader.read_parquet() {
100 Ok(pair) => pair,
101 Err(e) => {
102 warn!(
103 "ailake: MemoryDecayJob skipping {} — read error: {}",
104 file_entry.path, e
105 );
106 new_entries.push(file_entry.clone());
107 continue;
108 }
109 };
110
111 if batch.column_by_name(LAST_ACCESSED_COL).is_none() {
112 new_entries.push(file_entry.clone());
114 continue;
115 }
116
117 let updated_batch = apply_decay(&batch, today_day, self.decay_lambda)?;
118
119 let extra_embeddings: Vec<(String, u32, Vec<Vec<f32>>)> = file_entry
121 .extra_vector_indexes
122 .iter()
123 .filter_map(|xi| {
124 let r = AilakeFileReader::new(orig_bytes.clone(), &xi.column, xi.dim);
125 r.read_parquet()
126 .ok()
127 .map(|(_, embs)| (xi.column.clone(), xi.dim, embs))
128 })
129 .collect();
130
131 let file_writer = AilakeFileWriter::new(self.policy.clone());
133 let new_bytes = if extra_embeddings.is_empty() {
134 file_writer.write(&updated_batch, &embeddings)?
135 } else {
136 let extra_policies: Vec<VectorStoragePolicy> = extra_embeddings
138 .iter()
139 .map(|(col, dim, _)| VectorStoragePolicy {
140 column_name: col.clone(),
141 dim: *dim,
142 metric: self.policy.metric,
143 precision: self.policy.precision,
144 pq: None,
145 keep_raw_for_reranking: false,
146 pre_normalize: false,
147 hnsw_m: None,
148 hnsw_ef_construction: None,
149 ivf_residual: false,
150 embedding_model: None,
151 modality: None,
152 partition_by: None,
153 partition_value: None,
154 partition_column_type: None,
155 partition_fields: vec![],
156 })
157 .collect();
158 let primary_col = VectorColumnBatch {
159 policy: &self.policy,
160 embeddings: &embeddings,
161 };
162 let mut col_batches: Vec<VectorColumnBatch<'_>> = vec![primary_col];
163 for (policy, (_, _, embs)) in extra_policies.iter().zip(extra_embeddings.iter()) {
164 col_batches.push(VectorColumnBatch {
165 policy,
166 embeddings: embs,
167 });
168 }
169 file_writer.write_multi(&updated_batch, &col_batches)?
170 };
171 let new_size = new_bytes.len() as u64;
172 let new_bytes_ref = new_bytes.clone();
174 self.store.put(&file_entry.path, new_bytes.clone()).await?;
175
176 let centroid = compute_centroid_and_radius(&embeddings, self.policy.metric);
177 let new_reader =
178 AilakeFileReader::new(new_bytes, &self.policy.column_name, self.policy.dim);
179 let header = new_reader.read_header()?;
180 let ailk_start = new_reader.ailk_offset()?;
181
182 let new_extra: Vec<ExtraVectorIndex> = extra_embeddings
184 .iter()
185 .filter_map(|(col, dim, _)| {
186 let xr = AilakeFileReader::new(new_bytes_ref.clone(), col, *dim);
187 let xailk = xr.ailk_offset_for_column(col).ok()?;
188 let xhdr = xr.read_header_for_column(col).ok()?;
189 Some(ExtraVectorIndex {
190 column: col.clone(),
191 dim: *dim,
192 hnsw_offset: xailk + xhdr.hnsw_offset,
193 hnsw_len: xhdr.hnsw_len,
194 centroid_b64: None,
195 radius: None,
196 })
197 })
198 .collect();
199
200 let new_entry = make_multi_column_data_file_entry(
201 &file_entry.path,
202 updated_batch.num_rows() as u64,
203 new_size,
204 ¢roid,
205 VectorIndexInfo {
206 column: &self.policy.column_name,
207 dim: self.policy.dim,
208 hnsw_offset: ailk_start + header.hnsw_offset,
209 hnsw_len: header.hnsw_len,
210 },
211 &new_extra,
212 );
213 new_entries.push(new_entry);
214 updated += 1;
215 }
216
217 if updated == 0 {
218 info!(
219 "ailake: MemoryDecayJob — no files with last_accessed_at column; skipping commit"
220 );
221 return Ok(0);
222 }
223
224 let snap = NewSnapshot {
225 snapshot_id: new_snapshot_id(),
226 parent_snapshot_id: None,
227 files: new_entries,
228 operation: SnapshotOperation::Overwrite,
229 iceberg_schema: None,
230 extra_properties: std::collections::HashMap::new(),
231 bloom_filters: vec![],
232 equality_delete_files: vec![],
233 };
234 self.catalog.commit_snapshot(table, snap).await?;
235 info!(
236 "ailake: MemoryDecayJob — updated recency_weight in {} files (lambda={})",
237 updated, self.decay_lambda
238 );
239 Ok(updated)
240 }
241}
242
243fn days_old_vec(col: &Arc<dyn Array>, today_day: i64) -> AilakeResult<Vec<f32>> {
245 if let Some(ts) = col.as_any().downcast_ref::<TimestampNanosecondArray>() {
246 return Ok((0..ts.len())
247 .map(|i| {
248 if !ts.is_valid(i) {
249 return 0.0f32;
250 }
251 let day = ts.value(i) / (86_400 * 1_000_000_000i64);
252 (today_day - day).max(0) as f32
253 })
254 .collect());
255 }
256 if let Some(ts) = col.as_any().downcast_ref::<TimestampMicrosecondArray>() {
257 return Ok((0..ts.len())
258 .map(|i| {
259 if !ts.is_valid(i) {
260 return 0.0f32;
261 }
262 let day = ts.value(i) / (86_400 * 1_000_000i64);
263 (today_day - day).max(0) as f32
264 })
265 .collect());
266 }
267 if let Some(sa) = col.as_any().downcast_ref::<arrow_array::StringArray>() {
268 return Ok((0..sa.len())
269 .map(|i| {
270 if !sa.is_valid(i) {
271 return 0.0f32;
272 }
273 let access_day = parse_iso_date_days(sa.value(i)).unwrap_or(today_day);
274 (today_day - access_day).max(0) as f32
275 })
276 .collect());
277 }
278 Err(AilakeError::Catalog(
279 "last_accessed_at must be Timestamp(Nanosecond/Microsecond) or Utf8".into(),
280 ))
281}
282
283fn apply_decay(batch: &RecordBatch, today_day: i64, lambda: f32) -> AilakeResult<RecordBatch> {
285 let col = batch
286 .column_by_name(LAST_ACCESSED_COL)
287 .ok_or_else(|| AilakeError::Catalog("last_accessed_at column not found".into()))?;
288
289 let days_old = days_old_vec(col, today_day)?;
290 let new_weights: Vec<f32> = days_old.into_iter().map(|d| (-lambda * d).exp()).collect();
291
292 let new_weight_array = Arc::new(Float32Array::from(new_weights));
293
294 let old_schema = batch.schema();
296 let decay_field = Field::new(RECENCY_WEIGHT_COL, DataType::Float32, false);
297
298 let mut new_fields: Vec<arrow_schema::FieldRef> = old_schema.fields().iter().cloned().collect();
299 let mut new_columns: Vec<Arc<dyn Array>> = (0..batch.num_columns())
300 .map(|i| batch.column(i).clone())
301 .collect();
302
303 if let Some(pos) = old_schema
304 .fields()
305 .iter()
306 .position(|f| f.name() == RECENCY_WEIGHT_COL)
307 {
308 new_fields[pos] = Arc::new(decay_field);
309 new_columns[pos] = new_weight_array;
310 } else {
311 new_fields.push(Arc::new(decay_field));
312 new_columns.push(new_weight_array);
313 }
314
315 let new_schema = Arc::new(arrow_schema::Schema::new(new_fields));
316 RecordBatch::try_new(new_schema, new_columns).map_err(|e| AilakeError::Arrow(e.to_string()))
317}
318
319fn parse_iso_date_days(s: &str) -> Option<i64> {
322 if s.len() < 10 {
323 return None;
324 }
325 let y: i64 = s[0..4].parse().ok()?;
326 let m: i64 = s[5..7].parse().ok()?;
327 let d: i64 = s[8..10].parse().ok()?;
328 let a = (14 - m) / 12;
330 let y2 = y + 4800 - a;
331 let m2 = m + 12 * a - 3;
332 let jdn = d + (153 * m2 + 2) / 5 + 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 - 32045;
333 Some(jdn - 2440588)
335}
336
337fn current_day_since_epoch() -> i64 {
338 SystemTime::now()
339 .duration_since(UNIX_EPOCH)
340 .map(|d| d.as_secs() as i64 / 86400)
341 .unwrap_or(0)
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 #[test]
349 fn parse_iso_date_unix_epoch() {
350 assert_eq!(parse_iso_date_days("1970-01-01T00:00:00"), Some(0));
351 }
352
353 #[test]
354 fn parse_iso_date_known_date() {
355 let days = parse_iso_date_days("2024-01-15").unwrap();
357 assert_eq!(days, 19737);
359 }
360
361 #[test]
362 fn parse_iso_date_returns_none_on_short_string() {
363 assert!(parse_iso_date_days("2024").is_none());
364 assert!(parse_iso_date_days("").is_none());
365 }
366
367 #[test]
368 fn apply_decay_updates_recency_weight() {
369 use arrow_array::StringArray;
370 use arrow_schema::{Field, Schema};
371
372 let today = current_day_since_epoch();
373 let past_day = today - 10;
375 let y = 1970 + past_day / 365; let past_str = "2024-01-05T00:00:00"; let schema = Arc::new(Schema::new(vec![
380 Field::new(LAST_ACCESSED_COL, DataType::Utf8, true),
381 Field::new(RECENCY_WEIGHT_COL, DataType::Float32, false),
382 ]));
383 let batch = RecordBatch::try_new(
384 schema,
385 vec![
386 Arc::new(StringArray::from(vec![past_str])),
387 Arc::new(Float32Array::from(vec![1.0f32])),
388 ],
389 )
390 .unwrap();
391
392 let today_day = 19737i64;
394 let result = apply_decay(&batch, today_day, 0.1).unwrap();
395 let weights = result
396 .column_by_name(RECENCY_WEIGHT_COL)
397 .unwrap()
398 .as_any()
399 .downcast_ref::<Float32Array>()
400 .unwrap();
401
402 let w = weights.value(0);
403 let expected = (-0.1f32 * 10.0).exp();
405 assert!((w - expected).abs() < 0.001, "expected {expected}, got {w}");
406 let _ = y; }
408
409 #[test]
410 fn apply_decay_handles_timestamp_nanosecond() {
411 use arrow_schema::{Field, Schema, TimeUnit};
412
413 let day_19727_ns: i64 = 19727i64 * 86_400 * 1_000_000_000;
416
417 let schema = Arc::new(Schema::new(vec![
418 Field::new(
419 LAST_ACCESSED_COL,
420 DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
421 true,
422 ),
423 Field::new(RECENCY_WEIGHT_COL, DataType::Float32, false),
424 ]));
425 let batch = RecordBatch::try_new(
426 schema,
427 vec![
428 Arc::new(TimestampNanosecondArray::from(vec![day_19727_ns]).with_timezone("UTC")),
429 Arc::new(Float32Array::from(vec![1.0f32])),
430 ],
431 )
432 .unwrap();
433
434 let today_day = 19737i64;
436 let result = apply_decay(&batch, today_day, 0.1).unwrap();
437 let weights = result
438 .column_by_name(RECENCY_WEIGHT_COL)
439 .unwrap()
440 .as_any()
441 .downcast_ref::<Float32Array>()
442 .unwrap();
443 let w = weights.value(0);
444 let expected = (-0.1f32 * 10.0).exp();
445 assert!((w - expected).abs() < 0.001, "expected {expected}, got {w}");
446 }
447
448 #[test]
449 fn now_ns_is_recent() {
450 let floor_2025_ns: i64 = 55 * 365 * 86_400 * 1_000_000_000i64; let t = ailake_core::now_ns();
453 assert!(
454 t > floor_2025_ns,
455 "now_ns() returned suspiciously small value: {t}"
456 );
457 }
458}