BUG: XMP metadata export permanently overwrites file modification timestamp (mtime), destroying photo dates

Abierto Apto para principiantes
#1,788 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 3 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
76/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python

Línea de trabajo

Lee _atomic_replace en backend/app/utils/xmp/containers/png.py y el manejo de marcas de tiempo en backend/app/utils/xmp/exporter.py. Comprueba cómo las pruebas del contenedor PNG cubren el reemplazo atómico y, después de conservar las marcas de tiempo originales de acceso y modificación, ejecuta las pruebas pertinentes. La tarea está terminada cuando un PNG exportado conserva su mtime original.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug enhancement
Is there an existing issue for this?
  • I have searched the existing issues
What happened?

In backend/app/utils/xmp/exporter.py, the metadata export service explicitly documents and relies on preserving the file's modification timestamp (mtime) so folder rescans and external sync services do not treat the file as freshly edited:

# backend/app/utils/xmp/exporter.py:119-122
if outcome is WriteOutcome.WRITTEN:
    # The write kept mtime but changed the size; without this the
    # folder rescan would treat the file as edited.
    db_refresh_image_file_stat(image_id, stat.st_size, int(stat.st_mtime))
    summary["written"] += 1

However, examining _atomic_replace in backend/app/utils/xmp/containers/png.py:

# backend/app/utils/xmp/containers/png.py:145-175
def _atomic_replace(path: str, content: bytes, before: os.stat_result) -> None:
    ...
    fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
    try:
        with os.fdopen(fd, "wb") as tmp:
            tmp.write(content)
            tmp.flush()
            os.fsync(tmp.fileno())
        try:
            os.chmod(tmp_path, before.st_mode & 0o777)
        except OSError:
            pass

        now = os.stat(path)
        if (now.st_size, now.st_mtime_ns) != (before.st_size, before.st_mtime_ns):
            raise FileChangedError(f"{path} changed during metadata write")

        os.replace(tmp_path, path)

_atomic_replace preserves file permissions via os.chmod, but never calls os.utime() to restore the original timestamps.

When os.replace(tmp_path, path) replaces the target file, the file's modification time (mtime) is permanently overwritten with the current wall-clock time.

Impact
  1. Destruction of Photo Dates: Many images (such as screenshots, scans, converted PNGs, or photos shared via messaging apps) do not have internal EXIF DateTimeOriginal tags. For these images, PictoPy and external viewers rely on filesystem mtime as the photo creation date. Exporting metadata resets their mtime to the current timestamp, permanently destroying their original chronological order.
  2. Rescan and Sync Loops: Filesystem watchers and backup tools detect the updated mtime as a new external modification, triggering unnecessary re-indexing and synchronization churn.
Steps to Reproduce
  1. Choose a PNG image and note its stat.st_mtime (e.g. dated 2 years ago).
  2. Enable or trigger XMP metadata export (POST /metadata-export/run).
  3. Check stat.st_mtime of the file after the export completes.
  4. The file's mtime has changed to the current execution timestamp rather than preserving the original timestamp.
Expected Behavior

_atomic_replace should preserve before.st_atime_ns and before.st_mtime_ns on tmp_path before calling os.replace, ensuring the file modification timestamp remains unchanged after metadata embedding.

Proposed Fix

In backend/app/utils/xmp/containers/png.py, preserve the timestamp using os.utime:

try:
    os.utime(tmp_path, ns=(before.st_atime_ns, before.st_mtime_ns))
except OSError:
    pass
os.replace(tmp_path, path)
Record
  • I agree to follow this project's Code of Conduct
Lenguaje dominante
Python
Estrellas
322
Forks
793
Merge medio
6 d 11 h
PR fusionados (30 d)
21

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de AOSSIE-Org/PictoPy

Todos los issues de AOSSIE-Org/PictoPy

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.