Skip to content

Commit c8fc2f4

Browse files
committed
feat(connector): Add warning log for MV read permission fallback
When reading a Materialized View without 'bigquery.tables.getData' permission, the connector silently falls back to re-executing the view's query. This is opaque to the user and causes unexpected costs and poor performance, which are difficult to diagnose. This change introduces a try-catch block to detect a permission-denied error (HTTP 403) when attempting a direct read of a Materialized View. If this specific error is caught, a detailed WARN message is logged, explaining the cause of the fallback and instructing the user how to resolve it by granting the 'roles/bigquery.dataViewer' role. A new integration test, MaterializedViewReadIT, has been added to verify this behavior by impersonating a service account with insufficient permissions and asserting that the warning is logged. This significantly improves the supportability and user experience of the connector by making the fallback behavior transparent and empowering users to self-resolve the underlying permissions issue. Related to: https://issuetracker.google.com/296281345 Related to: dataform-co/dataform#1640 Resolves #1401
1 parent 79d320f commit c8fc2f4

File tree

3 files changed

+187
-1
lines changed

3 files changed

+187
-1
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,8 @@ AdAdHocITSuite.scala
3838

3939
# toolchains file
4040
toolchains.xml
41+
42+
# Emacs
43+
*~
44+
\#*\#
45+
.\#*

bigquery-connector-common/src/main/java/com/google/cloud/bigquery/connector/common/ReadSessionCreator.java

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import static com.google.cloud.bigquery.connector.common.BigQueryErrorCode.UNSUPPORTED;
1919
import static java.lang.String.format;
2020

21+
import com.google.cloud.bigquery.BigQueryException;
2122
import com.google.cloud.bigquery.TableDefinition;
2223
import com.google.cloud.bigquery.TableId;
2324
import com.google.cloud.bigquery.TableInfo;
@@ -47,6 +48,7 @@ public class ReadSessionCreator {
4748
public static final int DEFAULT_MAX_PARALLELISM = 20_000;
4849
public static final int MINIMAL_PARALLELISM = 1;
4950
public static final int DEFAULT_MIN_PARALLELISM_FACTOR = 3;
51+
private static final String ACCESS_DENIED_REASON = "accessDenied";
5052

5153
private static final Logger log = LoggerFactory.getLogger(ReadSessionCreator.class);
5254
private static boolean initialized = false;
@@ -92,8 +94,48 @@ public ReadSessionResponse create(
9294
TableId table, ImmutableList<String> selectedFields, Optional<String> filter) {
9395
Instant sessionPrepStartTime = Instant.now();
9496
TableInfo tableDetails = bigQueryClient.getTable(table);
97+
98+
if (tableDetails.getDefinition().getType() == TableDefinition.Type.MATERIALIZED_VIEW) {
99+
try {
100+
// Attempt to read the Materialized View directly. This will fail if the required
101+
// permissions are not present.
102+
return createReadSession(
103+
tableDetails, tableDetails, selectedFields, filter, sessionPrepStartTime);
104+
} catch (BigQueryException e) {
105+
if (!isPermissionDeniedError(e)) {
106+
// Not a permission error, so re-throw it.
107+
throw e;
108+
}
109+
// This is a permission error. Log a warning and fall back to materializing the view.
110+
log.warn(
111+
"Failed to initiate a direct read from Materialized View '{}' due to a permission"
112+
+ " error. The service account likely lacks 'bigquery.tables.getData'"
113+
+ " permission. Falling back to re-executing the view's underlying query. This"
114+
+ " will incur additional BigQuery costs and impact performance. For optimal"
115+
+ " performance, grant the 'roles/bigquery.dataViewer' role to the principal at"
116+
+ " the dataset or table level.",
117+
tableDetails.getTableId().toString());
118+
// Execution will now fall through to the getActualTable() call below.
119+
}
120+
}
121+
95122
TableInfo actualTable = getActualTable(tableDetails, selectedFields, filter);
123+
return createReadSession(
124+
actualTable, tableDetails, selectedFields, filter, sessionPrepStartTime);
125+
}
126+
127+
private boolean isPermissionDeniedError(BigQueryException e) {
128+
return e.getCode() == java.net.HttpURLConnection.HTTP_FORBIDDEN
129+
&& e.getError() != null
130+
&& ACCESS_DENIED_REASON.equals(e.getError().getReason());
131+
}
96132

133+
private ReadSessionResponse createReadSession(
134+
TableInfo actualTable,
135+
TableInfo tableDetails,
136+
ImmutableList<String> selectedFields,
137+
Optional<String> filter,
138+
Instant sessionPrepStartTime) {
97139
BigQueryReadClient bigQueryReadClient = bigQueryReadClientFactory.getBigQueryReadClient();
98140
log.info(
99141
"|creation a read session for table {}, parameters: "
@@ -203,7 +245,7 @@ public ReadSessionResponse create(
203245
if (config.isReadSessionCachingEnabled()
204246
&& getReadSessionCache().asMap().containsKey(createReadSessionRequest)) {
205247
ReadSession readSession = getReadSessionCache().asMap().get(createReadSessionRequest);
206-
log.info("Reusing read session: {}, for table: {}", readSession.getName(), table);
248+
log.info("Reusing read session: {}, for table: {}", readSession.getName(), actualTable);
207249
return new ReadSessionResponse(readSession, actualTable);
208250
}
209251
ReadSession readSession = bigQueryReadClient.createReadSession(createReadSessionRequest);
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
/*
2+
* Copyright 2025 Google LLC and Contributors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.google.cloud.spark.bigquery.integration;
17+
18+
import static com.google.common.truth.Truth.assertThat;
19+
20+
import com.google.cloud.bigquery.JobInfo;
21+
import com.google.cloud.bigquery.QueryJobConfiguration;
22+
import com.google.cloud.bigquery.TableId;
23+
import com.google.cloud.spark.bigquery.ReadSessionCreator;
24+
import com.google.cloud.spark.bigquery.connector.common.integration.IntegrationTestUtils;
25+
import com.google.cloud.spark.bigquery.connector.common.integration.SparkBigQueryIntegrationTestBase;
26+
import java.io.StringWriter;
27+
import java.util.Arrays;
28+
import java.util.List;
29+
import java.util.UUID;
30+
import java.util.stream.Collectors;
31+
import org.apache.log4j.Level;
32+
import org.apache.log4j.Logger;
33+
import org.apache.log4j.SimpleLayout;
34+
import org.apache.log4j.WriterAppender;
35+
import org.apache.spark.sql.Dataset;
36+
import org.apache.spark.sql.Row;
37+
import org.junit.After;
38+
import org.junit.Before;
39+
import org.junit.Test;
40+
41+
public class MaterializedViewReadIT extends SparkBigQueryIntegrationTestBase {
42+
43+
private final Logger logger = Logger.getLogger(ReadSessionCreator.class);
44+
private WriterAppender appender;
45+
private StringWriter stringWriter;
46+
private String testDataset;
47+
private String mvName;
48+
private TableId sourceTableId;
49+
private String testServiceAccount;
50+
51+
@Before
52+
public void setUp() throws InterruptedException {
53+
// Set up a custom log appender to capture logs
54+
stringWriter = new StringWriter();
55+
appender = new WriterAppender(new SimpleLayout(), stringWriter);
56+
appender.setThreshold(Level.WARN);
57+
logger.addAppender(appender);
58+
59+
// Create a dedicated service account for this test
60+
String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
61+
assertThat(projectId).isNotNull();
62+
testServiceAccount =
63+
String.format(
64+
"mv-test-%s@%s.iam.gserviceaccount.com",
65+
UUID.randomUUID().toString().substring(0, 8), projectId);
66+
IntegrationTestUtils.createServiceAccount(testServiceAccount);
67+
68+
// Create a temporary dataset and grant the new SA the BQ User role
69+
// This provides permissions to run jobs (for the fallback) but not to read table data directly
70+
testDataset = "mv_read_it_" + System.nanoTime();
71+
IntegrationTestUtils.createDataset(testDataset);
72+
IntegrationTestUtils.grantServiceAccountRole(
73+
testServiceAccount, "roles/bigquery.user", testDataset);
74+
IntegrationTestUtils.grantServiceAccountRole(
75+
testServiceAccount, "roles/bigquery.metadataViewer", testDataset);
76+
77+
// Create a source table
78+
sourceTableId = TableId.of(testDataset, "source_table_" + System.nanoTime());
79+
IntegrationTestUtils.createTable(sourceTableId, "name:string, value:integer", "name,value");
80+
81+
// Create a Materialized View
82+
mvName = "test_mv_" + System.nanoTime();
83+
String createMvSql =
84+
String.format(
85+
"CREATE MATERIALIZED VIEW `%s.%s` AS SELECT name, value FROM `%s.%s`",
86+
testDataset, mvName, testDataset, sourceTableId.getTable());
87+
QueryJobConfiguration createMvJob = QueryJobConfiguration.newBuilder(createMvSql).build();
88+
bigquery.create(JobInfo.of(createMvJob)).waitFor();
89+
}
90+
91+
@After
92+
public void tearDown() {
93+
logger.removeAppender(appender);
94+
try {
95+
if (testDataset != null) {
96+
IntegrationTestUtils.deleteDatasetAndTables(testDataset);
97+
}
98+
} finally {
99+
if (testServiceAccount != null) {
100+
IntegrationTestUtils.deleteServiceAccount(testServiceAccount);
101+
}
102+
}
103+
}
104+
105+
@Test
106+
public void testReadMaterializedView_lackingPermission_logsWarningAndFallsBack() {
107+
// This test confirms that when reading a Materialized View with a service account
108+
// that lacks `bigquery.tables.getData` permission, the connector:
109+
// 1. Logs a specific WARN message indicating the permission issue and the fallback.
110+
// 2. Successfully reads the data by falling back to materializing the view's query.
111+
112+
// Arrange: Use the dedicated service account with insufficient permissions for a direct read.
113+
String mvToRead = testDataset + "." + mvName;
114+
115+
// Act: Read the materialized view, impersonating the test service account
116+
Dataset<Row> df =
117+
spark
118+
.read()
119+
.format("bigquery")
120+
.option("viewsEnabled", "true") // Required to read any kind of view
121+
.option("impersonationServiceAccount", testServiceAccount)
122+
.load(mvToRead);
123+
124+
List<Row> result = df.collectAsList();
125+
126+
// Assert
127+
// 1. Assert that the read was successful via fallback
128+
assertThat(result).hasSize(2);
129+
List<String> names = result.stream().map(row -> row.getString(0)).collect(Collectors.toList());
130+
assertThat(names).containsExactlyElementsIn(Arrays.asList("name1", "name2"));
131+
132+
// 2. Assert that the specific warning was logged
133+
String logOutput = stringWriter.toString();
134+
assertThat(logOutput).contains("Failed to initiate a direct read from Materialized View");
135+
assertThat(logOutput)
136+
.contains("The service account likely lacks 'bigquery.tables.getData' permission");
137+
assertThat(logOutput).contains("Falling back to re-executing the view's underlying query");
138+
}
139+
}

0 commit comments

Comments
 (0)