new-cluster name=s1 nodes=1 disable-tenant
----

subtest restore-cleanup-with-range-tombstones

exec-sql
CREATE DATABASE restore;
CREATE SCHEMA restore.myschema;
CREATE TABLE foobar (pk int primary key);
CREATE VIEW foobar_v AS SELECT pk FROM foobar;
CREATE TABLE restore.myschema.table1 (pk int primary key);
INSERT INTO restore.myschema.table1 VALUES (1);
CREATE TYPE data.myenum AS ENUM ('hello');
----

exec-sql
BACKUP INTO 'nodelocal://1/cluster_backup';
----

new-cluster name=s2 nodes=1 share-io-dir=s1 disable-tenant
----

# Restore's OnFailOrCancel deletes descriptors which requires us to wait for no
# versions of that descriptor to be leased before proceeding. Since our test fails
# the job after the descriptors have been published, it's possible for them to be leased
# somewhere.
exec-sql
SET CLUSTER SETTING sql.catalog.descriptor_lease_duration = '1s';
----

# The GC Job sleeps between checking if a range being empty. Lowering this
# speeds up the test.
exec-sql vc=system
SET CLUSTER SETTING sql.gc_job.wait_for_gc.interval = '250ms';
----

# The protected timestamp poll interval controls how often our cache of
# protected timestamps is updated. The GC threshold can only advance as far as
# the time at which the cache was updated. We set this low so our cache is
# fresh and our range deletions are eligible for GC faster.
exec-sql vc=system
SET CLUSTER SETTING kv.protectedts.poll_interval = '250ms';
----

exec-sql
SET CLUSTER SETTING jobs.debug.pausepoints = 'restore.after_publishing_descriptors';
----

restore expect-pausepoint tag=a
RESTORE FROM LATEST IN 'nodelocal://1/cluster_backup';
----
job paused at pausepoint

exec-sql
SET CLUSTER SETTING jobs.debug.pausepoints = '';
----

# Cancel the job so that the cleanup hook runs.
job cancel=a
----

# The sleep(2) here to help ensure that the protected timestamp cache is fresh before we
# enqueue the ranges for GC. We enqueue them here, to speed up the test which would otherwise
# need to wait for them to be enqueued naturally.
#
# TODO(ssd): We sleep via the test runner and not via SQL using pg_sleep because if we try to
# execute a query too quickly we see failures. https://github.com/cockroachdb/cockroach/issues/88913
sleep ms=2000
----

exec-sql vc=system
SELECT crdb_internal.kv_enqueue_replica(range_id, 'mvccGC', true) FROM (SELECT range_id FROM crdb_internal.ranges);
----

# We should be able to restore as soon as the GC jobs complete. Without the many settings changes
# above, this would take several minutes as it relies on GC completing.
exec-sql
SHOW JOBS WHEN COMPLETE (SELECT job_id FROM [SHOW JOBS] WHERE job_type = 'SCHEMA CHANGE GC')
----

restore
RESTORE FROM LATEST IN 'nodelocal://1/cluster_backup';
----

subtest end
