Skip to content
Open
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
3 changes: 1 addition & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This file provides guidance to Claude Code when working with code in this reposi

## Project Overview

Kaapi is an AI platform built with FastAPI and PostgreSQL, containerized with Docker. It provides AI capabilities including OpenAI assistants, fine-tuning, document processing, and collection management.
Kaapi is an AI platform built with FastAPI and PostgreSQL, containerized with Docker. It provides AI capabilities including LLM calls, evaluations, document and collection management, and OpenAI assistants.

## Key Commands

Expand Down Expand Up @@ -55,7 +55,6 @@ The backend follows a layered architecture located in `backend/app/`:
- Database connection and session management
- Security (JWT, password hashing, API keys)
- Cloud storage (`cloud/storage.py`)
- Fine-tuning utilities (`finetune/`)
- Langfuse observability integration (`langfuse/`)
- Exception handlers and middleware

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,283 @@
"""drop fine_tuning and model_evaluation

Revision ID: 097
Revises: 096
Create Date: 2026-12-04 00:00:00.000000

The Fine-tuning and Model evaluation modules were removed, so nothing reads or
writes these tables any more. Rows are lost on upgrade; downgrade restores the schema
as it stood at 096 (empty tables) so older code can boot, not the data.

model_evaluation references fine_tuning, so it is dropped first and recreated last.
"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision = "097"
down_revision = "096"
branch_labels = None
depends_on = None


def upgrade():
op.drop_table("model_evaluation")
op.drop_table("fine_tuning")
op.execute("DROP TYPE IF EXISTS modelevaluationstatus")
op.execute("DROP TYPE IF EXISTS finetuningstatus")
Comment on lines +24 to +28

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 (optional) Admins who hard-delete a project or organization during a release rollout get a 500 with "relation fine_tuning does not exist". Migration 097 drops the tables before the ECS rollout replaces the old tasks. Those old tasks still map Project.fine_tuning with cascade_delete=True, so session.delete(project) first SELECTs from fine_tuning. Fix: remove the code in one release and drop the tables in a later one, so no running version still maps them. One way is to merge this change without 097 and add the drop migration afterwards.

Why this was flagged

In .github/workflows/create-release.yml, the "Run database migrations" step runs alembic upgrade head and waits for it to finish. Only then does "Deploy backend service" start the rollout, which has a 15-minute timeout, so old tasks keep serving traffic in that window. On base, backend/app/models/project.py maps fine_tuning: list["FineTuning"] = Relationship(back_populates="project", cascade_delete=True) without passive_deletes. So hard_delete_project (crud/project.py, session.delete(project)) loads that collection, and hard_delete_organization does the same through Organization.project (cascade_delete=True). Once 097 upgrade() has dropped fine_tuning, that load raises ProgrammingError UndefinedTable on old tasks. DELETE requests through api/routes/project.py:253 and api/routes/organization.py:166 then return 500, and the delete is rolled back. The FK ondelete="CASCADE" at the database level does not help, because the ORM issues the SELECT before any DELETE. Before this PR the tables exist, so these deletes work.

Verification: Trigger: an admin hard-deletes a project or organization while old backend tasks are still serving, after migration 097 has run. Old tasks stay in service until the new ones are healthy. In the base crud/project.py (lines 180-181), hard_delete_project calls session.delete(project). The ORM cascade SELECTs from fine_tuning, which migration 097 has dropped, so the request returns a 500.



def downgrade():
lifecycle_status = ("pending", "running", "completed", "failed")
finetuning_status = postgresql.ENUM(*lifecycle_status, name="finetuningstatus")
modelevaluation_status = postgresql.ENUM(
*lifecycle_status, name="modelevaluationstatus"
)

op.create_table(
"fine_tuning",
sa.Column(
"base_model",
sa.String(),
nullable=False,
comment="Base model used for fine-tuning",
),
sa.Column(
"split_ratio",
sa.Float(),
nullable=False,
comment="Train/test split ratio for the dataset",
),
sa.Column(
"document_id",
sa.Uuid(),
nullable=False,
comment="Reference to the training document",
),
sa.Column(
"training_file_id",
sa.String(),
nullable=True,
comment="OpenAI training file identifier",
),
sa.Column(
"system_prompt",
sa.Text(),
nullable=False,
comment="System prompt used during fine-tuning",
),
sa.Column(
"id",
sa.Integer(),
nullable=False,
comment="Unique identifier for the fine-tuning job",
),
sa.Column(
"provider_job_id",
sa.String(),
nullable=True,
comment="Fine-tuning job ID returned by the provider",
),
sa.Column(
"status",
finetuning_status,
server_default="pending",
nullable=False,
comment="Current status of the fine-tuning job",
),
sa.Column(
"fine_tuned_model",
sa.String(),
nullable=True,
comment="Name of the resulting fine-tuned model",
),
sa.Column(
"train_data_s3_object",
sa.String(),
nullable=True,
comment="S3 URL of the training data",
),
sa.Column(
"test_data_s3_object",
sa.String(),
nullable=True,
comment="S3 URL of the testing data",
),
sa.Column(
"error_message",
sa.String(),
nullable=True,
comment="Error message if the job failed",
),
sa.Column(
"project_id",
sa.Integer(),
nullable=False,
comment="Reference to the project",
),
sa.Column(
"organization_id",
sa.Integer(),
nullable=False,
comment="Reference to the organization",
),
sa.Column(
"inserted_at",
sa.DateTime(),
nullable=False,
comment="Timestamp when the job was created",
),
sa.Column(
"updated_at",
sa.DateTime(),
nullable=False,
comment="Timestamp when the job was last updated",
),
sa.Column(
"deleted_at",
sa.DateTime(),
nullable=True,
comment="Timestamp when the job was deleted",
),
sa.ForeignKeyConstraint(["document_id"], ["document.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["organization_id"], ["organization.id"], ondelete="CASCADE"
),
sa.ForeignKeyConstraint(["project_id"], ["project.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_fine_tuning_project_id", "fine_tuning", ["project_id"])
op.create_index(
"ix_fine_tuning_document_project", "fine_tuning", ["document_id", "project_id"]
)

op.create_table(
"model_evaluation",
sa.Column(
"fine_tuning_id",
sa.Integer(),
nullable=False,
comment="Reference to the fine-tuning job",
),
sa.Column(
"id",
sa.Integer(),
nullable=False,
comment="Unique identifier for the model evaluation",
),
sa.Column(
"document_id",
sa.Uuid(),
nullable=False,
comment="Reference to the evaluation document",
),
sa.Column(
"fine_tuned_model",
sa.String(),
nullable=False,
comment="Name of the fine-tuned model being evaluated",
),
sa.Column(
"test_data_s3_object",
sa.String(),
nullable=False,
comment="S3 URI of the testing data",
),
sa.Column(
"base_model",
sa.String(),
nullable=False,
comment="Base model used for fine-tuning",
),
sa.Column(
"split_ratio",
sa.Float(),
nullable=False,
comment="Train/test split ratio used",
),
sa.Column(
"system_prompt",
sa.Text(),
nullable=False,
comment="System prompt used during evaluation",
),
sa.Column(
"score",
sa.JSON(),
nullable=True,
comment="Evaluation scores per metric (e.g., MCC)",
),
sa.Column(
"prediction_data_s3_object",
sa.String(),
nullable=True,
comment="S3 URL where the prediction data is stored",
),
sa.Column(
"status",
modelevaluation_status,
server_default="pending",
nullable=False,
comment="Current status of the evaluation",
),
sa.Column(
"error_message",
sa.String(),
nullable=True,
comment="Error message if evaluation failed",
),
sa.Column(
"project_id",
sa.Integer(),
nullable=False,
comment="Reference to the project",
),
sa.Column(
"organization_id",
sa.Integer(),
nullable=False,
comment="Reference to the organization",
),
sa.Column(
"inserted_at",
sa.DateTime(),
nullable=False,
comment="Timestamp when the evaluation was created",
),
sa.Column(
"updated_at",
sa.DateTime(),
nullable=False,
comment="Timestamp when the evaluation was last updated",
),
sa.Column(
"deleted_at",
sa.DateTime(),
nullable=True,
comment="Timestamp when the evaluation was deleted",
),
sa.ForeignKeyConstraint(["document_id"], ["document.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["fine_tuning_id"], ["fine_tuning.id"], ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["organization_id"], ["organization.id"], ondelete="CASCADE"
),
sa.ForeignKeyConstraint(["project_id"], ["project.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"ix_model_evaluation_project_id", "model_evaluation", ["project_id"]
)
op.create_index(
"ix_model_evaluation_fine_tuning_project",
"model_evaluation",
["fine_tuning_id", "project_id"],
)
op.create_index(
"ix_model_evaluation_document_project_updated_at",
"model_evaluation",
["document_id", "project_id", sa.text("updated_at DESC")],
postgresql_where=sa.text("deleted_at IS NULL"),
)
3 changes: 1 addition & 2 deletions backend/app/api/docs/documents/permanent_delete.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
Permanently delete a document.

The file is removed from cloud storage (e.g., S3) and the database record is deleted. This cannot be undone. Records
that depend on the document, such as its transformed documents, fine-tuning jobs and model
evaluations, are deleted along with it.
that depend on the document, such as its transformed documents, are deleted along with it.

Works on both active and soft-deleted documents. Collections and knowledge bases that contain this document are not
touched.
25 changes: 0 additions & 25 deletions backend/app/api/docs/fine_tuning/create.md

This file was deleted.

7 changes: 0 additions & 7 deletions backend/app/api/docs/fine_tuning/retrieve.md

This file was deleted.

3 changes: 0 additions & 3 deletions backend/app/api/docs/model_evaluation/evaluate.md

This file was deleted.

10 changes: 0 additions & 10 deletions backend/app/api/docs/model_evaluation/examples.py

This file was deleted.

3 changes: 0 additions & 3 deletions backend/app/api/docs/model_evaluation/get_top_model.md

This file was deleted.

3 changes: 0 additions & 3 deletions backend/app/api/docs/model_evaluation/list_by_document.md

This file was deleted.

9 changes: 0 additions & 9 deletions backend/app/api/docs/openapi_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,6 @@
"config and poll or receive the result by webhook, and check whether a "
"submission duplicates an entry in a corpus."
),
"Fine Tuning": (
"Start OpenAI fine-tuning jobs from a labelled CSV dataset and refresh "
"their status."
),
"Model Evaluation": (
"Evaluate fine-tuned models for a document and find the best-performing one."
),
"Assistants": (
"[**Deprecated**] OpenAI Assistant creation and management. This "
"feature will be removed in a future version."
Expand Down Expand Up @@ -165,8 +158,6 @@
"TTS Evaluation",
"Assessment",
"Assessment (Experimental)",
"Fine Tuning",
"Model Evaluation",
"Assistants",
"Threads",
],
Expand Down
2 changes: 1 addition & 1 deletion backend/app/api/docs/organization/delete.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ Supports two delete modes, selected by an optional request body:
```

- **`hard_delete: false` (default)** — *Soft delete.* The organization is marked **inactive** and all of its projects are deactivated as well. No data is removed, so the organization can be reactivated later. It simply stops appearing in listings and can no longer be used. Omitting the body entirely also performs a soft delete.
- **`hard_delete: true`** — *Permanent delete.* The organization and everything owned by it — projects, collections, documents, credentials, assistants, fine-tunings, and user-project mappings — are permanently removed. **This cannot be undone.**
- **`hard_delete: true`** — *Permanent delete.* The organization and everything owned by it — projects, collections, documents, credentials, assistants, and user-project mappings — are permanently removed. **This cannot be undone.**

In both modes, user **accounts are never deleted** (a user may belong to other organizations). Any user left without an active project afterwards is marked **inactive** and can no longer log in until they are added to an active project again.
Loading
Loading