Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Read a ticket's ancestors in one query

Guido Boykede30440e776e
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index 6a0e189..409388f 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -380,6 +380,7 @@ jobs:
spec/requests/organisations/tickets_name_display_spec.rb
spec/requests/organisations/tickets_selected_page_redirect_spec.rb
spec/requests/organisations/tickets_timeline_spec.rb
+ spec/requests/organisations/tickets_subtasks_spec.rb
spec/requests/ticket_list_view_columns_spec.rb
spec/requests/ticket_column_pins_spec.rb
spec/models/activity_spec.rb
@@ -654,6 +655,7 @@ jobs:
spec/services/actors/ticket_relation_actors_tenant_boundary_spec.rb
spec/services/tickets/waiting_spec.rb
spec/services/tickets/cycle_check_spec.rb
+ spec/services/tickets/ancestry_spec.rb
spec/models/ticket_relation_spec.rb
spec/services/actors/create_ticket_relation_spec.rb
spec/services/actors/destroy_ticket_relation_spec.rb
diff --git a/app/services/tickets/ancestry.rb b/app/services/tickets/ancestry.rb
new file mode 100644
index 0000000..8817c28
--- /dev/null
+++ b/app/services/tickets/ancestry.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+# Answers which tickets lie above a ticket in its sub-task tree: its ancestors, from the
+# root down to the direct parent, each an Ancestor value with id, number and project_id
+# (enough to link it). A ticket without parent has none.
+#
+# One query, a recursive CTE, because sub-tasks nest to any depth: walking parent by parent
+# from Ruby would cost one query per level, on every ticket page that shows the trail.
+#
+# It ends on bad data. Every row carries the path of ids walked so far, and a step that would
+# visit an id already on the path is not taken, so a cycle written past the model (A -> B ->
+# A, or a ticket that is its own parent) stops after each ticket was seen once. Every step
+# stays in the ticket's own project and organisation: a parent_id that points elsewhere ends
+# the walk there instead of disclosing the foreign ticket or what lies above it.
+#
+# All values travel as positional binds ($1, $2, $3), none is interpolated.
+module Tickets
+ class Ancestry
+ # A value, not a Ticket: a Ticket loaded with three columns trips its own callbacks
+ # (CustomAttributable reads custom_attributes on initialize). to_param is the id, so a
+ # route helper takes it like a ticket.
+ Ancestor = Data.define(:id, :number, :project_id) do
+ def to_param = id
+ end
+
+ def self.call(ticket:)
+ new(ticket: ticket).call
+ end
+
+ def initialize(ticket:)
+ @ticket = ticket
+ end
+
+ def call
+ return [] if @ticket.parent_id.nil?
+
+ rows = ActiveRecord::Base.connection.select_all(<<~SQL.squish, self.class.name, binds)
+ WITH RECURSIVE ancestors(id, number, project_id, parent_id, depth, path) AS (
+ SELECT tickets.id, tickets.number, tickets.project_id, tickets.parent_id, 0, ARRAY[tickets.id]
+ FROM tickets
+ WHERE tickets.id = $1 AND tickets.project_id = $2 AND tickets.organisation_id = $3
+ UNION
+ SELECT parents.id, parents.number, parents.project_id, parents.parent_id,
+ ancestors.depth + 1, ancestors.path || parents.id
+ FROM tickets AS parents
+ JOIN ancestors ON parents.id = ancestors.parent_id
+ WHERE parents.project_id = $2 AND parents.organisation_id = $3
+ AND NOT parents.id = ANY(ancestors.path)
+ )
+ SELECT id, number, project_id FROM ancestors WHERE depth > 0 ORDER BY depth DESC
+ SQL
+
+ rows.map { |row| Ancestor.new(**row.symbolize_keys) }
+ end
+
+ private
+
+ def binds
+ [@ticket.id, @ticket.project_id, @ticket.organisation_id]
+ end
+ end
+end
diff --git a/spec/services/tickets/ancestry_spec.rb b/spec/services/tickets/ancestry_spec.rb
new file mode 100644
index 0000000..baf83b4
--- /dev/null
+++ b/spec/services/tickets/ancestry_spec.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# A ticket's ancestors, root first, read in one query. These examples pin the order, the
+# single query, that a cycle written past the model cannot make the query run forever, and
+# that the walk never leaves the ticket's own project.
+RSpec.describe Tickets::Ancestry do
+ let(:organisation) { create(:organisation) }
+ let(:projects) do
+ ActsAsTenant.with_tenant(organisation) { create_list(:project, 2, organisation: organisation) }
+ end
+ let(:root) { create(:ticket, project: projects[0]) }
+ let(:level1) { create(:ticket, project: projects[0], parent: root) }
+ let(:level2) { create(:ticket, project: projects[0], parent: level1) }
+ let(:level3) { create(:ticket, project: projects[0], parent: level2) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ # Past the model, as rows written before any rule existed would be.
+ def raw_parent(ticket, parent)
+ ActiveRecord::Base.connection.execute(
+ ActiveRecord::Base.sanitize_sql_array(['UPDATE tickets SET parent_id = ? WHERE id = ?', parent.id, ticket.id])
+ )
+ end
+
+ def ancestors_of(ticket)
+ described_class.call(ticket: ticket)
+ end
+
+ it 'returns nothing for a ticket without parent' do
+ expect(ancestors_of(root)).to eq([])
+ end
+
+ it 'returns the parent of a direct child' do
+ expect(ancestors_of(level1).map(&:id)).to eq([root.id])
+ end
+
+ it 'returns every ancestor from the root down to the direct parent' do
+ expect(ancestors_of(level3).map(&:id)).to eq([root.id, level1.id, level2.id])
+ end
+
+ it 'carries id, number and project_id of each ancestor' do
+ ancestor = ancestors_of(level1).first
+
+ expect([ancestor.id, ancestor.number, ancestor.project_id]).to eq([root.id, root.number, root.project_id])
+ end
+
+ it 'asks the database once for a ticket four levels deep' do
+ ticket = level3
+
+ statements = capture_sql { ancestors_of(ticket) }
+
+ expect(statements.size).to eq(1)
+ end
+
+ it 'ends on a cycle already in the data and returns a finite list' do
+ ticket_a = root
+ ticket_b = create(:ticket, project: projects[0])
+ raw_parent(ticket_a, ticket_b)
+ raw_parent(ticket_b, ticket_a)
+ ActiveRecord::Base.connection.execute("SET LOCAL statement_timeout = '2s'")
+
+ expect(ancestors_of(ticket_a.reload).map(&:id)).to eq([ticket_b.id])
+ expect(ancestors_of(ticket_b.reload).map(&:id)).to eq([ticket_a.id])
+ end
+
+ it 'ends on a ticket that is its own parent' do
+ raw_parent(root, root)
+ ActiveRecord::Base.connection.execute("SET LOCAL statement_timeout = '2s'")
+
+ expect(ancestors_of(root.reload)).to eq([])
+ end
+
+ it 'does not return an ancestor in another project, nor anything above it' do
+ foreign_root = create(:ticket, project: projects[1])
+ foreign = create(:ticket, project: projects[1], parent: foreign_root)
+ raw_parent(root, foreign)
+
+ expect(ancestors_of(level2.reload).map(&:id)).to eq([root.id, level1.id])
+ end
+
+ it 'does not return an ancestor of another organisation, even one claiming the same project' do
+ other_org = create(:organisation)
+ foreign = ActsAsTenant.with_tenant(other_org) do
+ create(:ticket, project: create(:project, organisation: other_org))
+ end
+ # Only the organisation clause can tell this row apart: its project_id matches.
+ ActiveRecord::Base.connection.execute(
+ ActiveRecord::Base.sanitize_sql_array(['UPDATE tickets SET project_id = ?, number = 9999 WHERE id = ?', root.project_id, foreign.id])
+ )
+ raw_parent(root, foreign)
+
+ expect(ancestors_of(level1.reload).map(&:id)).to eq([root.id])
+ end
+end